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 |
|---|---|---|---|---|---|
#include <qgssymbollayerv2utils.h>
Blurs an image in place, e.g.
creating Qt-independent drop shadows
Attempts to parse mime data as a color.
Attempts to parse mime data as a list of named colors.
Creates mime data from a list of named colors.
Creates mime data from a color.
Sets both the mime data's color data, and the mime data's text with the color's hex code.
Returns a friendly display name for a color.
Creates a render context for a pixel based device.
Returns the maximum estimated bleed for the symbol.
Return a field name if the whole expression is just a name of the field .
Returns full expression string if the expression is more complex than just one field. Using just expression->expression() method may return quoted field name, but that is not wanted for saving (due to backward compatibility) or display in GUI.
Return a new valid expression instance for given field or expression string.
If the input is not a valid expression, it is assumed that it is a field name and gets properly quoted. If the string is empty, returns null pointer. This is useful when accepting input which could be either a non-quoted field name or expression.
Imports colors from a gpl GIMP palette file.
Returns the line width scale factor depending on the unit and the paint device.
Return a list of all available svg files.
Return a list of svg files at the specified directory.
Multiplies opacity of image pixel values with a (global) transparency value.
Create ogr feature style string for brush.
Create ogr feature style string for pen.
Attempts to parse a string as a color using a variety of common formats, including hex codes, rgb and rgba strings.
Attempts to parse a string as a list of colors using a variety of common formats, including hex codes, rgb and rgba strings.
Attempts to parse a string as a color using a variety of common formats, including hex codes, rgb and rgba strings.
Returns scale factor painter units -> pixel dimensions.
Calculate whether a point is within of a QPolygonF.
Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point.
Calculate the centroid point of a QPolygonF.
Calculate a point within of a QPolygonF.
Converts a QColor into a premultiplied ARGB QColor value using a specified alpha value.
Exports colors to a gpl GIMP palette file.
Sorts the passed list in requested order.
Get symbol's path from its name.
If the name is not absolute path the file is searched in SVG paths specified in settings svg/searchPathsForSVG.
Get symbols's name from its path. | http://www.qgis.org/api/classQgsSymbolLayerV2Utils.html | CC-MAIN-2014-41 | refinedweb | 448 | 67.96 |
Unless you are a biblically familiar with COM, prior to .NET creating applications that were written
in multiply languages was quite the chore. XML based Web Services are becoming a very popular method to transfer
information between distributed systems, even thought web services themselves have been around well before
the .NET Framework was introduced. The .NET Framework allows us to quickly develop web services even
when multiple languages are introduced to the formula. The purpose of this article is two fold: I wanted to
learn a little more about Managed C++, and thought that writing the core database portion in Managed C++ would be a
great learning experience, while exposing the functionality to a C# web service. I had not actually written
a web service before and so I thought tying the two together would make a nice example. I will go ahead and
try to explain everything; however being familiar with concepts of classes themselves in C++ is helpful. Someone recently asked if it was possible for multiple languages to work together under .NET within one program, hopefully this example should identify this possibility.
We need to begin by creating a new Managed C++ assembly; this is where the majority of the
actual work will reside. If you are remotely familiar with C# you will notice that Managed
C++ uses a similar notation to include namespaces, however it is slightly different. For our
assembly we will need to include the following namespaces (This is listed in the mcpp.h header file):
using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Xml;
In Managed C++ we also have to identify the files that the namespaces reside in,
this is done using the #using statement, somewhat similar to the #include
for including header files with standard C++.
We will need to include the following files for our example project under the Stdafx.h header file.
#using <mscorlib.dll>
#using <System.dll>
#using <system.data.dll>
#using <System.Xml.dll>
When we created our project you will see that Visual Studio.NET created a base class called MyNumber.
The next step is to locate the header file that contains our class description and add a
function prototype to identify our new method, which we will use to get data from SQL Server.
You will find the mcpp.h header file contains out class framework. Upon opening up this file you should
see an initial class declaration that looks something like this, I have gone ahead and added the prototype below:
MyNumber
namespace mcpp
{
public __gc class MyNumber
{
// TODO: Add your methods for this class here.
public:
int GetWebStat(); <font color="green">// Add this function prototype</font>
};
}
Now we will need to add the implementation to this function in the mcpp.cpp file located inside your project.
int mcpp::MyNumber::GetWebStat()
{
SqlConnection* mySQLConnection;
SqlCommand* sqlCommand;
SqlDataReader* dr;
String* sql;
int i;
try
{
sql = S"select count(*) as myCount from site_stats";
// Assign our connection object with the connection string.
mySQLConnection = new SqlConnection(S"server=[YourServerName];" +
"database=[YourDatabaseName];" +
"Integrated Security=yes;");
// Open the databse connection.
mySQLConnection->Open ();
// Tie the SqlCommand object to our connection and SQL statement.
sqlCommand = new SqlCommand(sql, mySQLConnection);
// Fills the SqlDataReader with content.
dr = sqlCommand->ExecuteReader();
while(dr->Read())
{
i = Convert::ToInt32(dr->get_Item(S"myCount")->ToString());
}
return i;
}
catch(Exception* e)
{
Console::Write(e->ToString());
}
__finally
{
mySQLConnection->Close();
}
}
Now you can build and compile this assembly into your .DLL, which is all we will
need to do in the Managed C++ world.
The next step is to create a new Web Service in C# to expose the functionality
we just wrote into our Managed C++ assembly. You will need to load up Visual Studio.NET and
select choose ASP.NET Web Service as the project template.
To incorporate the Managed C++ assembly into our C# project we will need to do two things.
First, go to Projects and select "Add Reference". A dialog will load and you will need to select
"Browse" in the upper right hand corner. You will need to select the assembly .DLL from the
Managed C++ project, this is located in either the Debug or Release folder depending on how you
built your release. At the top of the code where all of the using statements are located identifying
all the namespaces in the project, include the following:
using mccp;
This was the name of the namespace that the Managed C++ assembly used earlier.
Now we simply add a new method in C# and create an instance of our Managed C++ class,
it's really that simple. Refer to the following code as an example for the
remaining C# source to the web service. What really becomes interesting is that if you have worked
with Windows Forms in C# your class declaration no longer inherits from System.Windows.Forms.Form
but from System.Web.Services.WebService instead. Once you have added the following function to your
C# code you can save and build the project. If you have never worked with XML based web services before,
Chris Maunder has written Your first C# Web Service
[^] which
is a nice source for additional information. You may need to map a virtual directory to your web server as I did for this
example.
System.Windows.Forms.Form
System.Web.Services.WebService
[WebMethod(Description="This is an implementation of a" +
" cross language web service between Managed C++ and C#.")]
public int MyWebStats()
{
int i;
<font color="green">// Create an instance of our MC++ class.</font>
mcpp.MyNumber m = new mcpp.MyNumber();
<font color="green">// Simply call the method from our class object.</font>
i = m.GetWebStat();
return i;
}
The ability to consumer these new XML based Web Services in our applications can add a great level of extensibility to any application. I have included another project that consumes this web service we have demonstrated. To include a Web Service in your project you will need to select "Add Web Reference" by right-clicking on the References in your project. This will load a dialog for you to locate your Web Service. You can enter the following URL to find my example service in your dialog:. As soon as the service is located you can hit the "Add Reference" button at the bottom right corner. I created a simple form and added the following code to gain access to our new Web Service; amazingly the plumbing is taken care of for us.
private void button1_Click(object sender, System.EventArgs e)
{
this.label2.Text = "Checking...";
this.label2.Refresh();
// Creates an instance of our class.
com.developernotes. stats = new com.developernotes.;
// Calls our method and assigns the return value to our label.
this.label2.Text = stats.MyWebStats().ToString();
}
A live example can be seen here running on my website to show the returning XML feed:
Live XML Web Service Example
This simple example should be enough to show you how easily the .NET Framework allows
multiple languages to talk to each other with ease and without the granularity COM introduces.
Any question, comments, or flames can be posted. | http://www.codeproject.com/Articles/3310/Cross-Language-Web-Service-Implementation?msg=732255 | CC-MAIN-2015-40 | refinedweb | 1,182 | 55.44 |
An Introduction to Functional Programming
Why is functional programming useful? Functional programming constructs have popped up in all major programming languages in the past decade. Programmers have enjoyed their benefits—simplified loops, more expressive code, and simple parallelization. But there's more to it—decoupling from time, enabling opportunities to remove duplication, composability, and a simpler design. Higher adoption of functional programming (including the large-scale adoption of Scala in the financial sector) means more opportunities for you once you know and understand it. While we will take a deep dive into functional programming in this book to help you learn, remember that functional programming is another tool to add to your toolbox—one that you can choose to use when the problem and the context fits.
The following topics will be covered in this chapter:
- An introduction to functional programming and an examination of how you've already been using functional constructs
- Structured loops versus functional loops
- Immutability
- Object-oriented programming (OOP) versus functional design
- Composability and removing duplication
Technical requirements
The code works with g++ 7.3.0 and C++ 17; it includes a makefile for your convenience. You can find it in the GitHub repository () in the Chapter01 directory.
An introduction to functional programming
My first experience with functional programming was at university. I was a 20-year-old geek who was interested in Sci-Fi, reading, and programming; programming was the highlight of my academic life. Everything to do with C++, Java, MATLAB, and a few other programming languages that we used was fun for me. Unfortunately, I can't say the same thing about the disciplines around electrical engineering, circuits, or compiler theory. I just wanted to write code!
Based on my interests, functional programming should have been a very fun course for me. Our teacher was very passionate. We had to write code. But something went wrong—I didn't click with what the teacher was telling us. Why were lists so interesting? Why was the syntax so backward and full of parentheses? Why would I use these things when it was much simpler to write the same code in C++? I ended up trying to translate all the programming constructs I knew from BASIC and C++ into Lisp and OCaml. It completely missed the point of functional programming, but I passed the course and forgot about it for many years.
I imagine that many of you can relate to this story, and I have a possible reason for this. I now believe that my teacher, despite being extremely passionate, used the wrong approach. Today, I understand that functional programming has a certain elegance at its core, due to its strong relationship with mathematics. But that elegance requires a sense of insightful observation that I didn't have when I was 20, that is, a sense that I was lucky to build on after years of various experiences. It's obvious to me now that learning functional programming shouldn't be related to the ability of the reader to see this elegance.
So, what approach could we use instead? Thinking about the past me, that is, the geek who just wanted to write code, there's only one way to go—look at the common problems in code and explore how functional programming reduces or removes them entirely. Additionally, start from the beginning; you've already seen functional programming, you've already used some of the concepts and constructs, and you might have even found them very useful. Let's examine why.
Functional programming constructs are everywhere
Around 10 years after I finished the university functional programming course, I had a casual chat with my friend, Felix. As any two geeks, we would rarely see each other, but we had, for years, an ongoing conversation on instant messaging discussing all kinds of nerdy topics and, of course, programming.
Somehow, the topic of functional programming came up. Felix pointed out that one of my favorite and most enjoyable programming languages, LOGO, was, in fact, a functional programming language.
It was obvious in retrospect; here is how to write a function that draws a square in the KTurtle version of LOGO:
learn square {
repeat 4 {forward 50 turnright 90}
}
The result is shown in the following screenshot:
Can you see how we're passing two lines of code to the repeat function? That's functional programming! A fundamental tenet of functional programming is that code is just another type of data, which can be packed in a function and passed around to other functions. I used this construct in LOGO hundreds of times without making the connection.
This realization made me think: could there be other functional programming constructs that I've used without knowing? As it turns out, yes, there were. In fact, as a C++ programmer, you've most likely used them as well; let's take a look at a few examples:
int add(const int base, const int exponent){
return pow(base, exponent);
}
This function is a typical example of recommended C++ code. I first learned about the benefits of adding const everywhere from the amazing books of Bertrand Meyer: Effective C++, More Effective C++, and Effective STL. There are multiple reasons this construct works well. First, it protects the data members and parameters that shouldn't change. Second, it allows a programmer to reason more easily about what happens in the function by removing possible side effects. Third, it allows the compiler to optimize the function.
As it turns out, this is also an example of immutability in action. As we'll discover in the following chapters, functional programming places immutability at the core of the programs, moving all side effects to the edges of the program. We already know the basic construct of functional programming; to say that we use functional programming just means to use it much more extensively!
Here's another example from STL:
std::vector aCollection{5, 4, 3, 2, 1};
sort (aCollection.begin(), aCollection.end());
The STL algorithms have great power; this power comes from polymorphism. I'm using this term in a more fundamental sense than in OOP—it merely means that it doesn't matter what the collection contains, because the algorithm will still work fine as long as a comparison is implemented. I have to admit that when I first understood it, I was impressed by the smart, effective solution.
There's a variant of the sort function that allows the sorting of elements even when the comparison is not implemented, or when it doesn't work as we'd like; for example, when we are given a Name structure, as follows:
using namespace std;
// Parts of code omitted for clarity
struct Name{
string firstName;
string lastName;
};
If we'd like to sort a vector<Name> container by first name, we just need a compare function:
bool compareByFirstName(const Name& first, const Name& second){
return first.firstName < second.firstName;
}
Additionally, we need to pass it to the sort function, as shown in the following code:
int main(){
vector<Name> names = {Name("John", "Smith"), Name("Alex",
"Bolboaca")};
sort(names.begin(), names.end(), compareByFirstName);
}
// The names vector now contains "Alex Bolboaca", "John Smith"
This makes a kind of higher-order function. A high-level function is a function that uses other functions as parameters in order to allow higher levels of polymorphism. Congratulations—you've just used a second functional programming construct!
I will go as far as to state that STL is a good example of functional programming in action. Once you learn more about functional programming constructs, you'll realize that they are used everywhere in STL. Some of them, such as function pointers or functors, have been in the C++ language for a very long time. In fact, STL has stood the test of time, so why not use similar paradigms in our code as well?
There's no better example to support this statement other than the functional loops present in STL.
Structured loops versus functional loops
It's hardly a surprise that one of the first things that we learn as programmers is how to write a loop. One of my first loops in C++ was printing the numbers from 1 to 10:
for(int i = 0; i< 10; ++i){
cout << i << endl;
}
As a curious programmer, I took this syntax for granted, went over its peculiarities and complications, and just used it. Looking back, I realize that there are a few unusual things about this construct. First, why start with 0? I've been told it's a convention, due to historical reasons. Then, the for loop has three statements—an initialization, a condition, and an increment. This sounds slightly too complicated for what we're trying to achieve. Finally, the end condition forced me into more off-by-one errors than I'd like to admit.
At this point, you will realize that STL allows you to use iterators when looping over collections:
for (list<int>::iterator it = aList.begin(); it != aList.end(); ++it)
cout << *it << endl;
This is definitely better than the for loop using a cursor. It avoids off-by-one errors and there are no 0 convention shenanigans. There's still a lot of ceremony around the operation, however. Even worse is that the loop tends to grow as the complexity of the program grows.
There's an easy way to show this symptom. Let's take a look back at the first problems that I've solved using loops.
Let's consider a vector of integers and compute their sum; the naive implementation will be as follows:
int sumWithUsualLoop(const vector<int>& numbers){
int sum = 0;
for(auto iterator = numbers.begin(); iterator < numbers.end();
++iterator){
sum += *iterator;
}
return sum;
}
If only production code was so simple! Instead, the moment we implement this code, we'll get a new requirement. We now need to sum only the even numbers from the vector. Hmm, that's easy enough, right? Let's take a look at the following code:
int sumOfEvenNumbersWithUsualLoop(const vector<int>& numbers){
int sum = 0;
for(auto iterator = numbers.begin(); iterator<numbers.end();
++iterator){
int number = *iterator;
if (number % 2 == 0) sum+= number;
}
return sum;
}
If you thought this is the end, it's not. We now require three sums for the same vector—one of the even numbers, one of the odd numbers, and one of the total. Let's now add some more code, as follows:
struct Sums{
Sums(): evenSum(0), oddSum(0), total(0){}
int evenSum;
int oddSum;
int total;
};
const Sums sums(const vector<int>& numbers){
Sums theTotals;
for(auto iterator = numbers.begin(); iterator<numbers.end();
++iterator){
int number = *iterator;
if(number % 2 == 0) theTotals.evenSum += number;
if(number %2 != 0) theTotals.oddSum += number;
theTotals.total += number;
}
return theTotals;
}
Our loop, which initially started relatively simple, has become more and more complex. When I first started professional programming, we used to blame users and clients who couldn't make up their minds about the perfect feature and give us the final, frozen requirements. That's rarely possible in reality, however; our customers learn new things every day from the interaction of users with the programs we write. It's up to us to make this code clear, and it's possible with functional loops.
Years later, I learned Groovy. A Java virtual machine-based programming language, Groovy focuses on making the job of programmers easier by helping them to write less code and avoid common errors. Here's how you could write the previous code in Groovy:
def isEven(value){return value %2 == 0}
def isOdd(value){return value %2 == 1}
def sums(numbers){
return [
evenSum: numbers.filter(isEven).sum(),
oddSum: numbers.filter(isOdd).sum(),
total: numbers.sum()
]
}
Let's compare the two for a moment. There's no loop. The code is extremely clear. There's no way to make off-by-one errors. There's no counter, so, therefore, there is no starting from 0 weirdness. Additionally, there's no scaffolding around it—I just write what I want to achieve, and a trained reader can easily understand it.
While the C++ version is more verbose, it allows us to achieve the same goals:;
}
There's still a lot of ceremony though, and too much code similarity. So, let's get rid of it, as follows:;
}
We've just replaced a complex for loop with a number of simpler, more readable, and composable functions.
So, is this code better? Well, that depends on your definition of better. I like to think of any implementation in terms of advantages and disadvantages. The advantages of functional loops are simplicity, readability, reduced code duplication, and composability. Are there any disadvantages? Well, our initial for loop only requires one pass through the vector, while our current implementation requires three passes. This can be a burden for very large collections, or when response time and memory usage are very important. This is definitely worth discussing, and we will examine it in more detail in Chapter 10, Performance Optimization, which is focused solely on performance optimization for functional programming. For now, I recommend that you focus on understanding the new tool of functional programming.
In order to do that, we need to revisit immutability.
Immutability
We've already understood that a certain level of immutability is preferred in C++; the common example is as follows:
class ...{
int add(const int& first, const int& second) const{
return first + second;
}
}
The const keyword clearly communicates a few important constraints on the code, such as the following:
- The function does not change any of its arguments before returning.
- The function does not change any data member of the class it belongs to.
Let's now imagine an alternate version of add, as follows
int uglyAdd(int& first, int& second){
first = first + second;
aMember = 40;
return first;
}
I called this uglyAdd for a reason—I don't tolerate code like this when I'm programming! This function violates the principle of minimal surprise and does too many things. Reading the function code reveals nothing about its intent. Imagine the surprise of the caller, if not careful, then, just by calling an add function, two things changed—one in the parameters passed, and the second in the class where the function is located.
While this is an extreme example, it contributes to an argument for immutability. Immutable functions are boring; they receive data, change nothing in the received data, change nothing in the class containing them, and return a value. When it comes to maintaining code over long periods of time, however, boring is good.
Immutability is the core property of functions in functional programming. Of course, there's at least one part of your program that cannot be immutable—input/output (I/O). We will accept I/O for what it is, and we will focus on increasing the immutability of our code as much as possible.
Now, you are probably wondering whether you have to completely rethink the way you write programs. Should you forget all that you learned about OOP? Well, not really, and let's see why.
OOP versus functional design styles
An important part of my job is to work with programmers and help them to improve the way they write code. To do so, I try my best to come up with simple explanations for complex ideas. I have one such explanation for software design. Software design is, for me, the way we structure the code such that we optimize it for business purposes.
I like this definition because it's plain and short. But one thing bugged me after I started experimenting with functional constructs; that is, functional programming leads to code such as the following:
const Sums sumsWithFunctionalLoopsSimplified(const vector<int>& numbers){
Sums theTotals(
sum(filter(numbers, isEven)),
sum(filter(numbers, isOdd)),
sum(numbers)
);
return theTotals;
}
Writing similar code in OOP style would most likely mean creating classes and using inheritance. So, which style is better? Additionally, if software design is about code structure, is there an equivalence between the two styles?
First, let's take a look at what the two design styles really promote. What is OOP? For many years, I believed all the books that listed the following three properties of object-oriented languages:
- Encapsulation
- Inheritance
- Polymorphism
Alan Kay, the thinker behind OOP, does not really agree with this list. For him, OOP is about communication between many small objects. As a biology major, he saw an opportunity to organize programs like the body organizes cells, and to allow objects to communicate much like cells do. He places more importance on objects over classes, and on communication over the commonly listed OOP properties. I would best summarize his position as follows: the dynamic relations in the system are more important than its static properties.
This changes a lot about the OOP paradigm. So, should classes match the real world? Not really. They should be optimized for the representation of the real world. Should we focus on having clear, well-thought out class hierarchies? No, since those are less important than the communication between objects. What is the smallest object that we can think of? Well, either a combination of data, or a function.
In a recent answer on Quora (), Alan Kay stated an interesting idea when answering a question on functional programming. Functional programming came from mathematics and from an effort to model the real world in order to enable artificial intelligence. This effort hit the following problem—Alex is in Bucharest and Alex is in London can both be true, but at different points in time. The solution to this modeling issue is immutability; that is, time becomes a parameter to functions, or a data member in the data structures. In any program, we can model data changes as time-bound versions of the data. Nothing stops us from modeling the data as small objects, and the changes as functions. Additionally, as we will see later, we can easily turn functions into objects and vice versa.
So, to summarize, there's no real tension between OOP as Alan Kay meant it and functional programming. We can use them together and interchangeably, as long as we focus on increasing the immutability of our code, and on small objects that communicate with one another. We'll discover, in the following chapters, how easy it is to replace a class with functions and vice versa.
But there are many ways to use OOP that are different from Alan Kay's vision. I've seen a lot of C++ code with my clients, and I've seen it all—big functions, huge classes, and deep inheritance hierarchies. Most of the time, the reason I'm called is because the design is too hard to change and because adding new features slows down to a crawl. Inheritance is a very strong relationship and overusing it leads to strong coupling, and, therefore, to code that's difficult to change. Long methods and long classes are harder to understand and harder to change. Of course, there are situations when inheritance and long classes make sense, but, in general, going for small objects with loose coupling enables changeability.
But classes can be reused, can't they? Can we do that with functions? Let's visit this topic next.
Composability and removing duplication
We have already seen an example of where we had a fair amount of duplication:;
}
We managed to reduce it using functions, as shown in the following code:;
}
It's interesting to see how the functions are composed in various ways; we have sum(filter()) called twice, and sum() called once. Moreover, filter can be used with multiple predicates. Additionally, with a bit of work, we can make both filter and sum polymorphic functions:
template<class CollectionType, class UnaryPredicate>
const CollectionType filter(const CollectionType& input, UnaryPredicate filterFunction){
CollectionType filtered;
copy_if(input.begin(), input.end(), back_inserter(filtered),
filterFunction);
return filtered;
}
template<typename T, template<class> class CollectionType>
const T sum(const CollectionType<T>& input, const T& init = 0){
return accumulate(input.begin(), input.end(), init);
}
It's now easy to call filter and sum with arguments of type other than vector<int>. The implementation is not perfect, but it illustrates the point that I'm trying to make, that is, small, immutable functions can easy become polymorphic and composable. This works especially well when we can pass functions to other functions.
Summary
We've already covered a lot of interesting topics! You've just realized that you know the basics of functional programming. You can write immutable functions in C++ with the help of the const keyword. You've already used high-level functions from STL. Additionally, you don't have to forget anything about OOP, but, instead, just see it from a different perspective. Finally, we discovered how small immutable functions can be composed to offer complex functionality, and how they can become polymorphic with the help of C++ templates.
It's now time to take an in-depth look at the building blocks of functional programming and learn how to use them in C++. This includes pure functions, lambdas, and operations with functions such as functional composition, currying, or partial functional application.
Questions
- What is an immutable function?
- How do you write an immutable function?
- How do immutable functions support code simplicity?
- How do immutable functions support simple design?
- What is a high-level function?
- What example of high-level function can you give from STL?
- What are the advantages of functional loops over structured loops? What are the potential disadvantages?
- What is OOP from the perspective of Alan Kay? How does it relate to functional programming? | https://www.packtpub.com/product/hands-on-functional-programming-with-c/9781789807332 | CC-MAIN-2020-50 | refinedweb | 3,615 | 54.32 |
Redirect any URL to the correct Angular route when using ASP.NET Core 1 and HTML5 routing. If you’re using Angular 2 with ASP.NET static file serving, you’ll have no doubt run into the fact that once you’ve navigated to a different Angular route, you can’t refresh the page. You’ll get a 404 error because the new URL no longer points to a valid file.
Instead we want to route all requests for Angular routes to the root page, usually index.html. Angular will then go figure out which page to load based on the URL.
Angular 2 Middleware for ASP.NET Core
Here is what you need to put into your
startup.cs to get your Angular 2 app served correctly.
public class Startup { public void Configure(IApplicationBuilder app, IApplicationEnvironment environment) { // Route all unknown requests to app root app.Use(async (context, next) => { await next(); // If there's no available file and the request doesn't contain an extension, we're probably trying to access a page. // Rewrite request to use app root if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) { context.Request.Path = "/app/index.html"; // Put your Angular root page here context.Response.StatusCode = 200; // Make sure we update the status code, otherwise it returns 404 await next(); } }); // Serve wwwroot as root app.UseFileServer(); // Serve /node_modules as a separate root (for packages that use other npm modules client side) app.UseFileServer(new FileServerOptions() { // Set root of file server FileProvider = new PhysicalFileProvider(Path.Combine(environment.ApplicationBasePath, "node_modules")), // Only react to requests that match this path RequestPath = "/node_modules", // Don't expose file system EnableDirectoryBrowsing = false }); } }
Ok that’s cool, but let’s breakdown the code to see what’s going on.
Custom ASP.NET Core Middleware
The first
app.use is a piece of custom middleware, which is really just a fancy way of saying a method that we’re adding to the Request/Response pipeline.
contextis the HttpContext of the request/response.
nextis the next piece of middleware in the pipeline.
Since we added our middleware at the top, it means we’re the first to see the request, and the last to see the response.
The first line
await next(); immediately passes the request off to the next piece of middleware in the pipeline. This is because we don’t know if we need to take any action yet.
Instead, we wait for the call to return, which means that the rest of the pipeline has processed the request AND the response. Once we have the response, we check to see if it was a 404. We also check to see if there’s an extension. This is to make sure the request was for a page, and not just a missing picture or something.
If we think they’re trying to reach a page that doesn’t exist, we assume they’re trying to hit an Angular route, so we alter the request path to the root of the application and send the request back down the pipeline. You should be careful here, especially with logging, as all of the middleware below us will think it’s a new request.
Luckily, this is exactly what we want for Angular. The browser URL remains the same, but the request looks like it was for the application root. This allows Angular to load successfully and then automatically route to the correct client side view.
app.UseFileServer()
The remaining two pieces of middleware expose the /wwwroot folder to the internet, and also the /node_modules folder which needs to be exposed to Angular, but NPM will always install it in the project root instead of wwwroot. This trick makes it appear as if both folders are at the root of the application.
I’ll go into more detail about the UseFileServer middleware in future posts.
At the time of writing, ASP.NET Core 1 was still a Release Candidate, so if anything has broken or changed please send me a tweet. | http://benjii.me/2016/01/angular2-routing-with-asp-net-core-1/ | CC-MAIN-2017-30 | refinedweb | 670 | 63.9 |
_lwp_cond_reltimedwait(2)
- map pages of memory
#include <sys/mman.h> void *mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off);
The mmap() function establishes a mapping between a process's address space and a file or shared memory object. The format of the call is as follows:
pa = mmap(addr, len, prot, flags, fildes, off);
The mmap() function establishes a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes. The value of pa is a function of the addr argument and values of flags, further described below. A successful mmap() call returns pa as its result. The address range starting at pa and continuing for len bytes will be legitimate for the possible (not necessarily current) address space of the process. The range of bytes starting at off and continuing for len bytes will be legitimate for the possible (not necessarily current) offsets in the file or shared memory object represented by fildes.
The mmap() function allows [pa, pa + len) to extend beyond the end of the object both at the time of the mmap() and while the mapping persists, such as when the file is created prior to the mmap() call and has no contents, or when the file is truncated. Any reference to addresses beyond the end of the object, however, will result in the delivery of a SIGBUS or SIGSEGV signal. The mmap() function cannot be used to implicitly extend the length of files.
The mapping established by mmap() replaces.
The mmap() function is supported for regular files and shared memory objects. Support for any other type of file is unspecified.
The prot argument determines whether read, write, execute, or some combination of accesses are permitted to the data being mapped. The prot argument should be either PROT_NONE or the bitwise inclusive OR of one or more of the other flags in the following table, defined in the header <sys/mman.h>.
Data can be read.
Data can be written.
Data can be executed.
Data cannot be accessed.
If an implementation of mmap() for a specific platform cannot support the combination of access types specified by prot, the call to mmap() fails. An implementation may permit accesses other than those specified by prot; however, the implementation will not permit a write to succeed where PROT_WRITE has not been set or permit any access where PROT_NONE alone has been set. Each platform-specific implementation of mmap() supports the following values of prot: PROT_NONE, PROT_READ, PROT_WRITE, and the inclusive OR of PROT_READ and PROT_WRITE. On some platforms, the PROT_WRITE protection option is implemented as PROT_READ|PROT_WRITE and PROT_EXEC as PROT_READ|PROT_EXEC. The file descriptor fildes is opened with read permission, regardless of the protection options specified. If PROT_WRITE is specified, the application must have opened the file descriptor fildes with write permission unless MAP_PRIVATE is specified in the flags argument as described below.
The flags argument provides other information about the handling of the mapped data. The value of flags is the bitwise inclusive OR of these options, defined in <sys/mman.h>:
Changes are shared.
Changes are private.
Interpret addr exactly.
Do not reserve swap space.
Map anonymous memory.
Interpret addr as required aligment.
Map text.
Map initialized data segment.
The MAP_SHARED and MAP_PRIVATE options describe the disposition of write references to the underlying object. If MAP_SHARED is specified, write references will change the memory object. If MAP_PRIVATE is specified, the initial write reference will create a private copy of the memory object page and redirect the mapping to the copy. The private copy is not created until the first write; until then, other users who have the object mapped MAP_SHARED can change the object. Either MAP_SHARED or MAP_PRIVATE must be specified, but not both. The mapping type is retained across fork(2).
When MAP_FIXED is set in the flags argument, the system is informed that the value of pa must be addr, exactly. If MAP_FIXED is set, mmap() may return (void *)-1 and set errno to EINVAL. If a MAP_FIXED request is successful, the mapping established by mmap() replaces any previous mappings for the process's pages in the range [pa, pa + len). The use of MAP_FIXED is discouraged, since it may prevent a system from making the most effective use of its resources.
When MAP_FIXED is set and the requested address is the same as previous mapping, the previous address is unmapped and the new mapping is created on top of the old one.
When MAP_FIXED is not set, the system uses addr to arrive at pa. The pa so chosen will be an area of the address space that the system deems suitable for a mapping of len bytes to the file. The mmap() function interprets an addr value of 0 as granting the system complete freedom in selecting pa, subject to constraints described below. A non-zero value of addr is taken to be a suggestion of a process address near which the mapping should be placed. When the system selects a value for pa, it will never place a mapping at address 0, nor will it replace any extant mapping, nor map into areas considered part of the potential data or stack “segments”.
When MAP_ALIGN is set, the system is informed that the alignment of pa must be the same as addr. The alignment value in addr must be 0 or some power of two multiple of page size as returned by sysconf(3C). If addr is 0, the system will choose a suitable alignment.
The MAP_NORESERVE option specifies that no swap space be reserved for a mapping. Without this flag, the creation of a writable MAP_PRIVATE mapping reserves swap space equal to the size of the mapping; when the mapping is written into, the reserved space is employed to hold private copies of the data. A write into a MAP_NORESERVE mapping produces results which depend on the current availability of swap space in the system. If space is available, the write succeeds and a private copy of the written page is created; if space is not available, the write fails and a SIGBUS or SIGSEGV signal is delivered to the writing process. MAP_NORESERVE mappings are inherited across fork(); at the time of the fork(), swap space is reserved in the child for all private pages that currently exist in the parent; thereafter the child's mapping behaves as described above.
When MAP_ANON is set in flags, and fildes is set to -1, mmap() provides a direct path to return anonymous pages to the caller. This operation is equivalent to passing mmap() an open file descriptor on /dev/zero with MAP_ANON elided from the flags argument.
The MAP_TEXT option informs the system that the mapped region will be used primarily for executing instructions. This information can help the system better utilize MMU resources on some platforms. This flag is always passed by the dynamic linker when it maps text segments of shared objects. When the MAP_TEXT option is used for regular file mappings on some platforms, the system can choose a mapping size larger than the page size returned by sysconf(3C). The specific page sizes that are used depend on the platform and the alignment of the addr and len arguments. Several diffrent mapping sizes can be used to map the region with larger page sizes used in the parts of the region that meet alignment and size requirements for those page sizes.
The MAP_INITDATA option informs the system that the mapped region is an initialized data segment of an executable or shared object. When the MAP_INITDATA option is used for regular file mappings on some platforms, the system can choose a mapping size larger than the page size returned by sysconf(). The MAP_INITDATA option should be used only by the dynamic linker for mapping initialized data of shared objects.
The off argument is constrained to be aligned and sized according to the value returned by sysconf() when passed _SC_PAGESIZE or _SC_PAGE_SIZE. When MAP_FIXED is specified, the addr argument must also meet these constraints. The system performs mapping operations over whole pages. Thus, while the len argument need not meet a size or alignment constraint, the system will include, in any mapping operation, any partial page specified by the range [pa, pa + len).
The system will always zero-fill any partial page at the end of an object. Further, the system will never write out any modified portions of the last page of an object which are beyond its end. References to whole pages following the end of an object will result in the delivery of a SIGBUS or SIGSEGV signal. SIGBUS signals may also be delivered on various file system conditions, including quota exceeded errors.
The mmap() function adds an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close(2) on that file descriptor. This reference is removed when there are no more mappings to the file by a call to the munmap(2) function.
The st_atime field of the mapped file may be marked for update at any time between the mmap() call and the corresponding munmap(2) call. The initial read or write reference to a mapped region will cause the file's st_atime field to be marked for update if it has not already been marked for update.
The st_ctime and st_mtime fields of a file that is mapped with MAP_SHARED and PROT_WRITE, will be marked for update at some point in the interval between a write reference to the mapped region and the next call to msync(3C) with MS_ASYNC or MS_SYNC for that portion of the file by any process. If there is no such call, these fields may be marked for update at any time after a write reference if the underlying file is modified as a result.
If the process calls mlockall(3C) with the MCL_FUTURE flag, the pages mapped by all future calls to mmap() will be locked in memory. In this case, if not enough memory could be locked, mmap() fails and sets errno to EAGAIN.
The mmap() function aligns based on the length of the mapping. When determining the amount of space to add to the address space, mmap() includes two 8-Kbyte pages, one at each end of the mapping that are not mapped and are therefore used as “red-zone” pages. Attempts to reference these pages result in access violations.
The size requested is incremented by the 16 Kbytes for these pages and is then subject to rounding constraints. The constraints are:
For 32-bit processes:
If length > 4 Mbytes round to 4-Mbyte multiple elseif length > 512 Kbytes round to 512-Kbyte multiple else round to 64-Kbyte multiple
For 64-bit processes:
If length > 4 Mbytes round to 4-Mbyte multiple else round to 1-Mbyte multiple
The net result is that for a 32-bit process:
If an mmap() request is made for 4 Mbytes, it results in 4 Mbytes + 16 Kbytes and is rounded up to 8 Mbytes.
If an mmap() request is made for 512 Kbytes, it results in 512 Kbytes + 16 Kbytes and is rounded up to 1 Mbyte.
If an mmap() request is made for 1 Mbyte, it results in 1 Mbyte + 16 Kbytes and is rounded up to 1.5 Mbytes.
Each 8-Kbyte mmap request “consumes” 64 Kbytes of virtual address space.
To obtain maximal address space usage for a 32-bit process:
Combine 8-Kbyte requests up to a limit of 48 Kbytes.
Combine amounts over 48 Kbytes into 496-Kbyte chunks.
Combine amounts over 496 Kbytes into 4080-Kbyte chunks.
To obtain maximal address space usage for a 64-bit process:
Combine amounts < 1008 Kbytes into chunks <= 1008 Kbytes.
Combine amounts over 1008 Kbytes into 4080-Kbyte chunks.
The following is the output from a 32-bit program demonstrating this:
64-Kbyte delta between starting addresses.
1–Mbyte delta between starting addresses.
512-Kbyte delta between starting addresses
1536-Kbyte delta between starting addresses
1-Mbyte delta between starting addresses
8-Mbyte delta between starting addresses
4-Mbyte delta between starting addresses
The following is the output of the same program compiled as a 64-bit application:
1-Mbyte delta between starting addresses
1-Mbyte delta between starting addresses
1-Mbyte delta between starting addresses
2-Mbyte delta between starting addresses
1–Mbyte delta between starting addresses
8-Mbyte delta between starting addresses
4-Mbyte delta between starting addresses
Upon successful completion, the mmap() function returns the address at which the mapping was placed (pa); otherwise, it returns a value of MAP_FAILED and sets errno to indicate the error. The symbol MAP_FAILED is defined in the header <sys/mman.h>. No successful return from mmap() will return the value MAP_FAILED.
If mmap() fails for reasons other than EBADF, EINVAL or ENOTSUP, some of the mappings in the address range starting at addr and continuing for len bytes may have been unmapped.
The mmap() function will fail if:
The fildes file descriptor is not open for read, regardless of the protection specified; or fildes is not open for write and PROT_WRITE was specified for a MAP_SHARED type mapping.
The mapping could not be locked in memory.
There was insufficient room to reserve swap space for the mapping.
The fildes file descriptor is not open (and MAP_ANON was not specified).
The arguments addr (if MAP_FIXED was specified) or off are not multiples of the page size as returned by sysconf().
The argument addr (if MAP_ALIGN was specified) is not 0 or some power of two multiple of page size as returned by sysconf(3C).
MAP_FIXED and MAP_ALIGN are both specified.
The field in flags is invalid (neither MAP_PRIVATE or MAP_SHARED is set).
The argument len has a value equal to 0.
MAP_ANON was specified, but the file descriptor was not -1.
MAP_TEXT was specified but PROT_EXEC was not.
MAP_TEXT and MAP_INITDATA were both specified.
The number of mapped regions would exceed an implementation-dependent limit (per process or per system).
The fildes argument refers to an object for which mmap() is meaningless, such as a terminal.
The MAP_FIXED option was specified and the range [addr, addr + len) exceeds that allowed for the address space of a process.
The MAP_FIXED option was not specified and there is insufficient room in the address space to effect the mapping.
The mapping could not be locked in memory, if required by mlockall(3C), because it would require more space than the system is able to supply.
The composite size of len plus the lengths obtained from all previous calls to mmap() exceeds RLIMIT_VMEM (see getrlimit(2)).
The system does not support the combination of accesses requested in the prot argument.
Addresses in the range [off, off + len) are invalid for the object specified by fildes.
The MAP_FIXED option was specified in flags and the combination of addr, len and off is invalid for the object specified by fildes.
The file is a regular file and the value of off plus len exceeds the offset maximum establish in the open file description associated with fildes.
The mmap() function may fail if:
The file to be mapped is already locked using advisory or mandatory record locking. See fcntl(2).
Use of mmap() may reduce the amount of memory available to other memory allocation functions.
MAP_ALIGN is useful to assure a properly aligned value of pa for subsequent use with memcntl(2) and the MC_HAT_ADVISE command. This is best used for large, long-lived, and heavily referenced regions. MAP_FIXED and MAP_ALIGN are always mutually-exclusive.
Use of MAP_FIXED may result in unspecified behavior in further use of brk(2), sbrk(2), malloc(3C), and shmat(2). The use of MAP_FIXED is discouraged, as it may prevent an implementation from making the most effective use of resources.
The application must ensure correct synchronization when using mmap() in conjunction with any other file access method, such as read(2) and write(2), standard input/output, and shmat(2).
The mmap() function has a transitional interface for 64-bit file offsets. See lf64(5).
The mmap() function allows access to resources using address space manipulations instead of the read()/write() interface. Once a file is mapped, all a process has to do to access it is use the data at the address to which the object was mapped. */
See attributes(5) for descriptions of the following attributes:
close(2), exec(2), fcntl(2), fork(2), getrlimit(2), memcntl(2), mprotect(2), munmap(2), shmat(2), lockf(3C), mlockall(3C), msync(3C), plock(3C), sysconf(3C), attributes(5), lf64(5), standards(5), null(7D), zero(7D) | http://docs.oracle.com/cd/E18752_01/html/816-5167/mmap-2.html | CC-MAIN-2015-11 | refinedweb | 2,791 | 60.14 |
cost of this endless stream of garbage is eventually going to push some
part of the system to the breaking point. And the results may not be
good. As the spam problem gets worse, most email users will be willing to
accept almost anything from their ISPs or legislators which promises to
improve things. It would not be surprising to see power grabs
coming from several directions as the usual cynical forces try to take
advantage of the situation. Are we ready for a world of centralized email
systems, proprietary protocols which limit bulk mailing to "authorized"
merchants, and new laws giving governments power to monitor and restrict
If we're not ready for those things, we're going to have to think again
about how to fight this problem. Filtering can be highly effective, but it
does little for many of the costs of spam, including bandwidth usage and
compromised servers. Filtering also does not work for all users. Somehow,
a way must be found to keep spammers and their output off the net. If we
can't come up with a way to do that which preserves the freedoms that have
made the net what it is, we're likely to see rather less palatable
attempted solutions imposed by others.
Solution
Posted May 5, 2004 20:57 UTC (Wed) by yodermk (subscriber, #3803)
[Link]
I've posted this on Slashdot a few times, and whiners always come back with reasons why it won't work. I have, with very little difficulty, been able to think of a reasonable answer to every objection.
So before you gripe here about why it won't work, please spend a few minutes yourself trying to think of a way to get around your supposed problem.
The biggest problem by far is getting people to switch mail systems. But if we do nothing, spam will keep getting worse. IM2000, along with a good blacklist system (which would work MUCH better than blacklists with SMTP), should go a long way to stopping spam. No centralized mail servers, certificates, or government intervention required.
Last I checked a few months ago, there were some good proposals swimming around on the Net. Need to look again for progress. Unfortunately, I don't know of an implementation yet, but it shouldn't be *that* hard. Once we get that, I bet people will start switching. Then as they drop SMTP accounts, others will need to switch to IM2000 to communicate with them. :)
Problem with your 'Solution'
Posted May 5, 2004 21:42 UTC (Wed) by lakeland (subscriber, #1157)
[Link]
Posted May 5, 2004 23:05 UTC (Wed) by yodermk (subscriber, #3803)
[Link]
> A large percentage of spam is sent by zombies. Your solution would enablethese zombies to continue spamming as before.
First, what do you mean by zombies? I know (roughly) the tactics of spammers, but I'm not familiar with which one(s) the term "zombie" applies to.
But no, I don't believe you're correct that it would enable them to keep spamming as before. Here's how I understand it:.
Blacklisting as I understand it in the IM2000 model: If joe@isp.com sends a spam, his particular address is added to the blacklist, which would probably be a "push" type deal. Eventually it would trickle down to all the clients. (Ok, a "pull" system might be better, where it queries for every email, that's up for debate.) If, say, three or more users of a certain ISP or domain name or maybe subnet send spam, that entire network goes onto the blacklist.
It probably won't stop 100% of spam, but I don't think our dear grumpy editor would be receiving 1200 spams a day with this protocol.
I can also see how it could cause some minor inconvenience for people in some circumstances, say, those in the middle of nowhere with spotty satellite connections. But, I'm 100% sure that it can be made to work somehow, even if it looses a feature or two of this setup.
Above all, please ask yourself this: Is any conceivable disadvantage to this system anywhere near as big a problem as 1200 spams a day???
> After all, the spammer couldtrivially manage to only store one copy of the message on their ISP.Though I admit I haven't thought this one through so carefully.
Yeah, think you need to read and think about this method more. :-) Actually one of the great things about this system is that it allows only one master copy to be stored on the ISP. For legitimate bulk mail, such as mailing lists, that's a rather significant benefit.
Posted May 5, 2004 23:29 UTC (Wed) by dlang (subscriber, #313)
[Link]
get a few thousand machines controlled by worms to each send a few dozen messages and you have a system that won't trigger any alarms at any one ISP.
also what happens to mailing lists? I have a low bandwidth DSL line to my mail server (144k IDSL, the only thing I can get to my location) if I sendd a message to the linux-kernel mailing list do I now have several tens of thousands of people trying to download the message over my slow link?
what happens if the senders server is down or unreachable when I want to read the message?.
Posted May 6, 2004 2:13 UTC (Thu) by rjw (guest, #10415)
[Link]
You need to allow for people running there own servers
Posted May 6, 2004 4:30 UTC (Thu) by alex (subscriber, #1355)
[Link]
Posted May 6, 2004 5:51 UTC (Thu) by copsewood (subscriber, #199)
[Link]
Posted May 6, 2004 17:21 UTC (Thu) by yodermk (subscriber, #3803)
[Link]
Posted May 6, 2004 13:08 UTC (Thu) by shapr (subscriber, #9077)
[Link]
If a zombie sends notifications, it must be at the same hostname or IP for them to be picked up. that also means that blacklists become much more effective when a server is 'accountable' for its actions.
As for mailing lists, I think the list host would pick up and then host the mail, allowing for pushed spam. But then this isn't a silver bullet, just an improvement.
Right, once a mail is in the system it's trusted and pushed. The cost of storing and delivering mails is on the system, not the sender. If you move those costs to the sender, spam becomes less economically viable.
The essence is that you and I pay for spam in a push system like we have now, and we only pay for notifications in im2000.
One major advantage here is that those most likely to respond to spam, namely Internet newbies who check their mail once a week, are much less likely to get spam, since geeks like us will have gotten a spammed notify, and had time to do something about it (update blacklist, remove virus, etc).That further cuts down on the economic advantages of spam.
Anyway, that's just my take on how to make spam less profitable for the spammers.
Posted May 6, 2004 17:19 UTC (Thu) by yodermk (subscriber, #3803)
[Link]
With the distributed blacklist (assuming it is administered in a trustworthy manner) would almost certainly make the cost to spam way too high.
As for mailing lists, the protocol changes somewhat drastically. See Bernstein's site, he talks about it.
> what happens if the senders server is down or unreachable when I want to read the message?
That is the second biggest problem with the system, after transition difficulties. Basically, someone (your ISP or you) needs to run a reliable mail server. That's a minor disadvantage perhaps, but keep in mind how it compares to 1200 spams a day.
>.
I really don't see how you can come to that conclusion. Of course it's deployable. It doesn't even use more bandwidth and storage in the long run. It will use much less bandwidth because of less spam. And storage would be less because it would only store one copy of an outgoing message to many users. Receiver-side storage would only be on his local computer, not on the server. (Ok, an IMAP-like mode could change that.)
Posted May 6, 2004 6:25 UTC (Thu) by pizza (subscriber, #46)
[Link]
Except you are forgetting one very important point.
The majority of these spams now contain unique subjects and/or bodies, be it via random dictionary words or whatever. So much to only one copy, eh?
Posted May 6, 2004 17:26 UTC (Thu) by yodermk (subscriber, #3803)
[Link]
2. In the long run it's no real disadvantage over SMTP even if you *do* have to store a separate copy for each recipient. And, if joe@isp.com sends a million distinct messages, some flag would still be raised, and it would be easy for an admin to nuke all his messages.
Heck, you could set a space limit for outgoing mail ... maybe 100MB or so (up to the ISP of course). That should eliminate a million distinct messages.
Posted May 6, 2004 7:20 UTC (Thu) by fergal (subscriber, #602)
[Link]!
Posted May 6, 2004 17:28 UTC (Thu) by yodermk (subscriber, #3803)
[Link]
Because they'd enter blacklists if they don't.
Posted May 7, 2004 2:19 UTC (Fri) by fergal (subscriber, #602)
[Link]
How exactly would you keep that blacklist up to date? Wouldn't you have to aim spam probes at various ISPs and see if they block them. Good luck with that project.
Posted May 17, 2004 5:50 UTC (Mon) by coolian (guest, #14818)
[Link]
Posted May 6, 2004 9:55 UTC (Thu) by mmarsh (subscriber, #17029)
[Link]
That's an unfair request. If it's all been thought of and debated before, provide a URL or something. You're making a proposal, so it's up to you to defend it. A capsule description provides insufficient detail to support a position or adequately describe a system.
!
How is this different than a spam where the body is essentially just an image tag (or a redirect) to an advertisement on a remote server? Since notification latency will vary from recipient to recipient and not everyone checks email immediately on arrival, there might never be a noticeable spike. Combine that with an ISP that just doesn't care about bandwidth usage, and you're really no better off than when you started.
.
So email availability is dependant on the reliability of the sender? If the sender's ISP has to keep track of whether all of the recipients have retrieved the message, how does that affect forwarding? Will mail that gets forwarded be retrievable at all? Here I don't mean A sends a message to B who then forwards it to C. That's a no-brainer: B has to store it. I mean A sends a message to B at foo.com, but B has a .forward file passing it along to bar.com. I've had forwarding chains of about four hops, and I suspect there are many people with longer chains. Does each hop have to cache the message?
What about messages of the type "Our server will be down for maintenance on Thursday"? If a recipient doesn't check mail on Wednesday, he'll see that there's a message waiting from him, possibly flagged as important, but he won't be able to retrieve it until it's no longer relevant.
Posted May 6, 2004 17:37 UTC (Thu) by yodermk (subscriber, #3803)
[Link]
> How is this different than a spam where the body is essentially just an image tag (or a redirect) to an advertisement on a remote server?
That would still end up as an email in someone's box. An IM2000 spam would have a subject, but may be unavailable upon mail check. Even though that type of spam is "short", it's still far better that it never reaches the recipient, to make spamming less profitable.
> Combine that with an ISP that just doesn't care about bandwidth usage
I do think it would be detectable, and any ISP that simply didn't care would be blacklisted.
> but B has a .forward file passing it along to bar.com. I've had forwarding chains of about four hops, and I suspect there are many people with longer chains. Does each hop have to cache the message?
Couple possibilities ... 1) each hop caches the message, 2) each hop notifies the originating ISP of the new recipient. That may have privacy concerns though.
> What about messages of the type "Our server will be down for maintenance on Thursday"?
That would be something to think about. This really does depend on mail servers being reliable. But, for the most part, they are.
Posted May 17, 2004 5:52 UTC (Mon) by coolian (guest, #14818)
[Link]
But you suggested it and said it would "of course" be the answer. If you don't have any actual knowledge of it, then how could you know it's the answer? Jesus, you must be 12.
Posted May 17, 2004 5:45 UTC (Mon) by coolian (guest, #14818)
[Link]
I think the only thing that will work without legislation is filtering/whitelist/challenge-response.
Why does everyone bring this up every time?
Posted May 6, 2004 10:24 UTC (Thu) by Ross (subscriber, #4065)
[Link]
Posted May 6, 2004 17:41 UTC (Thu) by yodermk (subscriber, #3803)
[Link]
1. Regulating all mail servers with government intevention2. Using only centralized mail servers3. Using certificates for mail servers, with each server needing to pay out the arse for a certificate4. IM2000, which has a couple minor disadvantage for a few uses, and which can be worked around5. 82% of our bandwidth being wasted on spam.
Which is least evil?
Posted May 17, 2004 5:58 UTC (Mon) by coolian (guest, #14818)
[Link]
>> Oh yeah, I don't think so.
2. Using only centralized mail servers
>> Meaning what?
3. Using certificates for mail servers, with each server needing to pay out the arse for a certificate
>> Why? Do you understand how certs work?
4. IM2000, which has a couple minor disadvantage for a few uses, and which can be worked around
>> Minor disadvantages? The whole system not working is more than minor. There are MAJOR unresolved issues with it, that you have zero answers for. They can be worked around? By who? You?
5. 82% of our bandwidth being wasted on spam.
>> This is the least evil of the ones you list. Sorry, but most would agree. I don't want people like you, who have zero answers, running my mail. Thanks, but no.
Posted May 6, 2004 13:19 UTC (Thu) by melauer (guest, #2438)
[Link]
I'm not convinced by this "solution". Those "brief notification" messages must either contain a little information, like a subject line, or people will have to click on them not knowing what they're going to get. Either way, these will become the new method of delivering spam. Then we'd be back where we started from. If a spammer runs their own mail server, we'd need to blacklist it. If there's an open relay out there for "brief notification" messages, it would have to be closed so spammers don't send fake ones. And so on.
The proposed method would cut down on the total bandwidth used by e-mail, though. That's kind of nice.
Incidentally, this system has basically already been implemented. Any number of private web forums use this. When one forum member sends a private message to another, the recipient gets a "brief notification" in the form on an e-mail. Then they login using a link provided in the e-mail and view the contents of the private message, which is of course stored on the forum's server.
Posted May 6, 2004 17:46 UTC (Thu) by yodermk (subscriber, #3803)
[Link]
I'd suggest they contain a subject line and sender name. Any obvious spam would then not need to be transmitted over the Net at all, at least to users who care, which would take care of a lot right there!
> Either way, these will become the new method of delivering spam.
But remember that it would be much easier for a responsible ISP to stop this before the worst part of the problem than it is under SMTP. If an ISP detects spam, it deletes the message at the source before most people have downloaded it. If a customer's computer is spamming with its own IM2000 server, it could simply block the receiving port to that IP. Under SMTP, if it was caught at any point after the spam was sent, it's too late.
> If there's an open relay out there for "brief notification" messages, it would have to be closed so spammers don't send fake ones.
It would be impossible to send fake notification messages, because the end-user's box needs the IP of the server from which to fetch the mail!
Posted May 7, 2004 15:02 UTC (Fri) by brouhaha (subscriber, #1698)
[Link]
The problem I see is that this doesn't address spam at all. It just changes the delivery mechanism. Today, the spammers bombard your MTA (e.g., Sendmail, Postfix, or Exchange) with spam. Your MTA uses a lot of resources (CPU, memory, disk) dealing with this. Depending on the MTA and configuration, it may or may not be able to do some filtering to avoid actually storing some of the spam in your mail queue. Then you check your inbox using an MUA (mail client such as Evolution, Mozilla Mail, Eudora, or Outlook). The MUA may also do some filtering, but at the very least has to inspect the headers of each message the MTA has received for you.
With IM2000, the spammer's machine doesn't directly send the spam to you. Instead, it tells your MTA (or whatever the IM2000 equivalent of an MTA is) that there is mail waiting for you on the spammer's machine. So now instead of getting 1200 spam emails a day, you get 1200 email waiting notifications from random machines all over the internet, many of which are probably zombies. Ultimately your software doesn't have any better way to tell which are spam than in today's architecture; it will simply have to poll each of the 1200 sender mail servers to get the mail headers and try to filter them.
This has *perhaps* reduced the internet backbone bandwidth consumed somewhat, if the filtering can be done with inspection of headers only and not the full message body, but it has not solved the spam problem. In fact, given that the IM2000 model provides for the sender's mail server to repeat the "mail available" notifications to the receiver, it may not even affect the bandwidth consumption. And it certainly does not improve the bandwidth consumption on the user's local link.
As far as I can see, IM2000 is a solution to a non-problem. It has attempted to solve the problem of reducing the amount of disk space the recipient needs to store the email, but disk space is the least significant problem associated with spam.
IM2000 appears to solve the "mailing list problem", except that there isn't really a "mailing list problem" either.
Part of the solution: laws that work
Posted May 5, 2004 21:11 UTC (Wed) by dwheeler (subscriber, #1216)
[Link]
Will people disobey the law? Sure.
But after a few people lose all their money, or go to jail,
this exploitation will quickly reduce to levels that can
be handled by current technology.
We need both laws and technology. One without the other is
like fighting with one hand tied behind our back.
Europe is already leading this way; they've already passed these
kinds of laws. But without cooperation from the US, it won't
be enough.
Once there are only a few rogue states, their cooperation can be
more easily acquired... by refusing to accept any of their email
until they update their laws.
This is just like the computer break-in laws a few decades ago;
at first, many people didn't even understand that break-ins were
like trespass.
Then, over time, laws were passed to forbid people from harming others
using computers.
Posted May 5, 2004 22:33 UTC (Wed) by jamesh (subscriber, #1159)
[Link]
Of course, the penalties for having your product advertised via spam would need to be a fine rather than jail. In the case where it really is done by a third party without consent, the company should have some way to recover the fine from the spammer.
Posted May 7, 2004 15:09 UTC (Fri) by brouhaha (subscriber, #1698)
[Link]
you'd probably need some kind of penalty for having your products advertised via spam.
Posted May 6, 2004 5:30 UTC (Thu) by copsewood (subscriber, #199)
[Link]
Blacklisting and blocking can become much more effective when spammers have to use their own domains and give valid return addresses.
82% of email is spam
Posted May 5, 2004 22:09 UTC (Wed) by freethinker (guest, #4397)
[Link].
Wood estimates that 70 percent of spam is sent through open proxies.
Well, then, this isn't a problem, because as everyone knows, Microsoft is now taking security seriously! So I'm sure all those zombies will be dead real soon now.
Posted May 6, 2004 9:31 UTC (Thu) by mmarsh (subscriber, #17029)
[Link]
Posted May 17, 2004 6:01 UTC (Mon) by coolian (guest, #14818)
[Link]
Posted May 13, 2004 6:47 UTC (Thu) by Wol (guest, #4433)
[Link]
Indeed, it was so bad, that it took me about four attempts before I could download the necessary security patches to fix the problem. The spam software - which I didn't know what it was although I knew something was wrong - was pinching nearly all available cpu and bandwidth so the system had nothing left to download the patches with :-(
Cheers,Wol
Solution: Sender Policy Framework
Posted May 6, 2004 5:39 UTC (Thu) by copsewood (subscriber, #199)
[Link]
This isn't a complete solution by any means, but it is likely to be a neccessary step in making a complete solution possible which doesn't break too many things worth keeping.
Posted May 6, 2004 6:07 UTC (Thu) by hingo (subscriber, #14792)
[Link]
Posted May 6, 2004 10:28 UTC (Thu) by Ross (subscriber, #4065)
[Link]
Posted May 6, 2004 6:29 UTC (Thu) by pizza (subscriber, #46)
[Link]
This has cut the spam I receive down to a small trickle from the couple hundred a day, to say nothing for the other users of the system I admin. (The only spam I get now is stuff sent via massive BCCs using a rather traditional e-mail client)
The nice thing about this is that it happens before mail is delivered, so you save on the bandwidth, storage, and cpu costs of post-delivery filtering.
There are multiple implementations of this technique now.
Posted May 6, 2004 7:32 UTC (Thu) by rwmj (guest, #5474)
[Link]
--- quote:beenhouse down!
Posted May 6, 2004 7:59 UTC (Thu) by alspnost (subscriber, #2763)
[Link]
At work, we use a 3-tiered strategy that's pretty effective. Firstly, we use RBL blacklists, and reject connections from malconfigured mail servers (eg with DNS problems); secondly, we use SpamAssassin on everything that reaches our queue; thirdly, we've put most of our users onto Thunderbird, and the built-in adaptive filtering is pretty good at mopping up anything that gets through SpamAssassin, once it's been trained.
For me personally, the biggest problem is accessing my (POP-based) mail via the webmail gateway when I'm away from home: with no spam filtering at that stage, I have to wade through 3 screenfuls of crap to find the 1 legitimate mail waiting for me....
Bandwidth
Posted May 6, 2004 8:21 UTC (Thu) by vondo (guest, #256)
[Link]
Besides, spam e-mails are generally small. I have 13 in my filtered area now, the largest is 12 KB. People regularly send me 1MB files in the mail.
Posted May 6, 2004 10:10 UTC (Thu) by smoogen (subscriber, #97)
[Link]
Thrusted mail ?
Posted May 6, 2004 12:50 UTC (Thu) by bockman (subscriber, #3650)
[Link]
Mailing lists also could work this way, carrying both the mailing list signature and the signature of the poster.
This would work for 90% of users or more. Those needing to receive truly anonymous mail, could set special mailboxes for that.
Thinking of that, is anyone aware of any anti-spam filter that works on signatures? (Just curious: my personal small spam problems are easily solved by pressing 'd' in mutt some 8-10 times per day ).
Posted May 7, 2004 2:14 UTC (Fri) by dd9jn (subscriber, #4459)
[Link]
The problem is the definition of what makes up a "good signature". Yeah, we know about the Web of Trust and hierachical trust models but this will only work between people who know each other. This would lead to a system of closed groups like BBSes decades ago.
If you don't care about the validity of the signature, but merely check for the mathematical correctness, spammers will simply create new keys for each spam and sign it. No, there is no performance problem given the legions of zombies waiting for their evil masters.
Posted May 7, 2004 5:22 UTC (Fri) by bockman (subscriber, #3650)
[Link]
Once per month, or even less, I may receive a mail from an unknown person, that wants to get in touch with me.
Therefore, for me would be very easy to define a list of 'good signatures' that could be used to filter my mail (possibly at server level). If I don't want to loose the mail from unauthenticated sources, I could isolate it in a separate mail folder, to check when/if I want. This mail folder could collect spam, but at least it is nicely isolated (and if I get too much annoyed, I could simply bounce unauthenticated mail).
Now, I understand that people, and especially business, can use e-mail to get in touch daily with unknown people. But I believe that a lot of people have an e-mail behaviour very similar to mine.Consider also that you don't need the same 'level of thrust' used for secure transactions (you are just talking by e-mail, not doing finantial transactions). Therefore you could also exchange public key by mail, when you start corresponding with someone else.
Posted May 7, 2004 6:37 UTC (Fri) by dd9jn (subscriber, #4459)
[Link]
Mailing lists are another problem. Of course the mailing list software could sign all message to be send out but that won't help. For a closed mailing list this will currently help but I have already encountered faked From addresses (which are the current way of authenticating subscribers) which led spam slip through. Open mailing lists (everyone is allowed to post) are already nice spam exploders and it won't help to have a signature applied by the ML software. Over short or long we have to change the authentication of mailing lists anyway to a stronger one (i.e. only accept signed posts), but this will require manual approval of subscription requests to sort out spammers. For some mailing lists this will not be possible at all - think of a help list for the signing or MUA software ;-).
Posted May 8, 2004 10:56 UTC (Sat) by giraffedata (subscriber, #1954)
[Link]
But I still have a big problem. I route the stranger mail to a special folder, which I check daily, but there are 250 spams a day. I've had to start automatically deleting some of it (e.g. any all-html email), but that's risky.
I think people who believe the only interesting email they will get is from acquaintances lack imagination. You can't just delete mail from strangers; you have to spend some time looking at it to see if it's spam.
I occasionally have my outgoing emails bounced by overzealous spam filters, and in every case the recipient would have been glad to get my email.
Trust metrics are the FUSSP
Posted May 6, 2004 17:42 UTC (Thu) by raph (guest, #326)
[Link]
Unfortunately, trust metrics are difficult enough to understand (and I've done such a poor job evangelizing people so they're motivated to understand), that they haven't made much impact on the world.
I resemble a few of those check-boxes on the form posted above, but I do suspect that one of two things is true: the spam problem won't be solved in our lifetime because of a combination of technical difficulty and lack of willpower; or that the solution will use some form of peer certification to distinguish spammers from legitimate email correspondents. These days I'm more inclined to believe the former, but that's probably just my legendary bitterness shining through.
Posted May 6, 2004 21:13 UTC (Thu) by neilbrown (subscriber, #359)
[Link]
But on a more serious side, I'm coming to the conclusion that the only long-term solution to SPAM must involve white-listing. i.e. I *only* accept mail from addresses (SPF-verifiable addresses) that I trust. This would require MUA support so that anyone I send mail to automatically gets white-listed, and things like that.
It would also mean that when people (e.g. companies) ask for your Email address, their would need to give your their email address in return (We will only send you mail from info@clever-company.com.) which you would have to white-list.
If people who you don't know want to send you mail, that has to be possible, but it also should be expensive (roughly the cost of a postage stamp or a 'phone call). This might involve finding a common correspondant to introduce you, or it might involve some "proof-of-cpu-power-spent" similar to HashCash, or it could even involve an exchange of money (e.g. I will read your mail if you can prove that you have bought a $1 e-postage stamp from World Vision). It could use any other challenge-response that a recipient is happy to impose on potential senders.
The big problem today with challenge-response is that you risk sending challenges to innocent third-parties whose address has been used inappropriately. This is where I think SPF really gives value. With SPF, I can tell if I can trust a return-address, and so I can know if it is safe to send a challenge.
If the MTA add an appropriate header with SPF status, this can all be done in the MUA.
This doesn't address the bandwidth/server-load problem. It isn't clear to me that there can be a better total solution to that than pushing the whitelist+challenge-response into the MTA (there are lots of partial solutions which can heurisically drop a lot of bad mail, but they will eventually cause the spammers to get smarter).
Posted May 7, 2004 15:21 UTC (Fri) by rgoates (subscriber, #3280)
[Link]
1) I get spam in my mailbox.2) I forward the spam to a "spam alert" service that verifies it as spam and then extracts the meat from the spam (the human intervention part), then feeds the meat to a pattern builder.3) The pattern is forwarded to all ISPs to be used in their spam filters. The filter would reject any email that contained text that fit the pattern within some reasonably high confidence level. The rejected email would be returned to the sender, hopefully by the sender's own ISP. Rejecting spam at the network edge would be a huge win.4) In the case of a false positive, the sender would have to sufficiently restate the email's text. This could be a pain, but I doubt it would happen all that often, percentage-wise.5) The spammer is also forced to sufficiently restate his spam.
So what do we gain? The spammer has to work a lot harder (harder than adding some bogus word strings, anyway). With adequate speed of response from spam recipients, many of the spammer's targets would never see his spam. And the pattern building is largely centralized and so can be more easily improved as we become more clever. Additionally, catching spam at the network edge allows easier identification of the spam source.
The monetary cost is primarily in the "spam alert" service. I suspect that cost will be very low compared to the size of the spam problem. The social cost (or effort) will include getting most of the ISPs to use the pattern filtering, but I suspect seeing success at a few ISPs will provide a lot of momentum. I for one am certainly willing to badger my ISP to use it.
There will be no silver bullet. As we all know, there are always antisocials with too much time and misdirected energy. The best we can do is to keep far enough ahead of them to keep their damage to a tolerable level. I think that will be good enough, if we can do it.
Posted May 8, 2004 11:13 UTC (Sat) by giraffedata (subscriber, #1954)
[Link]
So why isn't it working? Is it technologically infeasible? Are big ISP customers not availing themselves of the filtering?
Posted May 15, 2004 11:00 UTC (Sat) by bronson (subscriber, #4806)
[Link]
spam filtering by ISPs
Posted May 15, 2004 11:19 UTC (Sat) by giraffedata (subscriber, #1954)
[Link]
We may be using different definitions of ISPs; I believe this thread is about providers of email mailboxes. AOL, Yahoo, Hotmail, Earthlink, ...
I know these guys filter spam based on content. I see it in my own Yahoo mail account, and Earthlink advertises it. So why is spam still effective? Are they not filtering enough? Are users opting out?
Posted May 10, 2004 9:17 UTC (Mon) by ikm (subscriber, #493)
[Link]
This all is about humans, not about the computers. But computers can help achieve the goal. Say, any mail server that detects a spam messsage attaches a promotion text just above the text of the message, explaining the problem briefly and saying that the only way to stop spam is to stop accepting *any* offerings in that spam.
That is, attaching anti-spam to any spam. The more spam one gets, the more probably he will read the banner at last and understand the problem.
Well, in case most people are failing to read that banners and understand the problem, all the humanity will keep getting spam -- in that case, it actually deserves it. That sounds bitter, of course, but that's the economy -- while there is an interest, there is an offering.
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/83678/ | crawl-002 | refinedweb | 5,878 | 69.72 |
SSL_read,
SSL_peek
— read bytes from a TLS/SSL connection
#include
<openssl/ssl.h>
int
SSL_read(SSL
*ssl, void *buf,
int num);
int
SSL_peek(SSL
*ssl, void *buf,
int num);
SSL_read()
tries to read num bytes from the specified
ssl into the buffer buf.
SSL_peek()
is identical to
SSL_read() except that no bytes are
removed from the underlying BIO during the read, such that a subsequent call
to
SSL_read() will yield at least the same bytes
once again.
In the following,
SSL_read()
and
SSL_peek() are called “read
functions”. done by calling SSL_set_connect_state(3) or SSL_set_accept_state(3) before the first call to a read function.
The read functions works based on the SSL/TLS records. The data are received in records (with a maximum record size of 16kB). Only when a record has been completely received, it can be processed (decrypted and checked for integrity). Therefore data that was not retrieved at the last read call can still be buffered inside the SSL layer and will be retrieved on the next read call. If num is higher than the number of bytes buffered, the underlying BIO is blocking, a read
function will only return once the read operation has been finished or an
error occurred, except when a renegotiation takes place, in which case an
SSL_ERROR_WANT_READ may occur. This behavior can be
controlled with the
SSL_MODE_AUTO_RETRY flag of the
SSL_CTX_set_mode(3)
call. a
re-negotiation is possible, a read function may also cause write operations.
The calling process must then repeat the call after taking appropriate
action to satisfy the needs of the read function. a read function can be called without blocking or actually receiving new data from the underlying socket.
When a read function operation has to be repeated because of
SSL_ERROR_WANT_READ or
SSL_ERROR_WANT_WRITE, it must be repeated with the
same arguments.
The following return values can occur:
SSL_RECEIVED_SHUTDOWNflag in the ssl shutdown state is set (see SSL_shutdown(3) and SSL_set_shutdown(3)). It is also possible that the peer simply shut down the underlying transport and the shutdown is incomplete. Call
SSL_get_error() with the return value to find out whether an error occurred or the connection was shut down cleanly (
SSL_ERROR_ZERO_RETURN).
SSL_get_error() with the return value to find out the reason.
BIO_new(3), ssl(3), SSL_accept(3), SSL_connect(3), SSL_CTX_new(3), SSL_CTX_set_mode(3), SSL_get_error(3), SSL_pending(3), SSL_set_connect_state(3), SSL_set_shutdown(3), SSL_shutdown(3), SSL_write(3) | https://man.openbsd.org/OpenBSD-6.1/SSL_read.3 | CC-MAIN-2022-21 | refinedweb | 395 | 52.6 |
Targeting User Interface Solutions to the 2007 and 2010 Releases of Microsoft Office
Summary:Microsoft Office 2010 expands on the features that were introduced in the 2007 release of Microsoft Office. See how you can create solutions that target one version of Microsoft Office or both versions. (3 Printed Pages)
Last modified: April 07, 2011
Applies to: Excel 2010 | Office 2007 | Office 2010 | Open XML | PowerPoint 2010 | SharePoint Server 2010 | VBA | Word 2010
Published: November 2009
Provided by: Mirko Mandic, Microsoft Corporation
Contents
Authoring Solutions for the 2007 Office System and Microsoft Office 2010
Microsoft Office 2010 evolves the Microsoft Office Fluent user interface (UI) extensibility model by expanding the platform introduced in the 2007 release with new features and also, by introducing support for customizing the new Backstage view.
This article describes how to create UI extensibility solutions that are compatible with the 2007 release of Microsoft Office, Microsoft Office 2010, or both.
The new UI extensibility features are described in detail in the article Introduction to the Office 2010 Backstage View for Developers.
Creating a Document-Based Solution
Just as in the 2007 release, you can customize the UI in Office 2010 for a specific document. And, as in the 2007 release, this is achieved by adding an XML file with your custom UI definition to the Office Open XML format file.
If your solution targets the 2007 release (or if it targets Office 2010, but you do not want to use the new UI extensibility features introduced in Office 2010), you can rely on the UI extensibility approach introduced in the 2007 release—the XML file with your UI customizations should use the namespace for the 2007 Office system and the relationships (.rels) file should contain a relationship targeting the 2007 Office system.
This also means that if you wrote a solution in Office 2007, it works in Office 2010 without any required modifications.
The namespace for the 2007 release is. The corresponding relationship namespace is.
If your solution targets Office 2010, you need to ensure that you use the appropriate namespace and the corresponding relationship in the Office Open XML format file. The Office 2010 namespace is. The corresponding relationship namespace is.
If your solution targets both the 2007 release and the 2010 release (and you want your Office 2010 version to use the new UI extensibility features, which are not supported in the 2007 release), you need to have two custom UI XML files in the Office Open XML file, each extending the appropriate version of Office. You also need to ensure that the relationships file contains appropriate relationship entries for both of the files.
Table 1. How the 2007 and 2010 release of Office use custom UI XML file(s)
At the document level, the process for customizing the Office Fluent UI involves the following steps:
Replace the extension in your macro-enabled file name (.docm, .xlsm, etc.) with a .zip extension.
Open the Zip package and add the XML file that defines your custom UI to the package.
In addition to ensuring that your markup uses tags appropriate for the target version(s) of Office, ensure that it uses the correct namespace, as defined previously.
Modify the package relationship part (.rels) to link the correct XML file and ensure that the relationship type corresponds to the target version of Microsoft Office. For example, if you are creating a solution that targets Office 2010 and you added a customUI2010.xml file to a customUI folder (inside of the Zip package), the newly-added relationship line should look like the following example.
As long as it is unique within the .rels file, the relationship Id can have any value.
Close the Zip package and replace the .zip extension with the appropriate extension for your macro-enabled file.
Open the document and ensure that the customizations from your XML file appear.
Creating a COM Add-In Solution
In a typical scenario, a COM add-in contains code that returns the XML defining the custom UI to Microsoft Office. This XML can be contained in an external file or in simple cases, located in the code itself. When the application runs, the code returns the XML markup to Office. In an optional step, you can validate this XML against a XSD schema file. The XML is then loaded into memory and applied to the Office Fluent UI.
If your add-in targets a single version of Microsoft Office, regardless of whether it is the 2007 release or the 2010 release, the markup returned by code should contain the appropriate namespace (as defined previously) and should be valid for the target version.
If your add-in targets both the 2007 release and the 2010 release of Microsoft Office, the code should detect which version you are running and based on the check, return appropriate markup. This requires both markup files are authored and accessible by the code. You can rely on the application’s object model (Application.Version) to check which Microsoft Office version you are running.
Alternatively, you can use reflection to achieve the same thing. The following is an example using Microsoft Visual C#.
Conclusion
How you target each version of Microsoft Office depends on whether you are creating a document-specific solution or a COM-based solution. When creating a document-based solution, you need to ensure that Microsoft Office finds and loads the XML file defining the structure of the customized UI which is appropriate for the target version of Microsoft Office. When creating a COM-based solution, you need to ensure that your code returns the XML defining the structure of the customized which is appropriate for the target version of Microsoft Office.
For more information about Office 2010 extensibility, see the following resources: | http://msdn.microsoft.com/en-us/library/office/ee704588(v=office.14) | CC-MAIN-2014-42 | refinedweb | 961 | 50.26 |
Opened 9 years ago
Closed 9 years ago
Last modified 8 years ago
#14938 closed (fixed)
"Save as" does not save entries added with a Inline
Description (last modified by )
What steps will reproduce the problem?
- go to the admin change form of an instance of a model class with both the "save as" feature enabled, and a TabularInline for relate items.
- change the original instance
- add a new related instance using the TabularInline
What is the expected output? What do you see instead?
A new instance should be created, a copy of all the related instances should be created and a new instance for any item added in the TabularInline should be created.
Instead the original item is created, all the pre-existing instances are copied but the new ones are not created.
Note: deleting an entry works as expected is just the add that "fails" by creating the new instance without adding the new related items.
Additional information
django version: 1.2.3
locale: it-IT
this may also be related to #4045
Attachments (1)
Change History (12)
Changed 9 years ago by
comment:1 Changed 9 years ago by
The "save as" button in the admin change form simply redirects to the add_view with the only difference that the "save_as_new" parameter is passed to the formset:
formset = FormSet(data=request.POST, files=request.FILES, instance=new_object, save_as_new=request.POST.has_key("_saveasnew"), prefix=prefix, queryset=inline.queryset(request))
Where "FormSet" are instances of "BaseInlineFormSet"
It's a problem in the BaseInlineFormSet class. See the attached patch.
comment:2 Changed 9 years ago by
Yes, I could verify this issue. Here's a simple test case:
Models:
from django.db import models class Foo(models.Model): name = models.CharField(max_length=30) class Bar(models.Model): parent = models.ForeignKey(Foo) title = models.CharField(max_length=30)
Admin:
from django.contrib import admin from .models import Foo, Bar class BarInline(admin.StackedInline): model = Bar class FooAdmin(admin.ModelAdmin): inlines = (BarInline,) save_as = True admin.site.register(Foo, FooAdmin)
New inlines added before clicking "Save as new" get lost.
I really doubt your patch is the way to go , though.
comment:3 Changed 9 years ago by
comment:4 Changed 9 years ago by
(reformatted description)
comment:5 Changed 9 years ago by
comment:6 Changed 9 years ago by
comment:7 Changed 9 years ago by
Actually, the modification proposed by the OP doesn't seem wrong. Simply removing the BaseInlineFormSet implementation of the
total_form_count() method and so leaving to defer to the implementation in BaseFormSet makes the newly filled inline formsets to get validated and (once corrected if they didn't validate) saved associated with the new cloned parent model instance
That
if self.save_as_new : condition was added when these methods (
total_form_count() and
initial_form_count()) were introduced back in r10190 ~two years ago.
Joseph Kocherhans expressed on IRC it is possible this might be an implementation bug.
Changing component because this doesn't seem to be a admin-specific problem.
comment:8 Changed 9 years ago by
Not sure why I marked this blocker, regression; on inspection, it doesn't appear to be either. It's been a problem since at least 1.1.X, and it doesn't involve data loss (there's lost data on entry, but nothing destructive happens to existing data)
comment:9 Changed 9 years ago by
comment:10 Changed 9 years ago by
comment:11 Changed 8 years ago by
Milestone 1.3 deleted
Patch fixing the issue | https://code.djangoproject.com/ticket/14938 | CC-MAIN-2019-39 | refinedweb | 581 | 56.86 |
I'm used to edit my sources in 2 instances and every time I save changes in one instance the others in which the same source is opened offer me to reload source from the disk and delete all changes I've made in that instances. I wonder is there a way to make sublime 'add' changes from disk if the source changed (like scm git do).Thank you!
I've the same problem, not sure if a package exists to avoid fakes "clones". Would be nice to have a package that automatically clones the view, when opening the same file twice. I'll take a look
I remember now, why I did not solved this before, cloned views can't be moved from own window. Then, if you open the same file in another window, is not possible to clone the other, and move it to replace the current one.
I got stuck here:
import sublime_plugin, sublime
class Pref():
def load(self):
Pref.run = True
Pref = Pref()
Pref.load();
class Dolly(sublime_plugin.EventListener):
def on_load(self, view):
sublime.set_timeout(lambda: self.find_fake_clones(view), 1000)
sublime.set_timeout(lambda: self.find_fake_clones_run(view), 3000)
def on_post_save(self, view):
sublime.set_timeout(lambda: self.find_fake_clones(view), 1000)
sublime.set_timeout(lambda: self.find_fake_clones_run(view), 3000)
def find_fake_clones_run(self, view):
Pref.run = True
def find_fake_clones(self, view):
if Pref.run: # on save will run for each cloned view?
Pref.run = False
clones = ]
for window in sublime.windows():
for _view in window.views():
if _view.file_name() and _view.file_name() == view.file_name() and _view.buffer_id() != view.buffer_id():
# the view to clone
original_window = _view.window()
original_window.focus_view(_view)
original_window.run_command('clone_file');
good_clone = original_window.active_view();
# the view to close, and then append the clone to
fake_window = view.window()
fake_window.focus_view(view)
fake_group, fake_index = fake_window.get_view_index(view)
original_window.set_view_index(good_clone, fake_group, fake_index);
fake_window.focus_view(view)
# fake_window.run_command('close')
return
# window.run_command('close')sss
# print(clones);
# active_group() int Returns the index of the currently selected group.
# None Makes the given group active.
# focus_view(view) None Switches to the given view.
# get_view_index(view) (group, index) Returns the group, and index within the group of the view. Returns -1 if not found.
# set_view_index(view, group, index) None Moves the view to the given group and index. | https://forum.sublimetext.com/t/editing-source-in-multiple-instances/11902/3 | CC-MAIN-2017-22 | refinedweb | 372 | 62.04 |
.
Note: Future lessons have a lot more code than this one
Key Question of this course: How can we do matrix computations with acceptable speed and acceptable accuracy?
A list of the Top 10 Algorithms of science and engineering during the 20th century includes: the matrix decompositions approach to linear algebra. It also includes the QR algorithm, which we'll cover, and Krylov iterative methods which we'll see an example of. (See here for another take)
(source: Top 10 Algorithms)
There are 4 things to keep in mind when choosing or designing an algorithm for matrix computations:
Often there will be trade-offs between these categories.
Matrices are everywhere-- anything that can be put in an Excel spreadsheet is a matrix, and language and pictures can be represented as matrices as well. Knowing what options there are for matrix algorithms, and how to navigate compromises, can make enormous differences to your solutions. For instance, an approximate matrix computation can often be thousands of times faster than an exact one..
There are two key types of matrix computation, which get combined in many different ways. These are:
So basically we're going to be combining matrices, and pulling them apart again!]])
Convolutions are the heart of convolutional neural networks (CNNs), a type of deep learning, responsible for the huge advances in image recognitionin the last few years. They are now increasingly being used for speech as well, such as Facebook AI's results for speech translation which are 9x faster than RNNs (the current most popular approach for speech translation).
Computers are now more accurate than people at classifying images.
(Source: Andrej Karpathy)
You can think of a convolution as a special kind of matrix product
The 3 images below are all from an excellent blog post written by a fast.ai student on CNNs from Different Viewpoints:
A convolution applies a filter to each section of an image:
Neural Network Viewpoint:
Matrix Multiplication Viewpoint:
Let's see how convolutions can be used for edge detection in this notebook(originally from the fast.ai Deep Learning Course)
We will be talking about Matrix Decompositions every day of this course, and will cover the below examples in future lessons:
To understand accuracy, we first need to look at how computers (which are finite and discrete) store numbers (which are infinite and continuous)
Take a moment to look at the function $f$ below. Before you try running it, write on paper what the output would be of $x_1 = f(\frac{1}{10})$. Now, (still on paper) plug that back into $f$ and calculate $x_2 = f(x_1)$. Keep going for 10 iterations.
This example is taken from page 107 of Numerical Methods, by Greenbaum and Chartier.
def f(x): if x <= 1/2: return 2 * x if x > 1/2: return 2*x - 1
Only after you've written down what you think the answer should be, run the code below:
x = 1/10 for i in range(80): print(x) x = f(x)
What went wrong?
Two Limitations of computer representations of numbers:
The reason we need to care about accuracy, is because computers can't store infinitely accurate numbers. It's possible to create calculations that give very wrong answers (particularly when repeating an operation many times, since each operation could multiply the error).
How computers store numbers:
The mantissa can also be referred to as the significand.
IEEE Double precision arithmetic:
The interval $[1,2]$ is represented by discrete subset: $$1, \: 1+2^{-52}, \: 1+2 \times 2^{-52},\: 1+3 \times 2^{-52},\: \ldots, 2$$
The interval $[2,4]$ is represented: $$2, \: 2+2^{-51}, \: 2+2 \times 2^{-51},\: 2+3 \times 2^{-51},\: \ldots, 4$$
Floats and doubles are not equidistant:
Source: What you never wanted to know about floating point but will be forced to find out
Machine Epsilon
Half the distance between 1 and the next larger number. This can vary by computer. IEEE standards for double precision specify $$ \varepsilon_{machine} = 2^{-53} \approx 1.11 \times 10^{-16}$$
Two important properties of Floating Point Arithmetic:
The difference between a real number $x$ and its closest floating point approximation $fl(x)$ is always smaller than $\varepsilon_{machine}$ in relative terms. For some $\varepsilon$, where $\lvert \varepsilon \rvert \leq \varepsilon_{machine}$, $$fl(x)=x \cdot (1 + \varepsilon)$$
Where is any operation ($+, -, \times, \div$), and $\circledast$ is its floating point analogue, $$ x \circledast y = (x y)(1 + \varepsilon)$$ for some $\varepsilon$, where $\lvert \varepsilon \rvert \leq \varepsilon{machine}$ That is, every operation of floating point arithmetic is exact up to a relative error of size at most $\varepsilon{machine}$
Floating point arithmetic may seem like a clear choice in hindsight, but there have been many, many ways of storing numbers:
For references, see Chapter 1 (which is free) of the Handbook of Floating-Point Arithmetic. Yes, there is an entire 16 chapter book on floating point!
Timeline History of Floating Point Arithmetic:
"Many different ways of approximating real numbers on computers have been introduced.. And yet, floating-point arithmetic is by far the most widely used way of representing real numbers in modern computers. Simulating an infinite, continuous set (the real numbers) with a finite set (the “machine numbers”) is not a straightforward task: clever compromises must be found between, speed, accuracy, dynamic range, ease of use and implementation, and memory. It appears that floating-point arithmetic, with adequately chosen parameters (radix, precision, extremal exponents, etc.), is a very good compromise for most numerical applications."
Although a radix value of 2 (binary) seems like the pretty clear winner now for computers, a variety of other radix values have been used at various point:
Since we can not represent numbers exactly on a computer (due to the finiteness of our storage, and the gaps between numbers in floating point architecture), it becomes important to know how small perturbations in the input to a problem impact the output.
"A stable algorithm gives nearly the right answer to nearly the right question." --Trefethen
Conditioning: perturbation behavior of a mathematical problem (e.g. least squares)
Stability: perturbation behavior of an algorithm used to solve that problem on a computer (e.g. least squares algorithms, householder, back substitution, gaussian elimination)
Example: Eigenvalues of a Matrix
import scipy.linalg as la A = np.array([[1., 1000], [0, 1]]) B = np.array([[1, 1000], [0.001, 1]]) print(A) print(B)
[[ 1. 1000.] [ 0. 1.]] [[ 1. 1000. ] [ 0.001 1. ]]
np.set_printoptions(suppress=True, precision=4)
wA, vrA = la.eig(A) wB, vrB = la.eig(B) wA, wB
Reminder: Two properties of Floating Point Arithmetic
The difference between a real number $x$ and its closest floating point approximation $fl(x)$ is always smaller than $\varepsilon_{machine}$ in relative terms.
Every operation $+, -, \times, \div$ of floating point arithmetic is exact up to a relative error of size at most $\varepsilon_{machine}$
Examples we'll see:
It's rare that we need to do highly accurate matrix computations at scale. In fact, often we're doing some kind of machine learning, and less accurate approaches can prevent overfitting.
If we accept some decrease in accuracy, then we can often increase speed by orders of magnitude (and/or decrease memory use) by using approximate algorithms. These algorithms typically give a correct answer with some probability. By rerunning the algorithm multiple times you can generally increase that probability multiplicatively!
Example: A bloom filter allows searching for set membership with 1% false positives, using <10 bits per element. This often represents reductions in memory use of thousands of times.
The false positives can be easily handled by having a second (exact) stage check all returned items - for rare items this can be very effective. For instance, many web browsers use a bloom filter to create a set of blocked pages (e.g. pages with viruses), since blocked web pages are only a small fraction of the whole web. A false positive can be handled here by taking anything returned by the bloom filter and checking against a web service with the full exact list. (See this bloom filter tutorial for more details).
The below examples are from Greenbaum & Chartier.
European Space Agency spent 10 years and $7 billion on the Ariane 5 Rocket.
What can happen when you try to fit a 64 bit number into a 16 bit space (integer overflow):
from IPython.display import YouTubeVideo YouTubeVideo("PK_yguLapgA")
Here is a floating point error that cost Intel $475 million:
Resources: See Lecture 13 of Trefethen & Bau and Chapter 5 of Greenbaum & Chartier for more on Floating Point Arithmetic
Above we covered how numbers are stored, now let's talk about how matrices are stored. A key way to save memory (and computation) is not to store all of your matrix. Instead, just store the non-zero elements. This is called sparse storage, and it is well suited to sparse matrices, that is, matrices where most elements are zero.
Here is an example of the matrix from a finite element problem, which shows up in engineering (for instance, when modeling the air-flow around a plane). In this example, the non-zero elements are black and the zero elements are white:
Source
There are also special types of structured matrix, such as diagonal, tri-diagonal, hessenberg, and triangular, which each display particular patterns of sparsity, which can be leveraged to reduce memory and computation.
The opposite of a sparse matrix is a dense matrix, along with dense storage, which simply refers to a matrix containing mostly non-zeros, in which every element is stored explicitly. Since sparse matrices are helpful and common, numerical linear algebra focuses on maintaining sparsity through as many operations in a computation as possible.
Speed differences come from a number of areas, particularly:
If you are unfamiliar with computational complexity and $\mathcal{O}$ notation, you can read about it on Interview Cake and practice on Codecademy. Algorithms are generally expressed in terms of computation complexity with respect to the number of rows and number of columns in the matrix. E.g. you may find an algorithm described as $\mathcal{O(n^2m)}$.
Modern CPUs and GPUs can apply an operation to multiple elements at once on a single core. For instance, take the exponent of 4 floats in a vector in a single step. This is called SIMD. You will not be explicitly writing SIMD code (which tends to require assembly language or special C "intrinsics"), but instead will use vectorized operations in libraries like numpy, which in turn rely on specially tuned vectorized low level linear algebra APIs (in particular, BLAS, and LAPACK).
BLAS (Basic Linear Algebra Subprograms): specification for low-level matrix and vector arithmetic operations. These are the standard building blocks for performing basic vector and matrix operations. BLAS originated as a Fortran library in 1979. Examples of BLAS libraries include: AMD Core Math Library (ACML), ATLAS, Intel Math Kernel Library (MKL), and OpenBLAS.
LAPACK is written in Fortran, provides routines for solving systems of linear equations, eigenvalue problems, and singular value problems. Matrix factorizations (LU, Cholesky, QR, SVD, Schur). Dense and banded matrices are handled, but not general sparse matrices. Real and complex, single and double precision.
1970s and 1980s: EISPACK (eigenvalue routines) and LINPACK (linear equations and linear least-squares routines) libraries
LAPACK original goal: make LINAPCK and EISPACK run efficiently on shared-memory vector and parallel processors and exploit cache on modern cache-based architectures (initially released in 1992). EISPACK and LINPACK ignore multi-layered memory hierarchies and spend too much time moving data around.
LAPACK uses highly optimized block operations implementations (which much be implemented on each machine) LAPACK written so as much of the computation as possible is performed by BLAS.
Using slower ways to access data (e.g. over the internet) can be up to a billion times slower than faster ways (e.g. from a register). But there's much less fast storage than slow storage. So once we have data in fast storage, we want to do any computation required at that time, rather than having to load it multiple times each time we need it. In addition, for most types of storage its much faster to access data items that are stored next to each other, so we should try to always use any data stored nearby that we know we'll need soon. These two issues are known as locality.
Here are some numbers everyone should know (from the legendary Jeff Dean):
And here is an updated, interactive version, which includes a timeline of how these numbers have changed.
Key take-away: Each successive memory type is (at least) an order of magnitude worse than the one before it. Disk seeks are very slow.
This video has a great example of showing several ways you could compute the blur of a photo, with various trade-offs. Don't worry about the C code that appears, just focus on the red and green moving pictures of matrix computation.
Although the video is about a new language called Halide, it is a good illustration the issues it raises are universal. Watch minutes 1-13:
from IPython.display import YouTubeVideo YouTubeVideo("3uiEyEKji0M")
Locality is hard. Potential trade-offs:
The issue of "temporaries" occurs when the result of a calculation is stored in a temporary variable in RAM, and then that variable is loaded to do another calculation on it. This is many orders of magnitude slower than simply keeping the data in cache or registers and doing all necessary computations before storing the final result in RAM. This is particularly an issue for us since numpy generally creates temporaries for every single operation or function it does. E.g. $a=b\cdot c^2+ln(d)$ will create four temporaries (since there are four operations and functions).
We have a separate section for scalability, but it’s worth noting that this is also important for speed - if we can't scale across all the computing resources we have, we'll be stuck with slower computation.
Often we'll find that we have more data than we have memory to handle, or time to compute. In such a case we would like to be able to scale our algorithm across multiple cores (within one computer) or nodes (i.e. multiple computers on a network). We will not be tackling multi-node scaling in this course, although we will look at scaling across multiple cores (called parallelization). In general, scalable algorithms are those where the input can be broken up into smaller pieces, each of which are handled by a different core/computer, and then are put back together at the end. | https://nbviewer.jupyter.org/github/fastai/numerical-linear-algebra/blob/master/nbs/1.%20Why%20are%20we%20here.ipynb | CC-MAIN-2020-40 | refinedweb | 2,445 | 50.46 |
Search Type: Posts; User: peterarsentev
Search: Search took 0.01 seconds.
- 11 Mar 2012 5:33 AM
- Replies
- 0
- Views
- 450
Hello I would like to set special format to y axis in line chart.
I found that ChartModel has a method setYAxisLabelStyle(); and I guess that it can do it.
Can you help me with it?
Regard.
- 2 Mar 2012 4:52 AM
- Replies
- 0
- Views
- 400
Hello. I encountered with problems. I have a TreeGrid and I would like to apply ListFilter for it. TreeGrid has fields like name, login and ext. I set display field - name, but I would like to filter...
- 2 Mar 2012 3:05 AM
Jump to post Thread: adjust labels in line chart by peterarsentev
- Replies
- 1
- Views
- 681
Hello, I have problems with a LineChart. I would like to build LineChart with large range data for x axis.
For example y(x) = x*x; {-1000, 1000}. I can set min x, max x and step, but all labels will...
- 29 Feb 2012 5:04 AM
- Replies
- 3
- Views
- 3,086
Can you tell me anything about this problem?
- 27 Feb 2012 4:21 AM
- Replies
- 3
- Views
- 3,086
Yes sure
package com.sample.tree.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;...
- 17 Feb 2012 2:48 AM
- Replies
- 3
- Views
- 3,086
Hello I have a strange behavior in TreeGrid when I set setExpandOnFilter(false). It does not open leafs after filtering.
I made a maven project where you can testing it....
- 16 Feb 2012 1:08 AM
I did an sample that you can check it
there
It is a maven project.
- 15 Feb 2012 4:14 AM
Ok. I wrote an epic code that to do it.
final TextField<String> firstName = new TextField<String>();
Button button = new Button("Search");
button.addSelectionListener(new...
- 14 Feb 2012 5:42 AM
I made a little example what I meant.
package com.messagedna.client.widget;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.BaseModelData;
import...
- 9 Feb 2012 2:53 AM
Hello I have a problem with StoreFilterField in tree.
I use dynamic proxy for load branch in tree and would like to apply a filter only for root element.
if I use StoreFilterField right now it...
Results 1 to 10 of 10 | http://www.sencha.com/forum/search.php?s=f9addb98712b06d6bbe01dc8d3427cd2&searchid=5042607 | CC-MAIN-2014-15 | refinedweb | 404 | 77.43 |
Possible Duplicate:
Android How to draw a smooth line following your finger
I’m new to Android and java programming and have been playing around a bit with mobile app development. I recently created a View which simply keeps draws lines in step with the user’s finger movements. However, I’ve been having some trouble with the Canvas.drawLines method.
Instead of getting a continuous set of lines between all points I am getting more of a dashed pattern with breaks between segments:
Here is a sample set of data and simple code to reproduce the issue (point data was taken from a real finger swipe):
public class SomeView extends android.view.View { private float[] _data = { 292.36545f, 104.37576f, 285.3567f, 112.39249f, 274.34293f, 113.39456f, 254.3179f, 115.39874f, 248.3104f, 116.40082f, 228.28535f, 118.405f, 214.26784f, 119.407104f, 211.26408f, 119.407104f, 204.25533f, 120.40918f, 202.25282f, 120.40918f, 201.25157f, 121.411255f, 199.24907f, 124.41754f, 197.24657f, 125.41962f, 196.24532f, 130.43005f, 195.24406f, 139.44885f, 197.24657f, 144.45929f }; private Paint _paint; public SomeView( Context c, AttributeSet attrs) { super( c, attrs ); _paint = new Paint(); _paint.setColor(Color.BLUE); _paint.setStrokeWidth(6); } @Override public void onDraw(Canvas canvas) { canvas.drawLines( _data, _paint); } }
After plotting out each point and overlaying it atop the line I realized that the problem is actually that each point is not being connected, only every two points. Instead of connecting point 1 to point 2 to point 3 and so on, the method is connecting 1 to 2 and then 3 to 4 as shown below:
I can almost get what I want by drawing calling
drawLines again and providing an offset this time so that the other pairs are drawn together as well, but this seems inefficient and generally clunky to me, and the line still isn’t completely smooth (gets slightly choppy on corners).
So, my question is; what am I doing wrong and how can I draw a simple, smooth line given some number of points? Heck, forget the points, if there is a better way to trace the user’s finger with a line I am all ears. Thanks in advance.
What you get is exactly what is specified in the
drawLines documentation.
One way of doing what you want would be to construct a
Path from that data, and use
drawPath rather than
drawLines. Something like:
Path _path = new Path(); _path.moveTo(_data[0], _data[1]); for (int i=2; i<_data.length; i+=2) { _path.lineTo(_data[i], _data[i+1]); }
Then draw it with:
_canvas.drawPath(_path, _paint)
From the
Path docs:
The Path class encapsulates compound (multiple contour) geometric paths consisting of straight line segments, quadratic curves, and cubic curves. It can be drawn with canvas.drawPath(path, paint), either filled or stroked (based on the paint’s Style)
So you might have to change you’re paint’s style to get the right effect.
Answer:
I just ran into this issue tonight. For anyone else facing this, the problem is that Android doesn’t draw from point 1 to point 2, then point 2 to point 3, point 3 to point 4, etc. It will draw point 1 to 2, then point 3 to 4, etc. So you can also push the previous point twice into whatever data structure you use (I used Vector). So:
private Vector<Float> mPoints = new Vector<Float>(); private float mLastX = Float.NaN; private float mLastY = Float.NaN; public void addPoint(float x, float y) { if (mLastX == Float.NaN || mLastY == Float.NaN) { mLastX = x; mLastY = y; } else { mPoints.add(mLastX); mPoints.add(mLastY); mPoints.add(x); mPoints.add(y); mLastX = x; mLastY = y; } }
Then just make sure to convert your mPoints to a float[] and pass that to
canvas.drawLines().
Tags: canvas, javajava, join | https://exceptionshub.com/java-canvas-drawlines-displaying-disjointed-segments.html | CC-MAIN-2021-49 | refinedweb | 642 | 70.73 |
Earlier I wrote that I got a Netduino Go Starter kit for Christmas. I've worked with it from time to time. This is a little late posting, because I finished my first project in February. I thought I'd share it here and perhaps I might get some ideas for future projects.
You get several things with the starter kit including an RGB LED, button, and potentiometer. I put these together as an RGB flasher. The concept is simple. The LED flashes with color changes on an interval. The button starts and stops the flashing. And the potentiometer controls the rate of the flashing.
To start this I created a class with the following interface (full class code at the end of the article):
class RgbFlasher : IDisposable { RgbFlasher() Start() Dispose()}
This class pretty much controls everything. The Main method creates and starts a RgbFlasher and waits as shown below.
public static void Main() { var flasher = new RgbFlasher(); flasher.Start();
while (true) { Thread.Sleep(1000); } }
Overall, it was a fun, short project and was easy to put together. I'm looking for a little more of a challenge the next time around.
Full listing for the RgbFlasher class
using NetduinoGo;using System;using System.Threading;
public class RgbFlasher : IDisposable{ private readonly RgbLed rgbBtn; private readonly Button toggleBtn; private readonly Potentiometer delayMeter; private Timer timer;
private readonly Random rand; private bool isFlashing = false;
private const int DelayBase = 1750; private const int DelayMin = 250;
public RgbFlasher() { // init components rgbBtn = new RgbLed(); delayMeter = new Potentiometer(); toggleBtn = new Button(); toggleBtn.ButtonPressed += (sender, state) => isFlashing = !isFlashing;
rand = new Random((int)DateTime.Today.Ticks); }
public void Start() { int delay = GetDelay(delayMeter); timer = new Timer(new TimerCallback(Flash), null, 0, delay); }
private void Flash(object state) { // change the color while led state is flashing; button // controls that state if (isFlashing) { byte r = (byte)rand.Next(255); byte g = (byte)rand.Next(255); byte b = (byte)rand.Next(255);
rgbBtn.SetColor(r, g, b); }
// set the timer based on the potentiometer int newDelay = GetDelay(delayMeter); timer.Change(newDelay, newDelay); }
private static int GetDelay(Potentiometer meter) { return (int)(DelayBase * meter.GetValue()) + DelayMin; }
public void Dispose() { if (rgbBtn != null) rgbBtn.Dispose(); if (toggleBtn != null) toggleBtn.Dispose(); if (delayMeter != null) delayMeter.Dispose(); if (timer != null) timer.Dispose(); }} | http://gamecontest.geekswithblogs.net/tonyt/archive/2013/04/28/152809.aspx | CC-MAIN-2020-05 | refinedweb | 376 | 51.24 |
What is C#?
This article is provided courtesy of Sams Publishing
For additional information see the author's book, Sams Teach Yourself C# in 21 Days.
Have you heard of C# (pronounced See-Sharp)? It would not be unusual if you didn't know a lot about the language. Released to the public in June 2000, C# has not been around for very long.
C# is a new language created by Microsoft and submitted to the ECMA for standardization. This new language was created by a team of people at Microsoft led by Anders Hejlsberg . Interestingly, Hejlsberg is a Microsoft Distinguished Engineer who has created other products and languages, including Borland Turbo C++ and Borland Delphi. With C#, they focused on taking what was right about existing languages and adding improvements to make something better.
C# is a powerful and flexible programming language. Like all programming languages, it can be used to create a variety of applications. Your potential with C# is limited only by your imagination. The language does not place constraints on what you can do. C# has already been used for projects as diverse as dynamic Web sites, development tools, and even compilers.
C# was created as an object-oriented programming (OOP) language. Other programming languages include object-oriented features, but very few are fully object-oriented. In my book you can learn how C# compares to some of these other programming languages. My book also covers what it means to use an object-oriented language as well as the details of doing object-oriented programming with C#.
Why C#?
Many people believed that there was no need for a new programming language. Java, C++, Perl, Microsoft Visual Basic, and other existing languages were believed to offer all the functionality needed.
C# is a language derived from C and C++, but it was created from the ground up. Microsoft started with what worked in C and C++ and included new features that would make these languages easier to use. Many of these features are very similar to what can be found in Java. Ultimately, Microsoft had a number of objectives when building the language. These objectives can be summarized in the claims Microsoft makes about C#:
- C# is simple.
- C# is modern.
- C# is object-oriented.
In addition to Microsoft's reasons, there are other reasons to use C#:
- C# is powerful and flexible.
- C# is a language of few words.
- C# is modular.
- C# will be popular.
C# Is Simple
C# removes some of the complexities and pitfalls of languages such as Java and C++, including the removal of macros, templates, multiple inheritance, and virtual base classes. These are all areas that cause either confusion or potential problems for C++ developers. If you are learning C# as your first language, rest assured -- these are topics you won't have to spend time learning!
C# is simple because it is based on C and C++. If you are familiar with C and C++, or even Java, you will find C# very familiar in many aspects. Statements, expressions, operators, and other functions are taken directly from C and C++, but improvements make the language simpler. Some of the improvements include eliminating redundancies. Other areas of improvement include additional syntax changes. For example, C++ has three operators for working with members: ::, ., and ->. Knowing when to use each of these three symbols can be very confusing in C++. In C#, these are all replaced with a single symbol--the "dot" operator. For newer programmers, this and many other features eliminate a lot of confusion.
C# Is Modern
What makes a modern language? Features such as exception handling, garbage collection, extensible data types, and code security are features that are expected in a modern language. C# contains all of these.
C# Is Object-Oriented
The keys to an object-oriented language are encapsulation, inheritance, and polymorphism. C# supports all of these. Encapsulation is the placing of functionality into a single package. Inheritance is a structured way of extending existing code and functionality into new programs and packages. Polymorphism is the capability of adapting to what needs to be done. Understand, these are very simplistic definitions. The implementation of these is a bit more complicated.
C# Is Powerful and Flexible
As mentioned before, with C# you are limited only by your imagination. The language places no constraints on what can be done. C# can be used for projects as diverse as creating word processors, graphics, spreadsheets, and even compilers for other languages.
C# Is a Language of Few Words
C# is a language that uses a limited number of words. C# contains only a handful of terms, called keywords, which serve as the base on which the language's functionality is built. Table 1.1 lists the C# keywords. A majority of these keywords are used to describe information. You might think that a language with more keywords would be more powerful. This isn't true. As you program with C#, you will find that it can be used to do any task.
TABLE 1.1. The C# Keywordsabstract as base bool breakbyte case catch char checkedclass const continue decimal defaultdelegate do double else enumevent explicit extern false finallyfixed float for foreachgoto if implicit in intinterface internal is lock longnamespace new null object operatorout override params private protectedpublic readonly ref return sbytesealed short sizeof stackallocstatic string struct switch thisthrow true try typeof uintulong unchecked unsafe ushort usingvirtual void while
C# Is Modular
C# code can (and should) be written in chunks called classes, which contain routines called member methods. These classes and methods can be reused in other applications or programs. By passing pieces of information to the classes and methods, you can create useful, reusable code.
C# Will Be Popular
C# is one of the newest programming languages. At the time this book was written, it was unknown as to what the popularity of C# would be, but it is a good bet that this will become a very popular language for a number of reasons. One of the key reasons is Microsoft and the promises of .NET.
Microsoft wants C# to be popular. Although a company cannot make a product be popular, it can help. Not long ago, Microsoft suffered the abysmal failure of the Microsoft Bob operating system. Although Microsoft wanted Bob to be popular, it failed.
C# stands a better chance of success than Microsoft Bob. I dont know whether people at Microsoft actually used Bob in their daily jobs. C#, however, is being used by Microsoft. Many of its products have already had portions rewritten in C#. By using it, Microsoft helps validate the capabilities of C# to meet the needs of programmers.
Microsoft .NET is another reason why C# stands a chance to succeed. .NET is a change in the way the creation and implementation of applications is done. Although virtually any programming language can be used with .NET, C# is proving to be the language of choice. Tomorrow's lesson includes a section that explains the high points of .NET.
In Summary...
C# will also be popular for all the features mentioned earlier: simplicity, object-orientation, modularity, flexibility, and conciseness. As a programming language, C# takes the best of the programming languages that already exist and rolled them into a new languages.
C# is no harder to learn than C, C++, or Java. A number of books exist for learning C# including the one from which this article is derived -- Sams Teach Yourself C# in 21 Days. If Microsoft can fulfill its promise with .NET, then C# should have a long, robust life, and C# developers should become as demanded as C++ and Java programmers.
This article was originally published on November 13, 2001 | https://www.developer.com/net/asp/article.php/922211/What-is-C.htm | CC-MAIN-2020-50 | refinedweb | 1,289 | 57.16 |
Post your Comment
TRIGGERS
TRIGGERS
... take when some databases related event occurs. Triggers are executed when you... TRIGGER privilege.
In this section we will describe you about the syntax to create
More About Triggers
More About Triggers
... the misfire is occurred. More descriptions about
the misfire instruction will provide... of
triggers. As we know that the trigger objects are used for executing the jobs
Types of Triggers
Types of Triggers hii,
How many types of Triggers in sql?
hello,
there are three type of trigger
DML triggers
Instead of triggers
System triggers
Implementing more than one Job Details and Triggers
Implementing more than one Job Details and Triggers... will learn how to implement
more than one triggers and jobs with a quartz... of more than one
job details and triggers.
Description of program:
Here, we
Jobs & Triggers
of a job or trigger must be unique within its group.
More about Job & JobDetail
In this section you will understand some more things
about nature of jobs... Jobs & Triggers
What are the types of triggers?
What are the types of triggers? What are the types of triggers?
Hi,
There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words
Triggers - JSP-Servlet
Triggers Hello friends,
I have to do automatic change in my home page which shows logged members automatically. For this, purpose how can i use update triggers. That is, how can i get the result of a trigger
Cron Expression for Cron Triggers
JobStores
give to the scheduler: jobs, triggers, calendars, etc. The
important step..." on jobs and triggers. In
other words, this method's major deficiency... bit more complicated to configure and it is
also as faster than RAMJobStore
More About Simple Trigger
More About Simple Trigger
Simple trigger can be used to one shot execution or fire a
job... will use the "smart policy"
misfire instruction with the triggers
Avoid Stress using Stress Management
then it's all right but if he unable to fulfill those expectations then it triggers a stress... tension, which triggers stress. To overcome those stress inside an employee... or strain.
Needless to say, if someone is confident about his success in his
About struts
About struts How will we configure the struts
About Java
About Java Hi,
Can anyone tell me the About Java programming language? How a c programmer can learn Java development techniques?
Thanks
Hi,
Read about java at.
Thanks
About jsp
About jsp Read Excel data using JSP and update MySQL databse
about java
about java how to get the value from the user like c, c++ program pls explain with example for me
about jquery
about jquery i want to put already made dropdown menu code which is in internet into my website.but how to put
About Java2
About Java2 sir
i want to a develop one text editor but the problem is that i m not able to save our file as text formet or any formet
Sir plz guide me
about java1
about java1 Sir,
i want to know how we develop 3d button ,lable,textfield etc. in java .
sir plz give one program as well
Thank you
About Main
About Main can u create the object of one interface ? But i can able to create the abstract class through anonimous inner class.similarly can i
about connectivity
about connectivity hello i am basavaraj,will any one tell me how to use hibernate in struts.
Please visit the following link:
Struts Hibernate Integration
ABOUT Jtable
ABOUT Jtable My Project is Exsice Management in java swing Desktop Application.
I M Use Netbeans & Mysql .
How can retrive Data in Jtable from Mysql Database in Net Beans
About Database
About Database in my database i enter the date of birth as Birth_Date date but i dont know in which format we can mention the date of birth
In MySQL database, date should be entered in the following format:
yyyy-mm
About Jsp
About Jsp Hello sir, I am developing online Quiz project in jsp using MySql Database. I want to know that How I will show Questions from database One by One on Same page and also want to calculate Result for the User
About Constructor
About Constructor How many objects are create when this code will execute...
String string = new String("Java is best Lang.");
tell me the number of object of string which will create .
All are those are eligible for garbage
about session
about session hey i want to insert userid and username of the user who have currently loggedin in servlet using prepared statement
Please visit the following link:
About Project
About Project Hello friends i want to make a project on face reconization
this is my first projct
so please help me that how i start my projct
please tell me some working with image codeing.
thanks
about a program
about a program hi can anyone suggest program for this question.. it wil really be helpful.its based on *servlet programming*
1. First page should display a dropdown of mathematical operation (Add, Subtract, Multiply, Divide
About java
About java how we insert our database data into the jTable in java
or
how we show database content into the JTable in java
Hi Friend,
Try the following code:
import java.io.*;
import.
Post your Comment | http://www.roseindia.net/discussion/18146-More-About-Triggers.html | CC-MAIN-2013-48 | refinedweb | 895 | 68.5 |
year I started on a project to learn how to use SignalR, I had reasons to do so for my full time job (non-DNN related) but considering my DNN experience over the past 11 years I figured that learning how to use SignalR with DNN would be my fastest way to get myself up to speed. So I started working on a Chat module. Originally that module was called SignalRChat, and was available on codeplex, but ultimately I decided that name kind of sucked, so it needed to be something else.
In comes the DNN Chat module project, there was a Chat module for DNN long ago, but the last official release of it was in 2008, and while there was a Beta in 2010, it hadn't seen any development and work in years. So I approached DNNCorp about taking over the DNN Chat project and replacing it with my newly developed module, at the same time, going from "DNN Chat" to "dnnCHAT".
So here we are today, and the first official release of dnnCHAT is now available, v01.00.00, you can download it now from Codeplex.
You can see the module in action on
Here are some of the details about the module, but first things first, a note.
Note: If you previously used the DNN Chat module, and still have it installed, this module will not replace that, the namespaces are different, the Module Name in the Manifest is different. This module WILL NOT UPGRADE the older module. I would suggest uninstalling that module if you still have it, and then installing this module.
Minimum DNN Version: 7.1.0
Source Control Location:
Source Language: C#
Issue Tracking:
Live Demo:
This module is based on SignalR, utilizing C#, and requires DNN 7.1.0+, it provide basic Chat Room functionality, allowing both Anonymous and logged in users to communicate in the Lobby, logged in users can also join Rooms.
This is an entirely new module, old instances of the DNN CHAT module should be removed before attempting to use this module (they most likely weren't working anyways). | https://www.dnnsoftware.com/community-blog/cid/154923 | CC-MAIN-2021-17 | refinedweb | 353 | 65.15 |
If you intend to use this service regularly on large scale, consider downloading the package and use it locally. Storing a (conceptually) “cashed” version of the generated RDF, instead of referring to the life service, might also be an alternative to consider to avoid overloading this server…
RDFa is a specification for attributes to be used with XHTML or SVG Tiny. pyRdfa is a distiller that generates the RDF triples from an (X)HTML+RDFa or SVG Tiny 1.2 file in various RDF serialization formats. It can either be used directly from a command line or via a CGI service. It corresponds to the RDFa Recommendation, published on the 14th of October, 2008, and, for the SVG version, to the SVG Tiny 1.2 Recommendation, published on the 22nd of December, 2008. The form below can be used to start the service installed at this site. To learn more about RDFa, please consult the RDFa Syntax Document. See also below for the possibilities to download the package.
pyRdfa is a server-side implementation of RDFa. This also means that pages that generate their XHTML content dynamically (eg, using AJAX) will not be properly processed by this distiller.
about="pref:b"is found instead of
about="[pref:b]", unless
prefstands for one of the commonly used URI protocols like
http,
ftp, etc. The default is not to generate warnings.
(Note that the HTML5 parser is work in progress, errors may occur. Note also that the XML parser does not validate the content against the XHTML+RDFa DTD, although a warning is issued if none of the conformance options in the RDFa syntax are used.)
The SVG Tiny 1.2 recommendation, published in December 2008, also adopted RDFa as a means to add RDF (meta)data. The semantics of the RDFa attributes are identical to the XHTML case but the fact that the host language is SVG does lead to two small differences:
metadataelement. An SVG+RDFa distiller ought to understand this RDF graph and merge it with the graph produced by the regular RDFa processing. Such interpretation is meaningless in the XHTML case.
The distiller automatically recognizes an SVG content in case it uses the correct SVG namespace and the top level element is
svg. For other possible XML dialects the extra “host” option with value “xml” can be used to trigger an identical behaviour.
If you use Firefox or Opera, then you can also drag the following bookmarklets to your browser bar and use them to distill the current page: “RDFa it (RDF/XML)!”, “RDFa it (Turtle)!”, “RDFa it (N triples)!”.
When using the distiller URI directly, the option names for the default options can be ommited. E.g., the URI for the RDF/XML formatted RDFa output of, with whitespace preservation and without warnings, and using the “lax” parser is:
The same RDF content in turtle:
The same RDF content but with possible warnings:
Etc. It is also possible to use a fixed pseudo URI:
to generate the RDF (with the default options) of the current file without specifying the URI of the page. This can be used, say, as a link for a button on the page.
The underlying package, called pyRdfa, implemented as a Python module, is also available for download. The core package relies on the RDFLib package, on Deron Meranda’s httpheader module, and, if the “lax” mode is used, on a HTML5 parser. Otherwise it needs only the standard Python distribution (has been tested on version 2.4). The package includes a possible CGI interface script to start a service like this one.
This software is available for use under the W3C® SOFTWARE NOTICE AND LICENSE | http://www.w3.org/2007/08/pyRdfa/ | crawl-002 | refinedweb | 613 | 62.68 |
- ASCII Value of Character(s)
This article covers multiple programs in Java that find and prints the ASCII value of character(s). Here are the list of programs covered by this article:
- Find and print ASCII value of a given character
- Find and print the character of given ASCII value
- Print all ASCII characters with their values
Note - ASCII values of A-Z are 65-90.
Note - ASCII values of a-z are 97-122.
Note - ASCII values of 0-9 are 48-57.
Print ASCII Value of a Given Character in Java
The question is, write a Java program to find and print the ASCII value of a character. The character must be received by user at run-time of the program. The program given below is its answer:
import java.util.Scanner; public class CodesCracker { public static void main(String[] args) { char ch; int ascii; Scanner scan = new Scanner(System.in); System.out.print("Enter a Character: "); ch = scan.next().charAt(0); ascii = ch; System.out.println("\nASCII Value = " +ascii); } }
The snapshot given below shows the sample run of above program with user input A as character to find and print its ASCII value:
The above program can also be written as:
import java.util.Scanner; public class CodesCracker { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter a Character: "); char ch = scan.next().charAt(0); System.out.println("\nASCII Value of " +ch+ " is " +(int)(ch)); } }
Here is its sample run with user input 4:
Find and Print Character of Given ASCII Value in Java
This program is basically the reverse version of previous program. As this program does not find and prints the ASCII value of a character, rather it find and prints the character whose ASCII value will get entered by user at run-time.
import java.util.Scanner; public class CodesCracker { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the ASCII Value: "); int ascii = scan.nextInt(); char ch = (char)ascii; System.out.println("\nThe character is \'" +ch+ "\'"); } }
The sample run of above program with user input 90 as ASCII value to find and prints the character whose ASCII value is 90, is shown in the snapshot given below:
Print all ASCII Characters with their Values in Java
Characters stored using ASCII code are 256. Each ASCII character stored in computer system, using eight bits of information, that gives 28 or 256 characters.
The Java program given below, prints all the ASCII characters along with their values.
public class CodesCracker { public static void main(String[] args) { int ASCII; char ch; Scanner scan = new Scanner(System.in); System.out.println("ASCII\t\tCharacter"); for(ASCII=0; ASCII<=255; ASCII++) { ch = (char)ASCII; System.out.println(ASCII + "\t\t" +ch); } } }
The snapshot given below shows a part of the sample output produced by above program. This snapshot shows a part of sample output, because, it is not possible to show you the complete output, in a single snapshot. But the thing is, you'll get similar output, when you try this program, in your system.
Same Program in Other Languages
« Previous Program Next Program » | https://codescracker.com/java/program/java-program-print-ascii-values.htm | CC-MAIN-2022-21 | refinedweb | 531 | 54.12 |
23 July 2012 11:01 [Source: ICIS news]
LONDON (ICIS)--European chemical stocks fell sharply on Monday, in line with financial markets, amid fears ?xml:namespace>
At 11:39 GMT, the
Despite the approval of a €100bn ($121bn) bailout package for Spain to recapitalise its financial institutions, the region of Murcia looks to follow in
With European indices trading lower, the Dow Jones Euro Stoxx Chemicals index was down by 1.25%, as shares in many of
Petrochemical major BASF’s shares had fallen by 1.31%, while fellow Germany-based chemical company LANXESS’ shares were trading down by 4.34%.
Shares in Germany-based fertilizer producer K+S and chemical firm Wacker Chemie were trading down by 0.40% and 3.14% respectively, while France-based Arkema’s shares were trading down by 2.50% from the previous close.
Norway-based fertilizer producer Yara International saw its shares fall by 1.18%.
Meanwhile, concerns that Spain's financial situation could have a negative impact on fuel demand, also forced down oil prices.
($1 = €0.83) | http://www.icis.com/Articles/2012/07/23/9580084/europe-chem-stocks-fall-on-fears-spain-needs-full-sovereign.html | CC-MAIN-2014-52 | refinedweb | 176 | 55.64 |
#include <deal.II/distributed/cell_weights.h>
Anytime a parallel::TriangulationBase is repartitioned, either upon request or by refinement/coarsening, cells will be distributed amongst all subdomains to achieve an equally balanced workload. If the workload per cell varies, which is in general the case for hp::DoFHandler objects, we can take that into account by introducing individual weights for different cells.
This class allows computing these weights for load balancing by consulting the FiniteElement that is associated with each cell of a hp::DoFHandler. One can choose from predefined weighting algorithms provided by this class or provide a custom one.
This class offers two different ways of connecting the chosen weighting function to the corresponding signal of the linked parallel::TriangulationBase. The recommended way involves creating an object of this class which will automatically take care of registering the weighting function upon creation and de-registering it once destroyed. An object of this class needs to exist for every DoFHandler associated with the Triangulation we work on to achieve satisfying work balancing results. The connected weighting function may be changed anytime using the CellWeights::reinit() function. The following code snippet demonstrates how to achieve each cell being weighted by its current number of degrees of freedom. We chose a factor of
1000 that corresponds to the initial weight each cell is assigned to upon creation.
On the other hand, you are also able to take care of handling the signal connection manually by using the static member function of this class. In this case, an analogous code example looks as follows.
Definition at line 87 of file cell_weights.h.
An alias that defines the characteristics of a function that can be used for weighting cells during load balancing.
Such weighting functions take as arguments an iterator to a cell and the future finite element that will be assigned to it after repartitioning. They return an unsigned integer which is interpreted as the cell's weight or, in other words, the additional computational load associated with it.
Definition at line 102 of file cell_weights.h.
Constructor.
Definition at line 28 of file cell_weights.cc.
Destructor.
Disconnects the function previously connected to the weighting signal.
Definition at line 38 of file cell_weights.cc.
Constructor.
Definition at line 231 of file cell_weights.cc.
Connect a different
weighting_function to the Triangulation associated with the
dof_handler.
Disconnects the function previously connected to the weighting signal.
Definition at line 47 of file cell_weights.cc.
Converts a
weighting_function to a different type that qualifies as a callback function, which can be connected to a weighting signal of a Triangulation.
This function does not connect the converted function to the Triangulation associated with the
dof_handler.
Definition at line 131 of file cell_weights.cc.
Choose a constant weight
factor on each cell.
Definition at line 65 of file cell_weights.cc.
The pair of floating point numbers \((a,b)\) provided via
coefficients determines the weight \(w_K\) of each cell \(K\) with \(n_K\) degrees of freedom in the following way:
\[ w_K = a \, n_K^b \]
The right hand side will be rounded to the nearest integer since cell weights are required to be integers.
Definition at line 78 of file cell_weights.cc.
The container
coefficients provides pairs of floating point numbers \((a_i, b_i)\) that determine the weight \(w_K\) of each cell \(K\) with \(n_K\) degrees of freedom in the following way:
\[ w_K = \sum_i a_i \, n_K^{b_i} \]
The right hand side will be rounded to the nearest integer since cell weights are required to be integers.
Definition at line 102 of file cell_weights.cc.
Choose a constant weight
factor on each cell.
Definition at line 250 of file cell_weights.cc.
Choose a weight for each cell that is proportional to its number of degrees of freedom with a factor
factor.
Definition at line 272 of file cell_weights.cc.
Choose a weight for each cell that is proportional to its number of degrees of freedom squared with a factor
factor.
Definition at line 294 of file cell_weights.cc.
Register a custom weight for each cell by providing a function as a parameter.
Definition at line 316 of file cell_weights.cc.
A callback function that will be connected to the cell_weight signal of the
triangulation, to which the
dof_handler is attached. Ultimately returns the weight for each cell, determined by the
weighting_function provided as a parameter.
Definition at line 162 of file cell_weights.cc.
Pointer to the degree of freedom handler.
Definition at line 259 of file cell_weights.h.
Pointer to the Triangulation associated with the degree of freedom handler.
We store both to make sure to always work on the correct combination of both.
Definition at line 270 of file cell_weights.h.
A connection to the corresponding cell_weight signal of the Triangulation which is attached to the DoFHandler.
Definition at line 280 of file cell_weights.h. | https://dealii.org/current/doxygen/deal.II/classparallel_1_1CellWeights.html | CC-MAIN-2021-25 | refinedweb | 802 | 56.15 |
This action might not be possible to undo. Are you sure you want to continue?
10/27/2011
text
original
. . . . 127 2. . . . . . . .11 log null . . . . .6. . . . . . . 116 alert full . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 2.2 Configuration Specific Elements . . . 123 Attribute Table File Format . 117 database . . .3 2. . . . . . . . . . .10. . . . . . . . . . . . .11. . . . . . . . . . . . . . . . . 119 unified . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . .2 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . .1 Creating Multiple Configurations . . 130 2.6. . . . . . . . . . . . 133 2. . . . . . . . . . . . . . . . .5 Rule Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 2.6. . . . .6. . . . . . . . . . . 114 2. . . . . . . . . 117 alert unixsock . 122 2. . . . . . . . . . . .8 2. . .2 2. . . . . . . . . 123 2. . . . . . . 122 2. . . .4 React . . . . .6. . . . . . . . . . . . . . 117 log tcpdump . .8. . . . . . . . . . . . . 127 Directives . . . .9 alert syslog . . . . . . . . . . . . . . . . . . 120 unified 2 . . . . . . . . . . . . . . . .11. . . . . . . . . . . . . . . . . .4 2. . . . . . . . . . . . . .7. . . . . . . . . . .1 Enabling Active Response . . . .6.3 Enabling support . . . .11. . . .2 Configure Sniping . . . . . . . . . . .3 How Configuration is applied? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 2. . . . . .7. . . . . . . . . . . . . . . . . . . . . . .3 2. . . . . . . . . 123 2. . . . 132 2. . . . . . . . . . . . . . . . . . . . . . . .11 Active Response . . . . . . . . . . . 134 2. . . . . . . . . . . . . . . .6 2. 129 2. . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . .10. . . . . . . . . . . . . . .9. . . . . . . . . . . 124 Attribute Table Example . . . . . . .1 2. . 132 2. . . . . . . . .10 alert prelude . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . 133 2. . . . . . . . . . . . . . . . . 126 Dynamic Modules . . . . . . . . . 115 alert fast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8. . . . . 135 4 . . . . .12 alert aruba action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9. . 121 2. . . 133 2. . . . .6. . . . . .6. . . 128 Non-reloadable configuration options . . . . . . . . .13 Log Limits . . .1 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 2. . . . . . . . . . . . . . . . .6.10 Multiple Configurations . . . . . . . . . . . . . . .9 Reloading a Snort Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 2. . . . . . . . .7 2. . . . . . . .3 2. . . . . . . . . . . . . . . . . .6. .5 2. . . . . . . .7 Host Attribute Table . . . . . . . . . 111 Output Modules . . . . . . . 127 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Flexresp . . . . . . . . . . . . . . . . . . . . .2 Format . . . . . . . . . . . . . . . . . . . . .11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Packet Performance Monitoring (PPM) . . . . . . . . . 131 2. .8 Configuration Format . . . 118 csv . . . . . . . .7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9. . . . . . . 128 Reloading a configuration . . . . .2 2. . . . . . . .
. . .5. . . . . . . . . . . . . . . . . . . . .4. 149 3. . . . . . . . . . . . . . . . . . .4. 138 The Direction Operator . . 148 within .2. . . . . . . . 136 3. 147 distance . . . . .6 3.13 http method . . . . . .4. . . . . . . . 137 Port Numbers . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 3. . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16 http stat code . . . . . . . . . . . . . . . . . 140 reference . . . . . . . . . . . . . . . . . . . . . . .18 http encode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 http header . . . . . . . . .4. . . . . . . . . . . . . . .5. . . 142 classtype . .2. . . . . . . . .5. . . . . . . . . . . . . . .9 content .15 http raw uri . . . . . . . . . . . . . . . . . . . . .5 Payload Detection Rule Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 General Rule Options . . .5. . . . . . .1 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 rev . . . . . . . .5. . . . . . . . 145 3. . . . . .5. . . . . . . . . . . . . . . .2 3. . . . . . . . . . . . . . . . . . . . .2 3. . . . . . . . . 150 3. . . . . . . . . . . . . . .3 3. . . . . . . . . . . . . . 142 priority . . . . . . . 137 IP Addresses . . . . . . . .4 3. . . . . .4. . . . .5.10 http raw cookie . . . . 146 depth . . . . . .5. . . . . . . . . .5 3. . . . . . . . . . . . .12 http raw header . . . . . . . . . . . . . . . . . 146 rawbytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . .3 Writing Snort Rules 3. . . . . . . . . . . . . . . . . . . . . . . . . . .2 3. . . . . . . . . . . . . . . . . . . . . . . . . . . .14 http uri . . . . . . 151 3. . . . . . . . . .5. . . . . . . . . . 153 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 sid . . . . . . . . .4. 150 3. .4. . . . . . . . . . . . . . . . . . . . . . . .3 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . .8 3. . . . . . . . . . . . 153 5 . . 140 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 3. . . . . . . . . .9 msg . . . . . . 144 3. . . . . . . . . . . . . . . . . . 147 offset . . . . . . . . . . . . . .3 3. .6 Rule Actions . . . . . . 139 3. . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . .2. 144 General Rule Quick Reference . . . . . . . . . . . . 140 gid .5 3. . . . . . . . . . . . . . . . . . .8 3. . . . . . . . . . . . . . . . . . . . . .4. . . . . . . . . . .4 Rule Options . . . . . . . . . . . . . . . . . . . . . . . . . . 145 nocase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 3. . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 3. 152 3. . . . . . . . . . . . . . . . . . . . .5.4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 3. . . . . . . . . . . . . . . . . . . . . . .6 3. . . . . . . 152 3. . . . . . . . . . . . . .2 136 The Basics . . .4 3. . . . . . . . . . . . . . . .5. . . . . . . . . . . . 148 http client body . . . . . . . . . . .7 3. . . . . . . . . . . . . . . . . . . . . . . . . . 143 metadata . . . . . .1 3. . . .1 3. . . . .5 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 http stat msg . . . 136 Rules Headers . . . . . . . . . . . . . . .5. . . . . . . . . 138 Activate/Dynamic Rules . . . . . 136 Protocols . . . . 149 http cookie . . . . . . . . . . . . . . .
161 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . .29 byte extract . .5. . . . . . . . . . . 172 3. . . . . . . . .6.5. 168 fragbits . . . . . . . . . . . . . . . . . . . . .10 flowbits . . . . . . . . . . . . . . . . . . . . . . . . . . .30 ftpbounce . . . . . . . . . . . . . . . . .5.21 urilen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 3. . .5. . .38 Payload Detection Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 3. . . . . . 156 3. . . .6 Non-Payload Detection Rule Options . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . .35 dce stub data . . . 159 3. . . . . . . . . . . . . . .6 3. . . . . 167 id . . . . . . .5. . . . . . . . . . . .36 ssl version . . . . . . . . . . . . . . . 165 3. 166 3. . . . . . . . . . . . . .5. . . . . . . .6. . . . . . . . . . . .9 fragoffset . . . . . . . . . . 165 3. . . . . . . . . . . . . . . . . . . .5. 167 ipopts . . . . . . . . . . . . . .5. . . . .5 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . .8 3. . . . . . . . . . . . . . . . . . . . . 172 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16 icmp id . . . . . . . . . . . . . . . . 164 3. . . . . . . . . 158 3. . . . . . .26 base64 data . . . . . . . . . . . . . . .33 dce iface .25 base64 decode . 165 3. .6. . . 163 3. . . . 165 3. . . . . . . . . . . . . . 172 3. . . . . . . . . . . . . . . . .20 uricontent . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . 173 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 3. . . . . . . . . . . . .13 window . . . . . . .37 ssl state . . . . . .28 byte jump .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34 dce opnum . . . . . . . . . . . . . 157 3.6. . . . . . . . . . . . . . . . . . . . . . . . 162 3. . . . . . . . . . . . 157 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 3. . . . . . . . . . . . . . .22 isdataat . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 flow . . . . . . . 154 3. . . . . . . . . . . . . . . . . . . 164 3. . .32 cvs . . .27 byte test . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . 172 3. . . 168 dsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 3. 165 3. . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . .5. .5. . . . . . . . . . . . . . . . . 170 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 ttl . . . . . . . . . . . . . . . . . . . .23 pcre . . . . . . . . . . . . . . . . . . . . .6. .6. . . . . . . . . . . . 160 3. 166 tos . . . . .24 file data . . .4 3. .15 icode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . .6. . . . .12 ack . . . . . . . . . . . . . . 170 3. . . . .1 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 flags . .5. . . . . . . . . . . . . . . .17 icmp seq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 3. . . . . . . . . . . . . . . . . . . . . . . . .7 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 rpc . . . .14 itype . . . . . . . . . . .11 seq . . . . . . . . . . . . . . . . . . . .31 asn1 . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . .19 fast pattern . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . .6. . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .2 Preprocessor Example . . . . . . . . . . . . . . .6 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . .4 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 Catch the Oddities of the Protocol in the Rule . . . . . .9. . . . . . . . . . . . . . . . . . .9. . . . . . . . . . . . . . . . .7 3. .5 4 Content Matching . . . . . . . . . . 175 resp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 Rules . . . . . . . . .23 Non-Payload Detection Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . 180 Testing Numerical Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . .1 3. . . . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . .1 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 3. .2 4.10 detection filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 Optimizing Rules . . . . .7. . 185 Dynamic Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . 181 184 Dynamic Modules 4. . . 173 3. . . . . . . . . . . .7 Post-Detection Rule Options . 178 Writing Good Rules . . . . . . . . . . . 175 session . . .1. . .22 stream size . . . . . . 191 Detection Engine . . . . . . . . . . . . 176 tag . . . . . . . . . . . . . . . . . . 177 3. . . . . 177 replace . . . . 184 4. . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Examples . . . . .11 Post-Detection Quick Reference . . . . . . . . . . . . . 174 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . . . .9. . . . . .7. . . . .1. . . . . . . . . . . 176 react . . .7. . . . . 177 activated by . . . . . . . . . . . . . . . . . . . . . . 185 4. . . . 191 Rules . .6. . . . . . . . . . . . . . . . . . .21 stream reassemble . . . . . . . . . . . . . . . .4 4. . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 DynamicEngineData . . . . . . . . . . . . . . . . . .2.2 3. . . . 184 DynamicPreprocessorData . .8 3. . . . . . . . . . . .7. . . . . . . . . . .1 4. . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . . . .19 ip proto . . . . . . 190 4. . .20 sameip . . . . . . . . . . . . . .2 3.9 logto . . .7. . . . . . . . . . . . . . . . . . . . . . .5 DynamicPluginMeta . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 SFSnortPacket . . . . . . . . . . . . . . . . . . . . 175 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 3. . . . . . . . . .2 Required Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9. . . . . . . . . . . .9 Rule Thresholds . . . . . . . . . . 179 Catch the Vulnerability. . . . . . . . . . . . . . . . . . . . . . .6. . . . . . .7. . . . . . . . 192 4. . . . . . . . . . . . . 174 3. . . . . . . .3 Preprocessors . . . . . . . . . . . . . . . . . . . . .8 3. . . . . . . . .6. . . 176 activates . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . .3 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 7 . . . . . . . . . . . . . . . . . . . 177 count . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . .3 3. . . . . . . . . .1. . . . . . . . . . . .3. . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 4. . . . . . . . . .2 4. .3 4. . . . . . . . .4 3. . . . . . . . . . . . . . 173 3. 179 3. . . . . . . .9.1 4. . . . 177 3. . . . . . . .6. . .5 3. . . . . . . . . . . . . Not the Exploit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .2 197 Submitting Patches . . . . . . . . . . . . . 198 8 . . . .2. . . . . . . . . . . . . . . . . 197 Detection Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . 197 5. . . . . . . . . . . . . . . . . . . . 197 5. . . . . . . . . . . . . . . . . . . .3 The Snort Team . . . . . . . . . . . . 197 Snort Data Flow . . . . . . .2 5. . . . . . . . . .5 Snort Development 5. .1 5. . . . . . . . . . . . 197 Output Plugins . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . .1 5. . . . . . . . . . . . . . . . . . . . . . .3 Preprocessors . . . . . . . . . .
do this: 9 .org> and now is maintained by the Snort Team. which simply reads the packets off of the network and displays them for you in a continuous stream on the console (screen).tex. let’s start with the basics. 1. and it’s not always obvious which ones go together well. Before we proceed. sniffer mode). showing the data link layer headers. If you want to see the application data in transit. If you have a better way to say something or find that something in the documentation is outdated. It was then maintained by Brian Caswell <bmc@snort. the most complex and configurable configuration. Small documentation updates are the easiest way to help out the Snort Project. which logs the packets to disk. • Packet Logger mode. 1.1 Getting Started Snort really isn’t very hard to use.org>. there are a few basic concepts you should understand about Snort. which allows Snort to analyze network traffic for matches against a user-defined rule set and performs several actions based upon what it sees.e. drop us a line and we will update A it. Snort can be configured to run in three modes: • Sniffer mode. This file aims to make using Snort easier for new users.2 Sniffer Mode First. If you just want to print out the TCP/IP packet headers to the screen (i. try this: . If you want an even more descriptive display. you can find the latest version of the documentation in LTEX format in the Snort CVS repository at /doc/snort_manual. • Network Intrusion Detection System (NIDS) mode. nothing else. If you would like to submit patches for this document./snort -vd This instructs Snort to display the packet data as well as the headers./snort -v This command will run Snort and just show the IP and TCP/UDP/ICMP headers. try the following: . but there are a lot of command line options to play with.Chapter 1 Snort Overview This manual is based on Writing Snort Rules by Martin Roesch and further work from Chris Green <cmg@snort.
1. you can try something like this: 10 . The last command could also be typed out as: . Snort can also read the packets back by using the -r switch. all of these commands are pretty cool./log -h 192. Once the packets have been logged to the binary file. ! △NOTE both the source and destination hosts are on the home network. it collects every packet it sees and places it in a directory hierarchy based upon the IP address of one of the hosts in the datagram. the source address. When Snort runs in this mode. which puts it into playback mode. Binary mode logs the packets in tcpdump format to a single binary file in the logging directory: .. you can read the packets back out of the file with any sniffer that supports the tcpdump binary format (such as tcpdump or Ethereal)./snort -vde (As an aside. you may notice that Snort sometimes uses the address of the remote computer as the directory in which it places packets and sometimes it uses the local host address. this assumes you have a directory named log in the current directory.0 class C network. If you don’t. Additionally.168. you need to specify a logging directory and Snort will automatically know to go into packet logger mode: . We don’t need to specify a home network any longer because binary mode logs everything into a single file. they are logged to a directory Note that if with a name based on the higher of the two port numbers or. which eliminates the need to tell it how to format the output directory structure./log -b Note the command line changes here. All incoming packets will be recorded into subdirectories of the log directory.168. these switches may be divided up or smashed together in any combination.168. if you wanted to run a binary log file through Snort in sniffer mode to dump the packets to the screen. in the case of a tie. Packets from any tcpdump formatted file can be processed through Snort in any of its run modes. and you want to log the packets relative to the 192. In order to log relative to the home network.. but if you want to record the packets to the disk.1) host. If you’re on a high speed network or you want to log the packets into a more compact form for later analysis./snort -l ./snort -d -v -e and it would do the same thing./snort -dev -l . not just sections of it. you don’t need to run in verbose mode or specify the -d or -e switches because in binary mode the entire packet is logged.1. you need to tell Snort which network is the home network: ./log Of course.0/24 This rule tells Snort that you want to print out the data link and TCP/IP headers as well as application data into the directory . For example. Snort will exit with an error message. with the directory names being based on the address of the remote (non-192. If you just specify a plain -l switch. you should consider logging in binary mode./log.) 1.3 Packet Logger Mode OK./snort -dev -l .
One thing to note about the last command line is that if Snort is going to be used in a long term way as an IDS. syslog. and none. the -v switch should be left off the command line for the sake of speed.4. so you can usually omit the -e switch. try this: .. .168. Sends “fast-style” alerts to the console (screen). as well as with the BPF interface that’s available from the command line. This will apply the rules configured in the snort. cmg. simply specify a BPF filter at the command line and Snort will only see the ICMP packets in the file: . logging packets that trigger rules specified in the snort.conf is the name of your snort configuration file.0/24 -l . Writes the alert in a simple format with a timestamp.conf This will configure Snort to run in its most basic NIDS form. 1. These options are: Option -A fast -A full -A -A -A -A unsock none console cmg Description Fast alert mode. alert message. Alert modes are somewhat more complex./snort -dev -l . Sends alerts to a UNIX socket that another program can listen on. It’s also not necessary to record the data link headers for most applications. Generates “cmg style” alerts. This is the default alert mode and will be used automatically if you do not specify a mode. For example.1. Turns off alerting.168. too. source and destination IPs/ports.log You can manipulate the data in the file in a number of ways through Snort’s packet logging and intrusion detection modes. if you only wanted to see the ICMP packets from the log file./log -c snort./log -h 192. and packets can be dropped while writing to the display./snort -d -h 192.1 NIDS Mode Output Options There are a number of ways to configure the output of Snort in NIDS mode.0/24 -c snort. If you don’t specify an output directory for the program. console. There are several other alert output modes available at the command line.conf file to each packet to decide if an action based upon the rule type in the file should be taken. The default logging and alerting mechanisms are to log in decoded ASCII format and use full alerts./snort -dv -r packet. it will default to /var/log/snort. 11 . There are seven alert modes available at the command line: full. read the Snort and tcpdump man pages.1. socket.conf where snort. The screen is a slow place to write data to. 1.log icmp For more info on how to use the BPF interface. as well as two logging facilities./snort -dvr packet.conf in plain ASCII to disk using a hierarchical directory structure (just like packet logger mode).4 Network Intrusion Detection System Mode To enable Network Intrusion Detection System (NIDS) mode so that you don’t record every single packet sent down the wire. Six of these modes are accessed with the -A command line switch. Full alert mode. fast. The full alert mechanism prints out the alert message in addition to the full packet headers.
For example: .168. This number is primarily used when writing signatures.map. you need to use unified logging and a unified log reader such as barnyard.0/24 1. use the following command line to log to the default facility in /var/log/snort and send alerts to a fast alert file: . The second number is the Snort ID (sometimes referred to as Signature ID). use the output plugin directives in snort. 56 represents a T/TCP event. If you want to configure other facilities for syslog output. as each rendition of the rule should increment this number with the rev option. this tells the user what component of Snort generated this alert.3 High Performance Configuration If you want Snort to go fast (like keep up with a 1000 Mbps connection). In this case. use the -s switch. please read etc/generators in the Snort source. 1./snort -b -A fast -c snort.6.conf 12 . To disable packet logging altogether./snort -c snort. For example. For a list of preprocessor SIDs. Rule-based SIDs are written directly into the rules with the sid option.1 for more details on configuring syslog output.4. If you want a text file that’s easily parsed. see Section 2.Packets can be logged to their default decoded ASCII format or to a binary log file via the -b command line switch. it will usually look like the following: [**] [116:56:1] (snort_decoder): T/TCP Detected [**] The first number is the Generator ID.0/24 -s As another example. To send alerts to syslog.2 Understanding Standard Alert Output When Snort generates an alert message./snort -c snort. we know that this event came from the “decode” (116) component of Snort.6. The default facilities for the syslog alerting mechanism are LOG AUTHPRIV and LOG ALERT.conf -l . but still somewhat fast./log -h 192.conf. This will log packets in tcpdump format and produce minimal alerts.4. For output modes available through the configuration file. please see etc/gen-msg. This allows debugging of configuration issues quickly via the command line.168. This allows Snort to log alerts in a binary form as fast as possible while another program performs the slow actions. In this case. The third number is the revision ID. use the -N command line switch. use the following command line to log to default (decoded ASCII) facility and send alerts to syslog: . See Section 2. ! △NOTE Command line logging options override any output options specified in the configuration file. For a list of GIDs.1. try using binary logging with the “fast” output mechanism.1.conf -A fast -h 192. such as writing to a database.
• --alert-before-pass option forces alert rules to take affect in favor of a pass rule. in that the event processing is terminated when a pass rule is encountered. please refer to the --alert-before-pass option. or Data Acquisition library. For more information. It is possible to select the DAQ type and mode when invoking Snort to perform PCAP readback or inline operation.1. This allows use of an inline policy with passive/IDS mode. then the Drop rules. The sdrop rules are not loaded. • --process-all-events option causes Snort to process every event associated with a packet. Several command line options are available to change the order in which rule actions are taken. • --treat-drop-as-alert causes drop and reject rules and any associated alerts to be logged as alerts. while taking the actions based on the rules ordering.5 Packet Acquisition Snort 2. etc. Without this option (default case). ! △NOTE Sometimes an errant pass rule could cause alerts to not show up. you can select and configure the DAQ when Snort is invoked as follows: . in which case you can change the default ordering to allow Alert rules to be applied before Pass rules. However.1 Configuration Assuming that you did not disable static modules or change the default DAQ type. The DAQ replaces direct calls to PCAP functions with an abstraction layer that facilitates operation on a variety of hardware and software interfaces without requiring changes to Snort. you can run Snort just as you always did for file readback or sniffing an interface. then the Alert rules and finally. 1. only the events for the first action based on rules ordering are processed. ! △NOTE Pass rules are special cases here. The Pass rules are applied first.5. rather then the normal action.4.4 Changing Alert Order The default way in which Snort applies its rules to packets may not be appropriate for all installations. Log rules are applied.. for packet I/O. regardless of the use of --process-all-events.9 introduces the DAQ.
MMAPed pcap On Linux. if configured in both places. Note that if Snort finds multiple versions of a given library. On Ethernet. the maximum size is 32768./snort [--daq-list <dir>] The above command searches the specified directory for DAQ modules and prints type. By using PCAP FRAMES=max. Phil Woods (cpw@lanl./snort -i <device> . the most recent version is selected. and if that hasn’t been set. PCAP FRAMES is the size of the ring buffer. Once Snort linked against the shared memory libpcap. Also. The shared memory ring buffer libpcap can be downloaded from his website at. if snort is run w/o any DAQ arguments. and directory may be specified either via the command line or in the conf file. -r will force it to read-file./snort --daq pcap --daq-var buffer_size=<#bytes> Note that the pcap DAQ does not count filtered packets. variable./snort -r <file> . You may include as many variables and directories as needed by repeating the arg / config. a modified version of libpcap is available that implements a shared memory ring buffer. This feature is not available in the conf. . -Q and –daq-mode inline are allowed. libpcap is able to queue packets into a shared buffer that Snort is able to read directly. the mode defaults to passive. 1. the command line overrides the conf. -Q will force it to inline. 14 . libpcap will automatically use the most frames possible. enabling the ring buffer is done via setting the environment variable PCAP FRAMES.gov/cpw/./snort --daq pcap --daq-mode read-file -r <file> You can specify the buffer size pcap uses with: .5. for a total of around 52 Mbytes of memory for the ring buffer alone. this ends up being 1530 bytes per frame. but -Q and any other DAQ mode will cause a fatal error at start-up. version. Instead of the normal mechanism of copying the packets from kernel memory into userland memory.gov) is the current maintainer of the libpcap implementation of the shared memory ring buffer. mode./snort --daq pcap --daq-mode passive -i <device> . it will operate as it always did using this module. by using a shared memory ring buffer. DAQ type may be specified at most once in the conf and once on the command line. According to Phil. This applies to static and dynamic versions of the same library. as this appears to be the maximum number of iovecs the kernel can handle.2 PCAP pcap is the default DAQ. If the mode is not set explicitly. since there is no conflict.<mode> ::= read-file | passive | inline <var> ::= arbitrary <name>=<value> passed to DAQ <dir> ::= path where to look for DAQ module so’s The DAQ type. and attributes of each.lanl. This change speeds up Snort by limiting the number of times the packet is copied before Snort gets to perform its detection upon it. and if that hasn’t been set. These are equivalent: .
/snort --daq afpacket -i <device> [--daq-var buffer_size_mb=<#MB>] [--daq-var debug] If you want to run afpacket in inline mode.5 MB. default is 0 Notes on iptables are given below. here’s why.65535. you must set device to one or more interface pairs.3 AFPACKET afpacket functions similar to the memory mapped pcap DAQ but no external library is required: . 5.65535. the numbers break down like this: 1./snort --daq nfq \ [--daq-var device=<dev>] \ [--daq-var proto=<proto>] \ [--daq-var queue=<qid>] \ [--daq-var queue_len=<qlen>] <dev> ::= ip | eth0. default is 0 <qlen> ::= 0.. default is ip4 <qid> ::= 0. The frame size is 1518 (snaplen) + the size of the AFPacket header (66 bytes) = 1584 bytes. 1.5. etc. Actual memory allocated is 42366 * 4 KB = 165. As a result.4 NFQ NFQ is the new and improved way to process iptables packets: . The number of frames is 128 MB / 1518 = 84733.5. default is IP injection <proto> ::= ip4 | ip6 | ip*. where each member of a pair is separated by a single colon and each pair is separated by a double colon like this: eth0:eth1 or this: eth0:eth1::eth2:eth3 By default. The smallest block size that can fit at least one frame is 4 KB = 4096 bytes @ 2 frames per block. You can change this with: --daq-var buffer_size_mb=<#MB> Note that the total allocated is actually higher.. 15 . we need 84733 / 2 = 42366 blocks. the afpacket DAQ allocates 128MB for packet memory. 4. 3.1. 2. Assuming the default packet memory with a snaplen of 1518.
/configure --enable-inline / -DGIDS Start the IPQ DAQ as follows: . start Snort like this: .6 IPFW IPFW is available for BSD systems.65535. 1. Furthermore./snort --daq ipq \ [--daq-var device=<dev>] \ [--daq-var proto=<proto>] \ <dev> ::= ip | eth0. . It replaces the inline version available in pre-2../snort -r <pcap> --daq dump By default a file named inline-out.9 Snort like injection and normalization. you will probably want to have the pcap DAQ acquire in another mode like this: . 1.pcap will be created containing all packets that passed through or were generated by snort. It replaces the inline version available in pre-2.5 IPQ IPQ is the old way to process iptables packets.9 versions built with this: .1./snort -r <pcap> -Q --daq dump --daq-var load-mode=read-file . default is IP injection <proto> ::= ip4 | ip6./snort -J <port#> Instead. ./snort --daq dump --daq-var file=<name> dump uses the pcap daq for packet acquisition./snort -i <device> -Q --daq dump --daq-var load-mode=passive 16 . Note that the dump DAQ inline mode is not an actual inline mode.5. default is ip4 Notes on iptables are given below.5. You can optionally specify a different name.5. It therefore does not count filtered packets./snort --daq ipfw [--daq-var port=<port>] <port> ::= 1.9 versions built with this: .7 Dump The dump DAQ allows you to test the various inline mode features available in 2. etc./snort -i <device> --daq dump ./configure --enable-ipfw / -DGIDS -DIPFW This command line argument is no longer supported: . default is 8000 * IPFW only supports ip4 traffic.
you can give it a packet capture to read. Can specify path to pcap or directory to recurse to get pcaps.1.pcap 17 . Reset to use no filter when getting pcaps from file or directory. Injected packets Snort generated and sent. Shell style filter to apply when getting pcaps from file or directory. Added for completeness.pcap $ snort --pcap-single=foo. that specifying --pcap-reset and --pcap-show multiple times has the same effect as specifying them once.8 Statistics Changes The Packet Wire Totals and Action Stats sections of Snort’s output include additional fields: • Filtered count of packets filtered out and not handed to Snort for analysis.5. reset snort to post-configuration state before reading next pcap. A space separated list of pcaps to read. • Ignore packets that caused Snort to allow a flow to pass w/o inspection by this instance of Snort.2 Examples Read a single pcap $ snort -r foo. The action stats show ”blocked” packets instead of ”dropped” packets to avoid confusion between dropped packets (those Snort didn’t actually see) and blocked packets (those Snort did not allow to pass). If reading multiple pcaps. Note. 1. • Whitelist packets that caused Snort to allow a flow to pass w/o inspection by any analysis program. however. is not to reset state. Option -r <file> --pcap-single=<file> --pcap-file=<file> --pcap-list="<list>" --pcap-dir=<dir> --pcap-filter=<filter> Description Read a single pcap.e. without this option. Sorted in ASCII order. i. Snort will read and analyze the packets as if they came off the wire. Same as -r. A directory to recurse to look for pcaps. 1. This can be useful for testing and debugging Snort.1 Command line arguments Any of the below can be specified multiple times on the command line (-r included) and in addition to other Snort command line options. This filter will apply to any --pcap-file or --pcap-dir arguments following. eg due to a block rule. • Blacklist packets that caused Snort to block a flow from passing. eg TCP resets. File that contains a list of pcaps to read.6. • Replace packets Snort modified. • Block packets Snort did not forward. Print a line saying what pcap is currently being read. The default. --pcap-no-filter --pcap-reset --pcap-show 1. • Allow packets Snort analyzed and did not take action on.6.6 Reading Pcaps Instead of having Snort listen on an interface.
pcap --pcap-file=foo. then no filter will be applied to the files found under /home/foo/pcaps. so only files ending in ”.pcap foo2.pcap" --pcap-file=foo. Read pcaps under a directory $ snort --pcap-dir="/home/foo/pcaps" This will include all of the files under /home/foo/pcaps. the first filter ”*.pcap and all files under /home/foo/pcaps.cap” will be applied to files found under /home/foo/pcaps2.pcap" --pcap-dir=/home/foo/pcaps The above will only include files that match the shell pattern ”*.pcap" This will read foo1.pcap and foo3.pcap --pcap-file=foo.Read pcaps from a file $ cat foo. the first filter will be applied to foo.cap" --pcap-dir=/home/foo/pcaps2 In this example.txt.txt foo1. The addition of the second filter ”*. then no filter will be applied to the files found under /home/foo/pcaps.txt This will read foo1.cap" --pcap-dir=/home/foo/pcaps In the above.pcap” will only be applied to the pcaps in the file ”foo. $ snort --pcap-filter="*.pcap.txt \ > --pcap-filter="*.pcap”.txt \ > --pcap-no-filter --pcap-dir=/home/foo/pcaps In this example. $ snort --pcap-filter="*.cap” will cause the first filter to be forgotten and then applied to the directory /home/foo/pcaps. foo2. so all files found under /home/foo/pcaps will be included. then the filter ”*.cap” will be included from that directory. 18 . Note that Snort will not try to determine whether the files under that directory are really pcap files or not. in other words. Using filters $ cat foo.txt” (and any directories that are recursed in that file).pcap.pcap --pcap-file=foo.pcap /home/foo/pcaps $ snort --pcap-filter="*.pcap.pcap foo2. foo2.pcap /home/foo/pcaps $ snort --pcap-file=foo.txt foo1. so all files found under /home/foo/pcaps will be included. any file ending in ”.txt. Read pcaps from a command line list $ snort --pcap-list="foo1. $ snort --pcap-filter="*. the first filter will be applied to foo.pcap foo3.txt \ > --pcap-no-filter --pcap-dir=/home/foo/pcaps \ > --pcap-filter="*.pcap foo2.txt $ snort --pcap-filter="*.pcap”.
it will be like Snort is seeing traffic for the first time. Example: =============================================================================== Packet I/O Totals: Received: 3716022 Analyzed: 3716022 (100.2 Packet I/O Totals This section shows basic packet acquisition and injection peg counts obtained from the DAQ. in which case it is shown per pcap. statistics reset. minutes.1 Timing Statistics This section provides basic timing statistics. 1. etc.7. Snort ran for 0 days 0 hours 2 minutes 55 seconds Pkts/min: 1858011 Pkts/sec: 21234 =============================================================================== 1.000%) 19 .856509 seconds Snort processed 3716022 packets.7. meaning all buffers will be flushed. but after each pcap is read. This does not include all possible output data. • Injected packets are the result of active response which can be configured for inline or passive modes. and only shown when non-zero. Printing the pcap $ snort --pcap-dir=/home/foo/pcaps --pcap-show The above example will read all of the files under /home/foo/pcaps and will print a line indicating which pcap is currently being read. The rates are based on whole seconds. • Outstanding indicates how many packets are buffered awaiting processing. If you are reading pcaps. The others are summarized below. Many of these are self-explanatory. Example: =============================================================================== Run time for packet processing was 175.Resetting state $ snort --pcap-dir=/home/foo/pcaps --pcap-reset The above example will read all of the files under /home/foo/pcaps. For each pcap. It includes total seconds and packets as well as packet processing rates. • Filtered packets are not shown for pcap DAQs. Snort will be reset to a post-configuration state. The way this is counted varies per DAQ so the DAQ documentation should be consulted for more info.7 Basic Output Snort does a lot of work and outputs some useful statistics when it is done. unless you use –pcap-reset. etc. 1. the totals are for all pcaps combined. just the
This switch obfuscates your IP addresses in packet printouts. it acts as an IPS allowing drop rules to trigger. Snort policies can be configured in these three modes too./usr/local/bin/snort -c /usr/local/etc/snort. the -G command line option was added that specifies an instance identifier for the event logs. it acts as a IDS.1. This option can be used when running multiple instances of snort. and inline-test.log -O -h 192.5 Snort Modes Snort can operate in three different modes namely tap (passive). Users can specify either a decimal value (-G 1) or hex value preceded by 0x (-G 0x11).168. allowing evaluation of inline behavior without affecting traffic. or on the same CPU but a different interface. either on different CPUs. Each Snort instance will use the value specified to generate unique event IDs. obfuscating only the addresses from the 192.0/24 class C network: . Snort can be configured to run in inline-test mode using the command line option (–enable-inline-test) or using the snort config option policy mode as follows: 24 . For example. inline.3 Obfuscating IP Address Printouts If you need to post packet logs to public mailing lists. The drop rules will be loaded and will be triggered as a Wdrop (Would Drop) alert.168.4. This is useful if you don’t care who sees the address of the attacking host.9.9. 1. you could use the following command to read the packets from a log file and dump them to the screen.0/24 1. You can also combine the -O switch with the -h switch to only obfuscate the IP addresses of hosts on the home network.9. Explanation of Modes • Inline When Snort is in Inline mode.conf: config dump-dynamic-rules-path: /tmp/sorules In the above mentioned scenario the dump path is set to /tmp/sorules.conf \ --dump-dynamic-rules snort. also supported via a long option --logid.1. 1. Snort can be configured to passive mode using the snort config option policy mode as follows: config policy_mode:tap • Inline-Test Inline-Test mode simulates the inline mode of snort.4 Specifying Multiple-Instance Identifiers In Snort v2./snort -d -v -r snort. you might want to use the -O switch. Drop rules are not loaded (without –treat-drop-as-alert). This is handy if you don’t want people on the mailing list to know the IP addresses involved.
so sit back with a beverage of your choosing and read the documentation and mailing list archives.snort. a backslash (\) is needed to escape the ?.snort --enable-inline-test config policy_mode:inline_test ! △NOTE Please note –enable-inline-test cannot be used in conjunction with -Q. 25 . ! △NOTE In many shells. The Snort manual page and the output of snort -? or snort --help contain information that can help you get Snort running in several different modes. There’s a lot to Snort.sourceforge. so you may have to type snort -\? instead of snort -? for a list of Snort command line options.theaimsgroup..net provide informative announcements as well as a venue for community discussion and support.com/?l=snort-users at snort-users@lists.10 More Information Chapter 2 contains much information about many configuration options available in the configuration file.org) and the Snort Users mailing list:. The Snort web page (.
10.0/24.conf indicated on the Snort command line. Without IPv6 support. It works much like an #include from the C programming language. or portvar keywords as follows: var RULES_PATH rules/ portvar MY_PORTS [22.1024:1050] ipvar MY_NET [192.1.1 Includes The include keyword allows other snort config files to be included within the snort. Note that there Included files will substitute any predefined variable values into their own variable references. 2. msg:"SYN packet". 2.168. use a regular ’var’.1. Note: ’ipvar’s These are simple substitution variables set with the var.) include $RULE_PATH/example.2 for more information on defining and using variables in Snort config files.2 Variables Three types of variables may be defined in Snort: • var • portvar • ipvar ! △NOTE are only enabled with IPv6 support.rule 26 .1.Chapter 2 Configuring Snort 2.1 Format include <include file path/name> ! △NOTE is no semicolon at the end of this line. ipvar.1.0/24] alert tcp any any -> $MY_NET $MY_PORTS (flags:S.80.1. reading the contents of the named file and adding the contents in the place where the include statement appears in the file.1. See Section 2.
If IPv6 support is enabled.0 to 2.2. IP lists now OR non-negated elements and AND the result with the OR’ed negated elements.2.0/24. The following example list will match the IP 1.0/8. ’any’ will specify any ports. Previously.) The following examples demonstrate some invalid uses of IP variables and IP lists.1.!1.) alert tcp [1. Valid port ranges are from 0 to 65535. See below for some valid examples if IP variables and IP lists.2.1.255.1.2.![2.2.1.IP Variables and IP Lists IPs may be specified individually. The element ’any’ can be used to match all IPs.2.0/24.2.0.2.1. ranges.2.1. negated IP ranges that are more general than non-negated IP ranges are not allowed. Negation is handled differently compared with Snort versions 2.) Logical contradictions: ipvar EXAMPLE [1. IPs.2. each element in a list was logically OR’ed together.!1. Variables.) Different use of !any: ipvar EXAMPLE !any alert tcp $EXAMPLE any -> any any (msg:"Example".0.1.2. sid:1.2. Use of !any: ipvar EXAMPLE any alert tcp !$EXAMPLE any -> any any (msg:"Example".2.1.1. in a list.2.2.1.x and earlier. such as in: [10:50.2.sid:3.2. as a CIDR block.0/24. but it will be deprecated in a future release.0/24] any -> any any (msg:"Example".2.2.sid:2.2.888:900] 27 .sid:3.1. with the exception of IPs 2. IP lists.2. and CIDR blocks may be negated with ’!’.3. Also.2 and 2.3]] The order of the elements in the list does not matter.1.7.![2.2. Also.2.1.1.2. IP variables should be specified using ’ipvar’ instead of ’var’.2. or lists may all be negated with ’!’.1.1] Nonsensical negations: ipvar EXAMPLE [1.3]] alert tcp $EXAMPLE any -> any any (msg:"Example".!1. or any combination of the three.1.0/16] Port Variables and Port Lists Portlists supports the declaration and lookup of ports and the representation of lists and ranges of ports. [1. Lists of ports must be enclosed in brackets and port ranges may be specified with a ’:’. Using ’var’ for an IP variable is still allowed for backward compatibility. ipvar EXAMPLE [1.1. although ’!any’ is not allowed.1.1 and IP from 2.2.0. but ’!any’ is not allowed.
For backwards compatibility. The following examples demonstrate several valid usages of both port variables and port lists.!80] Ports out of range: portvar EXAMPLE7 [65536] Incorrect declaration and use of a port variable: var EXAMPLE8 80 alert tcp any $EXAMPLE8 -> any any (msg:"Example".100:200] alert tcp any $EXAMPLE1 -> any $EXAMPLE2_PORT (msg:"Example".Port variables should be specified using ’portvar’. provided the variable name either ends with ’ PORT’ or begins with ’PORT ’.) alert tcp any $PORT_EXAMPLE2 -> any any (msg:"Example". sid:4. sid:5. portvar EXAMPLE1 80 var EXAMPLE2_PORT [80:90] var PORT_EXAMPLE2 [1] portvar EXAMPLE3 any portvar EXAMPLE4 [!70:90] portvar EXAMPLE5 [80. sid:2. a ’var’ can still be used to declare a port variable. as described in the following table: 28 . You can define meta-variables using the $ operator.) Variable Modifiers Rule variable names can be modified in several ways. The use of ’var’ to declare a port variable will be deprecated in a future release. sid:1.) Port variable used as an IP: alert tcp $EXAMPLE1 any -> any any (msg:"Example".) Several invalid examples of port variables and port lists are demonstrated below: Use of !any: portvar EXAMPLE5 !any var EXAMPLE5 !any Logical contradictions: portvar EXAMPLE6 [80.) alert tcp any 90 -> any [100:1000. These can be used with the variable modifier operators ? and -.9999:20000] (msg:"Example".91:95. sid:3.
Here is an example of advanced variable usage in action: ipvar MY_NET 192.90] Likewise. but old-style variables (with the ’var’ keyword) can not be embedded inside a ’portvar’. Valid embedded variable: portvar pvar1 80 portvar pvar2 [$pvar1.1. They should be renamed instead: Invalid redefinition: var pvar 80 portvar pvar 90 2. For instance. types can not be mixed. Replaces the contents of the variable var with “default” if var is undefined.0/24 log tcp any any -> $(MY_NET:?MY_NET is undefined!) 23 Limitations When embedding variables.168. Replaces with the contents of variable var.90] Invalid embedded variable: var pvar1 80 portvar pvar2 [$pvar1. Format config <directive> [: <value>] 29 .1. variables can not be redefined if they were previously defined as a different type. Replaces with the contents of variable var or prints out the error message and exits
• debug-print-rule-group-build-details – Prints port group information during port group compilation.config detection: [debug] Options for detection engine debugging. Only useful if Snort was configured with –enable-inline-init-failopen. Dumps raw packet starting at link layer (snort -X). Turns off alerts generated by T/TCP options. • debug-print-rule-groups-compiled – Prints compiled port group information. Turns off alerts generated by T/TCP options. Disables option length validation alerts. Dumps application layer (snort -d). config enable decode oversized alerts Enable alerting on packets that have headers containing length fields for which the value is greater than the length of the packet. Enables the dropping of bad packets identified by decoder (only applicable in inline mode). • debug-print-rule-groups-uncompiled – Prints uncompiled port group information. • debug-print-fast-pattern – For each rule with fast pattern content.. prints information about the content being used for the fast pattern matcher. config disable decode alerts config disable inline init failopen Turns off the alerts generated by the decode phase of Snort. [debug-print-fast-pattern] [bleedover-warnings-enabled] • debug-print-nocontent-rule-tests – Prints port group information during packet evaluation. Disables failopen thread that allows inline traffic to pass while Snort is starting up. (snort --disable-inline-init-failopen) Disables IP option length validation alerts. [debug-print-nocontent-rule-tests] [debug-print-rule-group-build-details] • debug [debug-print-rule-groups-uncompiled] – Prints fast pattern information for a particular port [debug-print-rule-groups-compiled] group. Turns off alerts generated by experimental TCP options. 34 . Turns on character dumps (snort -C).
IP. Enables the dropping of bad packets with bad/truncated IP options (only applicable in inline mode). Sets the network interface (snort -i). it is off. config flowbits size: config ignore ports: <port-list> config interface: <num-bits> <proto> <iface> 35 . Enables support for MPLS multicast.4. (only applicable in inline mode). followed by a list of ports. Enables support for overlapping IP addresses in an MPLS network. (only applicable in inline mode). UDP. However. Specifies the maximum number of flowbit tags that can be used within a rule set. this configuration option should not be turned on. Enables the dropping of bad packets with bad/truncated TCP option (only applicable in inline mode). Enables the dropping of bad packets with obsolete TCP option. When this option is off and MPLS multicast traffic is detected. there could be situations where two private networks share the same IP space and different MPLS labels are used to differentiate traffic from the two VPNs. Snort’s packet decoder only decodes Teredo (IPv6 over UDP over IPv4) traffic on UDP port 3544. Enables the dropping of bad packets with T/TCP option. The default is 1024 bits and maximum is 2096. You can use the following options: • max queue <integer> (max events supported) • log <integer> (number of events to log) • order events [priority|content length] (how to order events within the queue) See Section 2. Snort will generate an alert. In such a situation. By default. Specify the protocol (TCP. it is off. Specifies conditions about Snort’s event queue. In a normal situation.4 for more information and examples. This option is needed when the network allows MPLS multicast traffic. enable decode oversized alerts must also be enabled for this to be effective (only applicable in inline mode). (only applicable in inline mode). Specifies ports to ignore (useful for ignoring noisy NFS traffic). or ICMP). (only applicable in inline mode). Enables the dropping of bad packets with T/TCP option. By default. Set global memcap in bytes for thresholding. Enables the dropping of bad packets with experimental TCP option. Port ranges are supported. Default is 1048576 bytes (1 megabyte). this configuration option should be turned on. This option makes Snort decode Teredo traffic on all UDP ports. where there are no overlapping IP addresses.
The default is 10000. See Section 2. up to the PCRE library compiled limit (around 10 million). frag timeout <secs>] [. This option is only supported with a Host Attribute Table (see section 2. Sets a Snort-wide minimum ttl to ignore all traffic. Disables logging. Sets a Snort-wide limit on the number of MPLS headers a packet can have. Obfuscates IP Addresses (snort -O). binding version must be in any file configured with config binding. Restricts the amount of stack used by a given PCRE option. max frag sessions <max-track>] The following options can be used: • bsd icmp frag alert on|off (Specify whether or not to alert.2 for more details. up to the PCRE library compiled limit (around 10 million). The snort default value is 1500.5. Disables pcre pattern matching. For example. 36 .7). Supply versioning information to configuration files. See Section 2. ipv6 and ethernet are also valid options. eg: pass alert log activation. Its default value is -1. The snort default value is 1500.config ipv6 frag: [bsd icmp frag alert on|off] [. Sets a limit on the maximum number of hosts to read from the attribute table. A value of 0 results in no PCRE evaluation. Sets a Snort-wide MPLS payload type.before Snort has had a chance to load a previous configuration.5. which means that there is no limit on label chain length. This option is used to avoid race conditions when modifying and loading a configuration within a short time span . Print statistics on rule performance. In addition to ipv4. In addition. (snort -N). Default is on) • bad ipv6 frag alert on|off (Specify whether or not to alert. Minimum value is 32 and the maximum is 524288 (512k). it will limit the number of nested repeats within a pattern. Restricts the amount of backtracking a given PCRE option. Note: Alerts will still occur.). This option is only useful if the value is less than the pcre match limit Exits after N packets (snort -n). A value of -1 allows for unlimited PCRE. Changes the order that rules are evaluated. The default MPLS payload type is ipv4 Disables promiscuous mode (snort -p). Print statistics on preprocessor performance. bad ipv6 frag alert on|off] [. an error is logged and the remainder of the hosts are ignored. A value of -1 allows for unlimited PCRE. If the number of hosts in the attribute table exceeds this value.1 for more details. A value of 0 results in no PCRE evaluation. Base version should be a string in all configuration files including included ones.
Causes Snort to ignore vlan headers for the purposes of connection tracking. from which to send responses. Sets UID to <id> (snort -u). Specifies a pcap file to use (instead of reading from network). See Section 3. this option sets the maximum number of packets to be tagged regardless of the amount defined by the other metric. Uses UTC instead of local time for timestamps (snort -U). NOTE: The command line switch -q takes effect immediately after processing the command line parameters. Set global memcap in bytes for thresholding. Uses verbose logging to STDOUT (snort -v). When a metric other than packets is used in a tag option in a rule.conf takes effect when the configuration line in snort. Setting this option to a value of 0 will disable the packet limit. Default is 0. Sets umask when running (snort -m). same effect as -P <snaplen> or --snaplen <snaplen> options. inline or inline test.).config quiet config read bin file: config reference: <pcap> <ref> config reference net <cidr> config response: [attempts <count>] [.5 on using the tag option when writing rules for more details. Shows year in timestamps (snort -y). Default is 1048576 bytes (1 megabyte).7. Adds a new reference system to Snort. Maximum value is the maximum value an unsigned 32 bit integer can hold which is 4294967295 or 4GB. Note this option is only available if Snort was built to use time stats with --enable-timestats. Set global memcap in bytes for so rules that dynamically allocate memory for storing session data in the stream preprocessor. These options may appear in any order but must be comma separated. This option is only valid in the base configuration when using multiple configurations. Also used to determine how to set up the logging directory structure for the session post detection rule option and ASCII output plugin an attempt is made to name the log directories after the IP address that is not in the reference net. 37 . Sets the policy mode to either passive. That may occur after other configuration settings that result in output to console or syslog. Set the snaplength of packet.com/?id= For IP obfuscation. whereas using config quiet in snort. the obfuscated net will be used if the packet contains an IP address in the reference net. Sets assurance mode for stream (stream is established). same effect as -r <tf> option. A value of 0 disables the memcap. eg: myref. (This is deprecated. The default value when this option is not configured is 256 packets.) Set the amount of time in seconds between logging time stats. Changes GID to specified GID (snort -g).conf is parsed. Use config event filter instead. Default is 3600 (1 hour). The are intended for passive mode. and the default is off. such as eth0. Set the number of strafing attempts per injected response and/or the device.
it is possible to evade the IDS.pdf.snort. Once we have this information we can start to really change the game for these complex modeling problems. they are usually implemented by people who read the RFCs and then write their interpretation of what the RFC outlines into code. When IP stacks are written for different operating systems. Faster execution than frag2 with less complex data management. there are ambiguities in the way that the RFCs define some of the edge conditions that may occur and when this happens different people implement certain aspects of their IP stacks differently. Target-based host modeling anti-evasion techniques. The frag2 preprocessor used splay trees extensively for managing the data structures associated with defragmenting packets.2.2 Preprocessors Preprocessors were introduced in version 1.2. The format of the preprocessor directive in the Snort config file is: preprocessor <name>: <options> 2.icir. We can also present the IDS with topology information to avoid TTL-based evasions and a variety of other issues. Target-based analysis is a relatively new concept in network-based intrusion detection. Preprocessor code is run before the detection engine is called. Splay trees are excellent data structures to use when you have some assurance of locality of reference for the data that you are handling but in high speed. This is where the idea for “target-based IDS” came from. There are at least two preprocessor directives required to activate frag3. but that’s a topic for another day. The basic idea behind target-based IDS is that we tell the IDS information about hosts on the network so that it can avoid Ptacek & Newsham style evasion attacks based on information about how an individual target IP stack operates.. In an environment where the attacker can determine what style of IP defragmentation is being used on a particular target. if the attacker has more information about the targets on a network than the IDS does.1 Frag3 The frag3 preprocessor is a target-based IP defragmentation module for Snort.org/vern/papers/activemap-oak03. The packet can be modified or analyzed in an out-of-band manner using this mechanism. idea of a target-based system is to model the actual targets on the network instead of merely modeling the protocols and looking for attacks within them. Preprocessors are loaded and configured using the preprocessor keyword. Unfortunately.org/docs/idspaper/. check out the famous Ptacek & Newsham paper at. As I like to say. There can be an arbitrary number of 38 .5 of Snort. For more detail on this issue and how it affects IDS. Frag 3 Configuration Frag3 configuration is somewhat more complex than frag2. They allow the functionality of Snort to be extended by allowing users and programmers to drop modular plugins into Snort fairly easily. heavily fragmented environments the nature of the splay trees worked against the system and actually hindered performance. For an IDS this is a big problem. Frag3 was implemented to showcase and prototype a target-based module within Snort to test this idea. Check it out at. but after the packet has been decoded. Frag3 is intended as a replacement for the frag2 defragmentation module and was designed with the following goals: 1. Frag3 uses the sfxhash data structure and linked lists for data handling internally which allows it to have much more predictable and deterministic performance in any environment which should aid us in managing heavily fragmented environments. a global configuration directive and an engine instantiation. 2.
– detect anomalies . Default is 8192.Minimum acceptable TTL value for a fragment packet. – bind to <ip list> . This engine will only run for packets with destination addresses contained within the IP List. – timeout <seconds> . – prealloc frags <number> .Memory cap for self preservation.Maximum simultaneous fragments to track.Option to turn off the preprocessor. The Paxson Active Mapping paper introduced the terminology frag3 is using to describe policy types. and prealloc frags are applied when specified with the configuration. – disabled . – memcap <bytes> . – min fragment length <number> .Detect fragment anomalies. By default this option is turned off.Select a target-based defragmentation mode. Default is 60 seconds.Timeout for fragments. This config option takes values equal to or greater than zero. if detect anomalies is also configured. Default is 1. last. Default is 4MB. Global Configuration • Preprocessor name: frag3 global • Available options: NOTE: Global configuration options are comma separated. This is an optional parameter. The known mappings are as follows.Alternate memory management mode. but only one global configuration.Defines smallest fragment size (payload size) that should be considered valid.engines defined at startup with their own configuration. prealloc memcap.IP List to bind this engine to. bsdright. Fragments in the engine for longer than this period will be automatically dropped. bsd. the minimum is ”0”. – overlap limit <number> . – min ttl <value> .255. detect anomalies option must be configured for this option to take effect. The default is ”0” (unlimited). The accepted range for this option is 1 . linux. Available types are first. Default type is bsd. Fragments smaller than or equal to this limit are considered malicious and an event is raised. – max frags <number> . The default is ”0” (unlimited). Anyone who develops more mappings and would like to add to this list please feel free to send us an email! 39 . – policy <type> . Engine Configuration • Preprocessor name: frag3 engine • Available options: NOTE: Engine configuration options are space separated. Default value is all.Limits the number of overlapping fragments per packet. When the preprocessor is disabled only the options memcap. detect anomalies option must be configured for this option to take effect. Use preallocated fragment nodes (faster in some situations). This is an optional parameter.
0/24.1..5.0A.16-3 Linux 2.0 OSF1 V3.1. bind_to [10.168.47.8 Tru64 Unix V5.V5.4 Linux 2.4 (RedHat 7.7-10 Linux 2. Packets that don’t fall within the address requirements of the first two engines automatically fall through to the third one.0.4.14-5.10smp Linux 2.3 8.2.00 IRIX 4.2. The first two engines are bound to specific IP address ranges and the last one applies to all other traffic.0/24 policy first.2 OSF1 V4.9.2.2smp Linux 2.1 SunOS 4.5F IRIX 6.0.4 SunOS 5.5.5.Platform AIX 2 AIX 4.0 Linux 2.19-6.1 OS/2 (version unknown) OSF1 V3.5. detect_anomalies 40 .10.3) MacOS (version unknown) NCD Thin Clients OpenBSD (version unknown) OpenBSD (version unknown) OpenVMS 7.7.4.172.5.3 Cisco IOS FreeBSD HP JetDirect (printer) HP-UX B.1.6.0.2.0. bind_to 192.8.3 IRIX64 6.9-31SGI 1.10 Linux 2.5. first and last policies assigned.1-7.16.20 HP-UX 11.1.2 IRIX 6.0/24] policy last.
the rule ’flow’ and ’flowbits’ keywords are usable with TCP as well as UDP traffic. \ [prune_log_max <bytes>]. Anomaly Detection TCP protocol anomalies. \ [track_icmp <yes|no>]. [max_tcp <number>]. etc. direction. Target-Based Stream5. Transport Protocols TCP sessions are identified via the classic TCP ”connection”. TCP Timestamps.2. while others do not. Its event output is packet-based so it will work with all output modes of Snort.Frag 3 Alert Output Frag3 is capable of detecting eight different types of anomalies. Stream API Stream5 fully supports the Stream API. The methods for handling overlapping data. 2. other protocol normalizers/preprocessors to dynamically configure reassembly behavior as required by the application layer protocol. \ [flush_on_alert]. \ [memcap <number bytes>]. etc are configured via the detect anomalies option to the TCP configuration. Some of these anomalies are detected on a per-target basis. and update the identifying information about the session (application protocol. data received outside the TCP window. such as data on SYN packets. FIN and Reset sequence numbers. etc). and the policies supported by Stream5 are the results of extensive research with many target operating systems. [disabled] 41 . which effectively terminate a TCP or UDP session. It is capable of tracking sessions for both TCP and UDP. ICMP messages are tracked for the purposes of checking for unreachable and service unavailable messages. \ [track_udp <yes|no>]. introduces target-based actions for handling of overlapping data and other TCP anomalies. identify sessions that may be ignored (large data transfers.2 Stream5 The Stream5 preprocessor is a target-based TCP reassembly module for Snort. Read the documentation in the doc/signatures directory with filenames that begin with “123-” for information on the different event types. [max_udp <number>]. UDP sessions are established as the result of a series of UDP packets from two end points via the same set of ports. [max_icmp <number>]. Stream5 Global Configuration Global settings for the Stream5 preprocessor. Data on SYN. [show_rebuilt_packets]. a few operating systems allow data in TCP SYN packets. preprocessor stream5_global: \ [track_tcp <yes|no>]. For example. With Stream5. like Frag3. etc) that can later be used by rules.
The default is ”yes”. [use_static_footprint_sizes]. minimum is ”1”. minimum is ”32768” (32KB). and the maximum is ”86400” (approximately 1 day). preprocessor stream5_tcp: \ [bind_to <ip_addr>]. The default is ”yes”. Print/display packet after rebuilt (for debugging). Print a message when a session terminates that was consuming more than the specified number of bytes. Maximum simultaneous TCP sessions tracked. Backwards compatibility. The default is ”131072”. The default is ”no”. Maximum simultaneous ICMP sessions tracked. \ [check_session_hijacking]. [flush_factor <number segs>] Option bind to <ip addr> timeout <num seconds> \ Description IP address or network for this policy. \ [ignore_any_rules]. minimum is ”1”. [ports <client|server|both> <all|number [number]*>]. and that policy is not bound to an IP address or network. The default is ”1048576” (1MB). \ [small_segments <number> bytes <number> [ignore_ports number [number]*]]. max udp and max icmp are applied when specified with the configuration. Flush a TCP stream when an alert is generated on that stream. Memcap for TCP packet storage. \ [require_3whs [<number secs>]]. Session timeout. \ [max_queued_bytes <bytes>]. \ [overlap_limit <number>]. maximum is ”1048576”. The default is set to any. the minimum is ”1”. [detect_anomalies]. 42 . maximum is ”1048576”. [max_window <number>]. One default policy must be specified. per policy that is bound to an IP address or network. \ [protocol <client|server|both> <all|service name [service name]*>]. maximum is ”1048576”. The default is ”30”. The default is set to off. The default is ”65536”. When the preprocessor is disabled only the options memcap. Track sessions for UDP. minimum is ”1”. Option to disable the stream5 tracking. Stream5 TCP Configuration Provides a means on a per IP address target to configure TCP policy. [max_queued_segs <number segs>]. \ [dont_store_large_packets]. minimum can be either ”0” (disabled) or if not disabled the minimum is ”1024” and maximum is ”1073741824”. The default is ”8388608” (8MB). [policy <policy_id>]. Maximum simultaneous UDP sessions tracked. This can have multiple occurrences. By default this option is turned off. \ [timeout <number secs>]. maximum is ”1073741824” (1GB). [dont_reassemble_async]. max tcp. The default is ”262144”. The default is set to off. Track sessions for ICMP.
That is the highest possible TCP window per RFCs. the minimum is ”0”. The default is ”0” (unlimited). This option should not be used production environments. and the maximum is ”86400” (approximately 1 day). so using a value near the maximum is discouraged. Performance improvement to not queue large packets in reassembly buffer. The default is ”0” (don’t consider existing sessions established). A message is written to console/syslog when this limit is enforced. If an ethernet layer is not part of the protocol stack received by Snort. This allows a grace period for existing sessions to be considered established during that interval immediately after Snort is started. and a maximum of ”1073741824” (1GB). last Favor first overlapped segment. first Favor first overlapped segment. and the maximum is ”1073725440” (65535 left shift 14). OpenBSD 3. The default is set to off. Establish sessions only on completion of a SYN/SYN-ACK/ACK handshake. The default is set to off.policy <policy id> overlap limit <number> max window <number> require 3whs [<number seconds>] detect anomalies check session hijacking use static footprint sizes dont store large packets dont reassemble async max queued bytes <bytes> The Operating System policy for the target OS.3 and newer Limits the number of overlapping packets per session. Default is ”1048576” (1MB). Use static values for determining when to build a reassembled packet to allow for repeatable tests.x and newer. The default is set to off. and the maximum is ”255”. Detect and alert on TCP protocol anomalies. NetBSD 2. there are no checks performed. Using this option may result in missed attacks. Don’t queue packets for reassembly if traffic has not been seen in both directions. This check validates the hardware (MAC) address from both sides of the connect – as established on the 3-way handshake against subsequent packets received on the session. A value of ”0” means unlimited.x and newer.4 and newer old-linux Linux 2. The optional number of seconds specifies a startup timeout. Maximum TCP window allowed. Windows XP.2 and earlier windows Windows 2000. This option is intended to prevent a DoS against Stream5 by an attacker using an abnormally large window. The default is set to off. The default is set to off.x and newer hpux HPUX 11 and newer hpux10 HPUX 10 irix IRIX 6 and newer macos MacOS 10. Check for TCP session hijacking. The policy id can be one of the following: Policy Name Operating Systems. Alerts are generated (per ’detect anomalies’ option) for either the client or server when the MAC address for one side or the other does not match. Limit the number of bytes queued for reassembly on a given TCP session to bytes. the minimum is ”0”. The default is set to queue packets. with a non-zero minimum of ”1024”.x and newer linux Linux 2. bsd FresBSD 4. The default is ”0” (unlimited). 43 . the minimum is ”0”. Windows 95/98/ME win2003 Windows 2003 Server vista Windows Vista solaris Solaris 9.
The default settings are ports client ftp telnet smtp nameserver dns http pop3 sunrpc dcerpc netbios-ssn imap login shell mssql oracle cvs mysql. This can appear more than once in a given config. Specify the client. ! △NOTE If no options are specified for a given TCP policy. This feature requires that detect anomalies be enabled. This is a performance improvement and may result in missed attacks. defines the list of ports in which will be ignored for this rule. This can appear more than once in a given config. A message is written to console/syslog when this limit is enforced. only those with content. Useful in ips mode to flush upon seeing a drop in segment size after N segments of non-decreasing size. The second number is the minimum bytes for a segment to be considered ”small”. there should be only one occurrence of the UDP configuration. The first number is the number of consecutive segments that will trigger the detection rule. Configure the maximum small segments queued. The minimum port allowed is ”1” and the maximum allowed is ”65535”. This option can be used only in default policy. The default settings are ports client 21 23 25 42 53 80 110 111 135 136 137 139 143 445 513 514 1433 1521 2401 3306. The drop in size often indicates an end of request or response. The default is ”2621”. including any of the internal defaults (see 2. If only a bind to option is used with no other options that TCP policy uses all of the default values.7). The default value is ”0” (disabled). and a maximum of ”1073741824” (1GB). Stream5 UDP Configuration Configuration for UDP session tracking. [ignore_any_rules] 44 . The number of ports can be up to ”65535”. Using this does not affect rules that look at protocol headers. server.7. preprocessor stream5_udp: [timeout <number secs>]. PCRE. Rules that have flow or flowbits will never be ignored. A value of ”0” means unlimited. with a maximum of ”2048”. with a non-zero minimum of ”2”. derived based on an average size of 400 bytes. that is the default TCP policy. server. Since there is no target based binding. or both and list of services in which to perform reassembly. ignore ports is optional. or byte test options. with a maximum of ”2048”. Specify the client. Don’t process any -> any (ports) rules for TCP that attempt to match payload if there are no port specific rules for the src or destination port. A message is written to console/syslog when this limit is enforced.3) or others specific to the network. The default is ”off”. The default value is ”0” (disabled). The service names can be any of those used in the host attribute table (see 2. or both and list of ports in which to perform reassembly.
This configuration maps two network segments to different OS policies. Using this does not affect rules that look at protocol headers. only those with content. track_tcp yes.Option timeout <num seconds> ignore any rules Description Session timeout. It is not ICMP is currently turned on by default.conf and can be used for repeatable tests of stream reassembly in readback mode. track_icmp no preprocessor stream5_tcp: \ policy first. Since there is no target based binding. track_udp yes. and the maximum is ”86400” (approximately 1 day). For example. or byte test options. with all other traffic going to the default policy of Solaris. the minimum is ”1”. if a UDP rule that uses any -> any ports includes either flow or flowbits. The default is ”off”. the minimum is ”1”. ! △NOTE any rules option. one for Windows and one for Linux. Rules that have flow or flowbits will never be ignored. PCRE. use_static_footprint_sizes preprocessor stream5_udp: \ ignore_any_rules 2. Example Configurations 1. preprocessor stream5_icmp: [timeout <number secs>] Option timeout <num seconds> Description Session timeout. the ’ignored’ any -> any rule will be applied to traffic to/from port 53. This example configuration is the default configuration in snort. a UDP rule will be ignored except when there is another port specific rule With the ignore that may be applied to the traffic. and the maximum is ”86400” (approximately 1 day). preprocessor stream5_global: \ max_tcp 8192. This is a performance improvement and may result in missed attacks. Because of the potential impact of disabling a flowbits rule. there should be only one occurrence of the ICMP configuration. The default is ”30”. The default is ”30”. Stream5 ICMP Configuration Configuration for ICMP session tracking. in minimal code form and is NOT ready for use in production networks. With the ignore the ignore any rules option is effectively pointless. A list of rule SIDs affected by this option are printed at Snort’s startup. but NOT to any other source or destination port. ! △NOTE untested. Don’t process any -> any (ports) rules for UDP that attempt to match payload if there are no port specific rules for the src or destination port. 45 . ! △NOTE any rules option. if a UDP rule specifies destination port 53. the ignore any rules option will be disabled in this case.
One of the most common portscanning tools in use today is Nmap. Our primary objective in detecting portscans is to detect and track these negative responses.1.. This phase assumes the attacking host has no prior knowledge of what protocols or services are supported by the target. In the Reconnaissance phase.3 sfPortscan The sfPortscan module. only the attacker has a spoofed source address inter-mixed with the real scanning address. since most hosts have relatively few services available. negative responses from hosts are rare. an attacker determines what types of network protocols or services a host supports. if not all. In the nature of legitimate network communications.1. so we track this type of scan through the scanned host. of the current portscanning techniques. policy windows stream5_tcp: bind_to 10. This is the traditional place where a portscan takes place.0/24. ! △NOTE Negative queries will be distributed among scanning hosts. is designed to detect the first phase in a network attack: Reconnaissance. developed by Sourcefire. Distributed portscans occur when multiple hosts query one host for open services.2. This tactic helps hide the true identity of the attacker.1. sfPortscan alerts for the following types of portsweeps: 46 . otherwise. sfPortscan was designed to be able to detect the different types of scans Nmap can produce. This is used to evade an IDS and obfuscate command and control hosts. most queries sent by the attacker will be negative (meaning that the service ports are closed). this phase would not be necessary..preprocessor preprocessor preprocessor preprocessor stream5_global: track_tcp yes stream5_tcp: bind_to 192..168. policy linux stream5_tcp: policy solaris 2. Most of the port queries will be negative. As the attacker has no beforehand knowledge of its intended target.0/24.
such as NATs. sfPortscan will only track open ports after the alert has been triggered. 47 . On TCP sweep alerts however. Open port events are not individual alerts. On TCP scan alerts. For example. sfPortscan only generates one alert for each host pair in question during the time window (more on windows below). ! △NOTE The characteristics of a portsweep scan may not result in many negative responses. Active hosts. sfPortscan will also display any open ports that were scanned. if an attacker portsweeps a web farm for port 80.. A filtered alert may go off before responses from the remote hosts are received. we will most likely not see many negative responses.• TCP Portsweep • UDP Portsweep • IP Portsweep • ICMP Portsweep These alerts are for one→many portsweeps. One host scans a single port on multiple hosts. can trigger these alerts because they can send out many connection attempts within a very small amount of time. but tags based on the original scan alert. It’s also a good indicator of whether the alert is just a very active legitimate host.
The list is a comma separated list of IP addresses. You should enable the Stream preprocessor in your snort. proxies. ignore scanners <ip1|ip2/cidr[ [port|port2-port3]]> Ignores the source of scan alerts. watch ip <ip1|ip2/cidr[ [port|port2-port3]]> Defines which IPs.. after which this window is reset. IPs or networks not falling into this range are ignored if this option is used. However.“Medium” alerts track connection counts. IP address using CIDR notation. 7.sfPortscan Configuration Use of the Stream5 preprocessor is required for sfPortscan. so the user may need to deploy the use of Ignore directives to properly tune this directive.2. networks. The parameter is the same format as that of watch ip. and so will generate filtered scan alerts. 5. but is very sensitive to active hosts. 48 .conf. and specific ports on those hosts to watch. • high . 6. Optionally. this setting will never trigger a Filtered Scan alert because of a lack of error responses. etc).“High” alerts continuously track hosts on a network using a time window to evaluate portscan statistics for that host. scan type <scan type> Available options: • portscan • portsweep • decoy portscan • distributed portscan • all 3. The parameter is the same format as that of watch ip. this setting should see very few false positives. logfile <file> This option will output portscan events to the file specified. If file does not contain a leading slash. Stream gives portscan direction in the case of connectionless protocols like ICMP and UDP.2. A ”High” setting will catch some slow scans because of the continuous monitoring. This most definitely will require the user to tune sfPortscan. This setting is based on a static time window of 60 seconds. as described in Section 2. DNS caches. sense level <level> Available options: • low . ignore scanned <ip1|ip2/cidr[ [port|port2-port3]]> Ignores the destination of scan alerts. this file will be placed in the Snort config dir. and because of the nature of error responses. 4. This setting may false positive on active hosts (NATs.“Low” alerts are only generated on error packets sent from the target host. • medium . proto <protocol> Available options: • TCP • UDP • IGMP • ip proto • all 2.
8. especially under heavy load with dropped packets. The sfPortscan alert output was designed to work with unified packet logging. IP range.. snort generates a pseudo-packet and uses the payload portion to store the additional portscan information of priority count. 49 . detect ack scans This option will include sessions picked up in midstream by the stream module. connection count. This can lead to false alerts. which is necessary to detect ACK scans. Open port alerts differ from the other portscan alerts. etc. The open port information is stored in the IP payload and contains the port that is open. 9. Any valid configuration may have ”disabled” added to it. disabled This optional keyword is allowed with any policy to avoid packet processing. include midstream This option will include sessions picked up in midstream by Stream5. and port range. especially under heavy load with dropped packets. When the preprocessor is disabled only the memcap option is applied when specified with the configuration. so it is possible to extend favorite Snort GUIs to display portscan alerts and the additional information in the IP payload using the above packet characteristics. This means that if an output system that doesn’t print tagged packets is used. 10. This option disables the preprocessor. port count. then the user won’t see open port alerts. The size tends to be around 100 . the packet looks like the IP portion of the packet that caused the portscan alert to be generated. which is why the option is off by default.200 bytes. this can lead to false alerts. which is why the option is off by default. The payload and payload size of the packet are equal to the length of the additional portscan information that is logged. IP count. This includes any IP options. The characteristics of the packet are: Src/Dst MAC Addr == MACDAD IP Protocol == 255 IP TTL == 0 Other than that. The other options are parsed but not used. because open port alerts utilize the tagged packet output system. However.
High connection count and low priority count would indicate filtered (no response received from target). Port Count Port Count keeps track of the last port contacted and increments this number when that changes.168. We use this count (along with IP Count) to determine the difference between one-to-one portscans and one-to-one decoys.3 -> 192. and ignore scanned options. and increments the count if the next IP is different.4 Port/Proto Count: 200 Port/Proto Range: 20:47557 If there are open ports on the target. The watch ip option is easy to understand.3:192.168.169. and one-to-one scans may appear as a distributed scan. Use the watch ip. For one-to-one scans.3 -> 192. one or more additional tagged packet(s) will be appended: Time: 09/08-15:07:31. IP Count IP Count keeps track of the last IP to contact a host. If no watch ip is defined. Portsweep (one-to-many) scans display the scanned IP range. This is accurate for connection-based protocols. 5. 3.5 (portscan) Open Port Open Port: 38458 1.169. 4.168. the more bad responses have been received. sfPortscan will watch all network traffic.603880 event_id: 2 192. Scanned/Scanner IP Range This field changes depending on the type of alert. Event id/Event ref These fields are used to link an alert with the corresponding Open Port tagged packet 2. Portscans (one-to-one) display the scanner IP. It’s important to correctly set these options.168.169. Connection Count Connection Count lists how many connections are active on the hosts (src or dst).Log File Output Log file output is displayed in the following format.5 (portscan) TCP Filtered Portscan Priority Count: 0 Connection Count: 200 IP Count: 2 Scanner IP Range: 192. For active hosts this number will be high regardless.169. ignore scanners.168.169.168. The analyst should set this option to the list of CIDR blocks and IPs that they want to watch. 6. unreachables).603881 event_ref: 2 192. The higher the priority count. 50 . this is a low number.169. and is more of an estimate for others. Here are some tuning tips: 1. Tuning sfPortscan The most important aspect in detecting portscans is tuning the detection engine for your network(s). Priority Count Priority Count keeps track of bad responses (resets. Whether or not a portscan was filtered is determined here. and explained further below: Time: 09/08-15:07:31.
lower the sensitivity level. The easiest way to determine false positives is through simple ratio estimations. indicating that the scanning host connected to few ports but on many hosts. If the host is generating portsweep events. 2. The following is a list of ratios to estimate and the associated values that indicate a legitimate scan and not a false positive. So be much more suspicious of filtered portscans. Some of the most common examples are NAT IPs. The portscan alert details are vital in determining the scope of a portscan and also the confidence of the portscan. the analyst will know which to ignore it as. 2. Format preprocessor rpc_decode: \ <ports> [ alert_fragments ] \ [no_alert_multiple_requests] \ [no_alert_large_fragments] \ [no_alert_incomplete] 51 . These responses indicate a portscan and the alerts generated by the low sensitivity level are highly accurate and require the least tuning. Most of the false positives that sfPortscan may generate are of the filtered scan alert type. If all else fails. this ratio should be low. syslog servers. IP Range. It does this by normalizing the packet into the packet buffer. this ratio should be high. Connection Count / IP Count: This ratio indicates an estimated average of connections per IP. The low sensitivity level only generates alerts based on error responses. lower the sensitivity level.The ignore scanners and ignore scanned options come into play in weeding out legitimate hosts that are very active on your network. If none of these other tuning techniques work or the analyst doesn’t have the time for tuning. For portsweeps. For portscans. Port Count. but it’s also important that the portscan detection engine generate alerts that the analyst will find informative. we hope to automate much of this analysis in assigning a scope level and confidence level. IP Count. 4. If stream5 is enabled. the higher the better. Connection Count / Port Count: This ratio indicates an estimated average of connections per port. this ratio should be low. If the host continually generates these types of alerts. Many times this just indicates that a host was very active during the time period in question. By default. since these are more prone to false positives.2. it will only process client-side traffic. this ratio should be high. For portscans.). Filtered scan alerts are much more prone to false positives. it runs against traffic on ports 111 and 32771. This indicates that each connection was to a different port. add it to the ignore scanned option. the alert type is very important. but for now the user must manually do this. For portscans. is because the priority count is included in the connection count and the above comparisons take that into consideration. For portsweeps. and nfs servers. DNS cache servers. but be aware when first tuning sfPortscan for these IPs. and Port Range to determine false positives. If the host is generating portscan alerts (and is the host that is being scanned).4 RPC Decode The rpc decode preprocessor normalizes RPC multiple fragmented records into a single un-fragmented record. Connection Count. Depending on the type of alert that the host generates. this ratio should be low. 3. this ratio should be high and indicates that the scanned host’s ports were connected to by fewer IPs. sfPortscan may not generate false positives for these types of hosts. You get the best protection the higher the sensitivity level. For portsweeps. When determining false positives. Make use of the Priority Count. then add it to the ignore scanners option. In the future. This indicates that there were many connections to the same port. The reason that Priority Count is not included. The low sensitivity level does not catch filtered scans. add it to the ignore scanners list or use a lower sensitivity level. .2. Snort’s real-time statistics are processed.5 Performance Monitor This preprocessor measures Snort’s real-time and theoretical maximum performance. it should have an output mode enabled. Don’t alert when a single fragment record exceeds the size of one packet. Whenever this preprocessor is turned on. By default. either “console” which prints statistics to the console window or “file” with a file name.Option alert fragments no alert multiple requests no alert large fragments no alert incomplete Description Alert on any fragmented RPC record. where statistics get printed to the specified file name. Don’t alert when the sum of fragmented records exceeds one packet. 2. .• Number of CPUs [*** Only if compiled with LINUX SMP ***.
By default.Turns on the theoretical maximum performance that Snort calculates given the processor speed and current performance. This boosts performance. • accumulate or reset . • time . Snort will log a distinctive line to this file with a timestamp to all readers to easily identify gaps in the stats caused by Snort not running. A high non-qualified event to qualified event ratio can indicate there are many rules with either minimal content or no content that are being evaluated without success.Prints out statistics about the type of traffic and protocol distributions that Snort is seeing. At startup. Rules without content are not filtered via the fast pattern matcher and are always evaluated. so if possible.Defines which type of drop statistics are kept by the operating system. reset is used.Represents the number of seconds between intervals. The fast pattern matcher is used to select a set of rules for evaluation based on the longest content or a content modified with the fast pattern rule option in a rule .Adjusts the number of packets to process before checking for the time sample. • console . By default. Not all statistics are output to this file. Both of these directives can be overridden on the command line with the -Z or --perfmon-file options.Prints statistics in a comma-delimited format to the file that is specified. • max . since many operating systems don’t keep accurate kernel statistics for multiple CPUs. 54 . This option can produce large amounts of output. the number of rules that were evaluated and matched (qualified events). generic contents are more likely to be selected for evaluation than those with longer. • file . • atexitonly . Rules with short. • pktcnt . This is only valid for uniprocessor machines. this is 10000.Prints statistics at the console. adding a content rule option to those rules can decrease the number of times they need to be evaluated and improve performance. more unique contents.Turns on event reporting.Dump stats for entire life of Snort. • events . This prints out statistics as to the number of rules that were evaluated and didn’t match (non-qualified events) vs. since checking the time sample reduces Snort’s performance. You may also use snortfile which will output into your defined Snort log directory.
Future versions will have a stateful processing mode which will hook into various reassembly modules. and normalize the fields.Sets the memory cap on the hash table used to store IP traffic statistics for host pairs. Before the file exceeds this size. it will be rolled into a new date stamped file of the format YYYY-MM-DD. Examples preprocessor perfmonitor: \ time 30 events flow file stats. followed by YYYY-MM-DD. The minimum is 4096 bytes and the maximum is 2147483648 bytes (2GB). • flow-ip-file . Within HTTP Inspect.. Given a data buffer.6 HTTP Inspect HTTP Inspect is a generic HTTP decoder for user applications. For each pair of hosts for which IP traffic has been seen. This means that HTTP Inspect looks for HTTP fields on a packet-by-packet basis. The default is the same as the maximum. HTTP Inspect works on both client requests and server responses. find HTTP fields. HTTP Inspect will decode the buffer. Global Configuration The global configuration deals with configuration options that determine the global functioning of HTTP Inspect. as well as the IP addresses of the host pairs in human-readable format. there are two areas of configuration: global and server. are included. • flow-ip-memcap . and will be fooled if packets are not reassembled. the table will start to prune the statistics for the least recently seen host pairs to free memory.Prints the flow IP statistics in a comma-delimited format to the file that is specified.Defines the maximum size of the comma-delimited file.• max file size .csv pktcnt 1000 2. All of the statistics mentioned above. Users can configure individual HTTP servers with a variety of options. • flow-ip . which should allow the user to emulate any type of web server.Collects IP traffic distribution statistics based on host pairs. HTTP Inspect has a very “rich” user configuration. Once the cap has been reached.2. where x will be incremented each time the comma delimited file is rolled over.x. This works fine when there is another module handling the reassembly. but there are limitations in analyzing the protocol. The current version of HTTP Inspect only handles stateless processing. The following example gives the generic global configuration format: 55 .profile max console pktcnt 10000 preprocessor perfmonitor: \ time 300 file /var/tmp/snortstat pktcnt 10000 preprocessor perfmonitor: \ time 30 flow-ip flow-ip-file flow-ip-stats. This value is in bytes and the default value is 52428800 (50MB).
Configuration 1. 2. 3.map and should be used if no other codepoint map is available. Blind firewall proxies don’t count. For US servers. So. but for right now. the value specified in the default policy is used and this value overwrites the values specified in the other policies. 56 . individual servers can reference their own IIS Unicode map. This value can be set from 1 to 65535. you will only receive proxy use alerts for web users that aren’t using the configured proxies or are using a rogue proxy server. the codemap is usually 1252. This value should be specified in the default policy even when the HTTP inspect is turned off using the disabled keyword. 4. then you may get a lot of proxy alerts.Format preprocessor http_inspect: \ global \ iis_unicode_map <map_filename> \ codemap <integer> \ [detect_anomalous_servers] \ [proxy_alert] \ [max_gzip_mem <num>] \ [compress_depth <num>] [decompress_depth <num>] \ disabled You can only have a single global configuration. ! △NOTE Please note. this inspects all network traffic. in case of multiple policies. we want to limit this to specific networks so it’s more useful. This option is turned off by default.org/dl/contrib/. detect anomalous servers This global configuration option enables generic HTTP server traffic inspection on non-HTTP configured ports. you’ll get an error if you try otherwise. In the future. Don’t turn this on if you don’t have a default server configuration that encompasses all of the HTTP server ports that your users might access. A Microsoft US Unicode codepoint map is provided in the Snort source etc directory by default. It is called unicode. The iis unicode map file is a Unicode codepoint map which tells HTTP Inspect which codepage to use when decoding Unicode characters. The iis unicode map is a required configuration parameter. In case of unlimited decompress this should be set to its max value. and alerts if HTTP traffic is seen. please only use this feature with traditional proxy environments. compress depth <integer> This option specifies the maximum amount of packet payload to decompress. ! △NOTE Remember that this configuration is for the global IIS Unicode map. proxy alert This enables global alerting on HTTP server proxy usage. The default for this option is 1460. By configuring HTTP Inspect servers and enabling allow proxy use.c. Please note that if users aren’t required to configure web proxy use.snort. The map file can reside in the same directory as snort. iis unicode map <map filename> [codemap <integer>] This is the global iis unicode map file. which is available at or be specified via a fully-qualified path to the map file. A tool is supplied with Snort to generate custom Unicode maps--ms unicode generator.
57 . ! △NOTE This value should be specified in the default policy even when the HTTP inspect is turned off using the disabled keyword. max gzip session = max gzip mem /(decompress depth + compress depth) 7. disabled This optional keyword is allowed with any policy to avoid packet processing. This option disables the preprocessor. In case of unlimited decompress this should be set to its max value. It is suggested to set this value such that the max gzip session calculated as follows is at least 1. ! △NOTE Please note. the value specified in the default policy is used and this value overwrites the values specified in the other policies. Example Default Configuration preprocessor http_inspect_server: \ server default profile all ports { 80 } Configuration by IP Address This format is very similar to “default”. Most of your web servers will most likely end up using the default configuration. This value should be specified in the default policy even when the HTTP inspect is turned off using the disabled keyword. The default for this option is 2920. Other options are parsed but not used. max gzip mem This option determines (in bytes) the maximum amount of memory the HTTP Inspect preprocessor will use for decompression.5. decompress depth <integer> This option specifies the maximum amount of decompressed data to obtain from the compressed packet payload. in case of multiple policies. The default value for this option is 838860. the only difference being that specific IPs can be configured. Default This configuration supplies the default server configuration for any server that is not individually configured.map 1252 Server Configuration There are two types of server configurations: default and by IP address. Any valid configuration may have ”disabled” added to it. This option along with compress depth and decompress depth determines the gzip sessions that will be decompressed at any given instant. 6. When the preprocessor is disabled only the ”max gzip mem”. Example Global Configuration preprocessor http_inspect: \ global iis_unicode_map unicode. This value can be set from 1 to 65535. This value can be set from 3276 bytes to 100MB. ”compress depth” and ”decompress depth” options are applied when specified with the configuration.
0.6. there was a double decoding vulnerability. except they will alert by default if a URL has a double encoding. HTTP normalization will still occur. profile <all|apache|iis|iis5 0|iis4 0> Users can configure HTTP Inspect by using pre-defined HTTP server profiles. and iis4 0.1 profile all ports { 80 } Configuration by Multiple IP Addresses This format is very similar to “Configuration by IP Address”. backslashes. This differs from the iis profile by only accepting UTF-8 standard Unicode encoding and not accepting backslashes as legitimate slashes.. whether set to ‘yes’ or ’no’. 1-A.5.4. only the alerting functionality. 1-C. The ‘yes/no’ argument does not specify whether the configuration option itself is on or off. 1-D. apache The apache profile is used for Apache web servers. etc. like IIS does. iis4 0. double decoding. So that means we use IIS Unicode codemaps for each server. %u encoding. default. bare-byte encoding. Example Multiple IP Configuration preprocessor http_inspect_server: \ server { 10.1 and beyond. 1. This is a great profile for detecting all types of attacks. Profiles allow the user to easily configure the preprocessor for a certain type of server. . iis.1.1 10. iis5 0 In IIS 4. 1-B. There is a limit of 40 IP addresses or CIDR notations per http inspect server line. There are five profiles available: all.1. Apache also accepts tabs as whitespace. and rules based on HTTP traffic will still trigger. apache.Example IP Configuration preprocessor http_inspect_server: \ server 10. profile all sets the configuration options described in Table 2.1. so it’s disabled by default. no profile The default options used by HTTP Inspect do not use a profile and are described in Table 2. We alert on the more serious forms of evasions. iis The iis profile mimics IIS servers.0 and IIS 5.3. profile apache sets the configuration options described in Table 2. In other words.2.1. all The all profile is meant to normalize the URI using most of the common tricks available. profile iis sets the configuration options described in Table 2. the only difference being that multiple IPs can be specified via a space separated list. These two profiles are identical to iis. This argument specifies whether the user wants the configuration option to generate an HTTP Inspect alert or not. but are not required for proper operation.2. regardless of the HTTP server. iis5 0. Double decode is not supported in IIS 5.0/24 } profile all ports { 80 } Server Configuration Options Important: Some configuration options have an argument of ‘yes’ or ‘no’.
alert on %u decoding on. 3. alert on iis unicode codepoints on. alert on bare byte decoding on. ports {<port> [<port>< . use the SSL preprocessor. >]} This is how the user configures which ports to decode on the HTTP server. iis unicode map <map filename> codemap <integer> The IIS Unicode map is generated by the program ms unicode generator.snort. alert off double decoding on. This program is located on the Snort.1 profile all ports { 80 3128 } 2.Table 2. number of headers not checked • • • • • • • • • • • • • • • non strict URL parsing on tab uri delimiter is set max header length 0. However. alert off directory normalization on. Executing this program generates a 59 .org web site at. alert on iis backslash on.org/dl/contrib/ directory. alert off iis delimiter on.. HTTPS traffic is encrypted and cannot be decoded with HTTP Inspect. Example preprocessor http_inspect_server: \ server 1.1.c.. To ignore HTTPS traffic. alert off apache whitespace on.1. alert off webroot on. alert off multiple slash on. header length not checked max headers 0.
But the ms unicode generator program tells you which codemap to use for you server. For US servers. cookie (when enable cookie is configured) and body are extracted and saved into buffers. the decompressed data from different packets are not combined while inspecting). headers. But the decompressed data are individually inspected. The Cookie header line is extracted and stored in HTTP Cookie buffer for HTTP requests and Set-Cookie is extracted and stored in HTTP Cookie buffer for HTTP responses. When the compressed data is spanned across multiple packets. alert off webroot on. number of headers not checked Unicode map for the system that it was run on. By default the cookie inspection and extraction will be turned off. alert off multiple slash on. Different rule options are provided to inspect these buffers. You can select the correct code page by looking at the available code pages that the ms unicode generator outputs. extended response inspection This enables the extended HTTP response inspection. 5. http stat code.e. the user needs to specify the file that contains the IIS Unicode map and also specify the Unicode map to use. 60 . it’s the ANSI code page. ! △NOTE When this option is turned on. So. status message. http stat msg and http cookie. You should select the config option ”extended response inspection” before configuring this option.Table 2. (i. alert on apache whitespace on. Snort should be configured with the –enable-zlib flag. to get the specific Unicode mappings for an IIS web server. header length not checked max headers 0. The default http response inspection does not inspect the various fields of a HTTP response. ! △NOTE To enable compression of HTTP server response. you run this program on that server and use that Unicode map in this configuration. alert off non strict url parsing on tab uri delimiter is set max header length 0. In both cases the header name is also stored along with the cookie. By turning this option the HTTP response will be thoroughly inspected. 4. To search for patterns in the header of the response. 6. The different fields of a HTTP response such as status code. Decompression is done across packets. the state of the last decompressed packet is used to decompressed the data of the next packet. alert on utf 8 encoding on. So the decompression will end when either the ’compress depth’ or ’decompress depth’ is reached or when the compressed data ends. one should use the http modifiers with content such as http header. this is usually 1252.4: Options for the apache Profile Option Setting server flow depth 300 client flow depth 300 post depth 0 chunk encoding alert on chunks larger than 500000 bytes ASCII decoding on. inspect gzip This option specifies the HTTP inspect module to uncompress the compressed data(gzip/deflate) in HTTP response. When using this option. alert off directory normalization. Also the amount of decompressed data that will be inspected depends on the ’server flow depth’ configured.
number of headers not checked 7. Unlike client flow depth this option is applied per TCP session. To ensure unlimited decompression. The XFF/True-Client-IP Original client IP address is logged only with unified2 output and is not logged with console (-A cmg) output. Most of these rules target either the HTTP header. or the content that is likely to be in the first hundred or so bytes of non-header data. alert on non strict URL parsing on max header length 0. alert on %u decoding on. value of -1 causes Snort to ignore the HTTP response body data and not the HTTP headers. alert on apache whitespace on. alert off directory normalization on. ! △NOTE The original client IP from XFF/True-Client-IP in unified2 logs can be viewed using the tool u2spewfoo. It is suggested to set the server flow depth to its maximum value. alert on iis backslash on.Decompression will stop when the compressed data ends or when a out of sequence packet is received. it is applied to the HTTP response body (decompressed data when inspect gzip is turned on) and not the HTTP headers. server flow depth <integer> This specifies the amount of server response payload to inspect. This value can be set from -1 to 65535. Values above 0 tell Snort the number of bytes to inspect of the server response 61 . a value of 0 causes Snort to inspect all HTTP server payloads defined in ”ports” (note that this will likely slow down IDS performance). 9. unlimited decompress This option enables the user to decompress unlimited gzip data (across multiple packets).Table 2. alert off multiple slash on. This tool is present in the tools/u2spewfoo directory of snort source tree. alert on iis unicode codepoints on. header length not checked max headers 0. When extended response inspection is turned off the server flow depth is applied to the entire HTTP response (including headers). When the extended response inspection is turned on. alert off webroot. This option can be used to balance the needs of IDS performance and level of inspection of HTTP server response data. Headers are usually under 300 bytes long. The decompression in a single packet is still limited by the ’compress depth’ and ’decompress depth’. alert on bare byte decoding on. Inversely. Snort rules are targeted at HTTP server response traffic and when used with a small flow depth value may cause false negatives. alert off iis delimiter on. enable xff This option enables Snort to parse and log the original client IP present in the X-Forwarded-For or True-ClientIP HTTP request headers along with the generated events. user should set the ’compress depth’ and ’decompress depth’ to its maximum values in the default policy. 8. but your mileage may vary. alert on double decoding on. A value of -1 causes Snort to ignore all server side traffic for ports defined in ports when extended response inspection is turned off. When extended response inspection is turned on.
header length not checked max headers 0. It has a default value of 300. Inversely. The value can be set from -1 to 65495. If more than flow depth bytes are in the payload of the first packet only flow depth bytes of the payload will be inspected. alert off multiple slash on. alert off iis delimiter on. Values above 0 tell Snort the number of bytes to inspect in the first packet of the client request.Table 2. Note that the 65535 byte maximum flow depth applies to stream reassembled packets as well. client flow depth <integer> This specifies the amount of raw client request payload to inspect. ! △NOTE server flow depth is the same as the old flow depth option. It primarily eliminates Snort from inspecting larger HTTP Cookies that appear at the end of many client request Headers. number of headers not checked (excluding the HTTP headers when extended response inspection is turned on) in a given HTTP session. which will be deprecated in a future release. Unlike server flow depth this value is applied to the first packet of the HTTP request. a value of 0 causes Snort to inspect all the client post message. It is suggested to set the client flow depth to its maximum value. If less than flow depth bytes are in the payload of the HTTP response packets in a given session. alert off apache whitespace on. This increases the performance by inspecting only specified bytes in the post message.. a value of 0 causes Snort to inspect all HTTP client side traffic defined in ”ports” (note that this will likely slow down IDS performance). 11. the entire payload will be inspected. If less than flow depth bytes are in the TCP payload (HTTP request) of the first packet. the entire payload will be inspected.” Inversely. 62 . alert off webroot on. alert off directory normalization on.6: Default HTTP Inspect Options Option Setting port 80 server flow depth 300 client flow depth 300 post depth -1 chunk encoding alert on chunks larger than 500000 bytes ASCII decoding on. alert on iis backslash on. The default value is -1. This value can be set from -1 to 1460. alert off utf 8 encoding on. Rules that are meant to inspect data in the payload of the HTTP response packets in a session beyond 65535 bytes will be ineffective unless flow depth is set to 0.. It is not a session based flow depth. post depth <integer> This specifies the amount of data to inspect in a client post message. Note that the 1460 byte maximum flow depth applies to stream reassembled packets as well. Only packets payloads starting with ’HTTP’ will be considered as the first packet of a server response. 10. A value of -1 causes Snort to ignore all the data in the post message. A value of -1 causes Snort to ignore all client side traffic for ports defined in ”ports. The default value for server flow depth is 300.
In the first pass. 16.patch. so for any Apache servers. 17. This option is turned off by default and is not supported with any of the profiles. ascii <yes|no> The ascii decode option tells us whether to decode encoded ASCII chars. utf 8 <yes|no> The utf-8 decode option tells HTTP Inspect to decode standard UTF-8 Unicode sequences that are in the URI.12. 13. so ASCII is also enabled to enforce correct decoding. ASCII. ASCII and UTF-8 decoding are also enabled to enforce correct decoding. 14. If %u encoding is enabled. The xxxx is a hex-encoded value that correlates to an IIS Unicode codepoint. You have to use the base36 option with the utf 8 option. So it is most likely someone trying to be covert. When base36 is enabled. bare byte. bare byte. like %uxxxx. This option is based on info from:. doing decodes in each one. %2e = . You should alert on %u encodings. This value can most definitely be ASCII. Don’t use the %u option. It is normal to see ASCII encoding usage in URLs. In the second pass. the following encodings are done: ASCII. double decode <yes|no> The double decode option is once again IIS-specific and emulates IIS functionality. Apache uses this standard. bare byte <yes|no> Bare byte encoding is an IIS trick that uses non-ASCII characters as valid values when decoding UTF-8 values.yk. %u002e = . If there is no iis unicode map option specified with the server config. this is really complex and adds tons of different encodings for one character. because there are no legitimate clients that encode UTF-8 this way since it is non-standard. The iis unicode option handles the mapping of non-ASCII codepoints that the IIS server accepts and decodes normal UTF-8 requests. base36 <yes|no> This is an option to decode base36 encoded chars. u encode <yes|no> This option emulates the IIS %u encoding scheme.a %2f = /. When iis unicode is enabled.or. extended ascii uri This option enables the support for extended ASCII codes in the HTTP request URI. Anyway. iis unicode uses the default codemap. To alert on UTF-8 decoding.k. but this will be prone to false positives as legitimate web clients use this type of encoding.. ASCII encoding is also enabled to enforce correct behavior. We leave out utf-8 because I think how this works is that the % encoded utf-8 is decoded to the Unicode byte in the first pass. You should alert on the iis unicode option. you must enable also enable utf 8 yes. you may be interested in knowing when you have a UTF-8 encoded URI. 19. because base36 won’t work. because it is seen mainly in attacks and evasion attempts. and %u. 15. and %u. This is not in the HTTP standard. and then UTF-8 is decoded in the second stage. An ASCII character is encoded like %u002f = /. How this works is that IIS does two passes through the request URI.jp/˜shikap/patch/spp_http_decode.rim. make sure you have this option turned on. When utf 8 is enabled. When double decode is enabled. it seems that all types of iis encoding is done: utf-8 unicode. ASCII decoding is also enabled to enforce correct functioning.. If no iis unicode map is specified before or after this option. this option will not work. the default codemap is used. etc. How the %u encoding scheme works is as follows: the encoding scheme is started by a %u followed by 4 characters. a. because we are not aware of any legitimate clients that use this encoding. 63 . as all non-ASCII values have to be encoded with a %. Bare byte encoding allows the user to emulate an IIS server and interpret non-standard encodings correctly. As for alerting. so it is recommended that you disable HTTP Inspect alerting for this option. This abides by the Unicode standard and only uses % encoding. 18. The alert on this decoding should be enabled. etc. iis unicode <yes|no> The iis unicode option turns on the Unicode codepoint mapping.
directory <yes|no> This option normalizes directory traversals and self-referential directories. 26. because you could configure it to say. alert on all ‘/’ or something like that. 25. otherwise.” If you want an alert when multiple slashes are seen.>]} This option lets users receive an alert if certain non-RFC chars are used in a request URI.. specify yes.20. enable this option. It’s flexible. 27. It is only inspected with the generic pattern matching. iis backslash <yes|no> Normalizes backslashes to slashes. specify no. This is again an IIS emulation. chunk length <non-zero positive integer> This option is an anomaly detector for abnormally large chunk sizes. then configure with a yes. a user may not want to see null bytes in the request URI and we can alert on that. but when this option is enabled.. iis delimiter <yes|no> This started out being IIS-specific. 22. and is a performance enhancement if needed. no pipeline req This option turns HTTP pipeline decoding off.. use no. Please use this option with care. pipeline requests are inspected for attacks. But you can still get an alert on this option. This alert may give false positives. 64 .” 23. otherwise./bar gets normalized to: /foo/bar The directory: /foo/. non rfc char {<byte> [<byte ./bar gets normalized to: /foo/bar If you want to configure an alert. The directory: /foo/fake\_dir/. Since this is common. So a request URI of “/foo\bar” gets normalized to “/foo/bar. For instance. and may also alert on HTTP tunneling that uses chunk encoding. so if the emulated web server is Apache. so be careful. but may also be false positive prone. This picks up the Apache chunk encoding exploits. 21. so something like: “foo/////////bar” get normalized to “foo/bar. since some web sites refer to files using directory traversals. multi slash <yes|no> This option normalizes multiple slashes in a row. apache whitespace <yes|no> This option deals with the non-RFC standard of using tab for a space delimiter. Apache uses this. 24. Alerts on this option may be interesting. By default. we always take this as standard since the most popular web servers accept it. pipeline requests are not decoded and analyzed per HTTP protocol field. but Apache takes this non-standard delimiter was well.
max header length <positive integer up to 65535> This option takes an integer as an argument. As this field usually contains 90-95% of the web attacks. 32. then there is nothing to inspect. no alerts This option turns off all alerts that are generated by the HTTP Inspect preprocessor module. This has no effect on HTTP rules in the rule set. To enable. The argument specifies the max char directory length for URL directory.28. which is associated with certain web attacks. inspect uri only This is a performance optimization. the user is allowing proxy use on this server. If a url directory is larger than this argument size. specify an integer argument to max header length of 1 to 65535. So if you need extra performance. This should limit the alerts to IDS evasion type attacks. 65 . If the proxy alert keyword is not enabled. a tab in the URI should be treated as any other character.htm http/1. then this option does nothing. No argument is specified. Specifying a value of 0 is treated as disabling the alert. content: "foo". you’ll catch most of the attacks. When enabled. a tab is treated as whitespace if a space character (0x20) precedes it.0\r\n\r\n No alert will be generated when inspect uri only is enabled. then no inspection will take place. It’s important to note that if this option is used without any uricontent rules. because it doesn’t alert on directory traversals that stay within the web server directory structure. The allow proxy use keyword is just a way to suppress unauthorized proxy use for an authorized server. and if there are none available. 34. only the URI portion of HTTP requests will be inspected for attacks. For IIS. This generates much fewer false positives than the directory option. 29. tab uri delimiter This option turns on the use of the tab character (0x09) as a delimiter for a URI. Whether this option is on or not. Requests that exceed this length will cause a ”Long Header” alert. Apache accepts tab as a delimiter. ) and the we inspect the following URI: get /foo. It only alerts when the directory traversals go past the web server root directory. IIS does not. 33. The integer is the maximum length allowed for an HTTP client request header field. non strict This option turns on non-strict URI parsing for the broken way in which Apache servers will decode a URI. The inspect uri only configuration turns off all forms of detection except uricontent inspection. an alert is generated. No argument is specified. Only use this option on servers that will accept URIs like this: ”get /index. oversize dir length <non-zero positive integer> This option takes a non-zero positive integer as an argument. This alert is off by default. enable this optimization. 35. This means that no alert will be generated if the proxy alert global keyword has been used. like whisker -i 4. A good argument value is 300 characters. 30. allow proxy use By specifying this keyword. 31. For example. if we have the following rule set: alert tcp any any -> any 80 ( msg:"content". webroot <yes|no> This option generates an alert when a directory traversal traverses past the web server root directory. This is obvious since the URI is only inspected with uricontent rules.
etc. multi-slash.1. normalize cookies This option turns on normalization for HTTP Cookie Fields (using the same configuration parameters as the URI normalization (ie. It is useful for normalizing data in HTTP Cookies that may be encoded. etc.). The alert is off by default. ”utf-32le”. specify an integer argument to max headers of 1 to 1024. http_methods { PUT CONNECT } ! △NOTE Please note the maximum length for a method name is 7 Examples preprocessor http_inspect_server: \ server 10. directory. or ”utf-32be”. normalize headers This option turns on normalization for HTTP Header Fields.). The integer is the maximum number of HTTP client request header fields. http methods {cmd[cmd]} This specifies additional HTTP Request Methods outside of those checked by default within the preprocessor (GET and POST). 40. The list should be enclosed within braces and delimited by spaces. Specifying a value of 0 is treated as disabling the alert. Requests that contain more HTTP Headers than this value will cause a ”Max Header” alert. tabs. generating an alert if the extra bytes are non-zero.36. 37. directory. braces and methods also needs to be separated by braces. To enable. not including Cookies (using the same configuration parameters as the URI normalization (ie. HTTP Inspect will attempt to normalize these back into 8-bit encoding \ 66 . line feed or carriage return. 39. normalize utf This option turns on normalization of HTTP response bodies where the Content-Type header lists the character set as ”utf-16le”. The config option. It is useful for normalizing Referrer URIs that may appear in the HTTP Header. ”utf-16be”. 38. max headers <positive integer up to 1024> This option takes an integer as an argument.1. multi-slash.
Also. this is relatively safe to do and can improve the performance of data inspection. 67 . 5. for encrypted SMTP. Space characters are defined as space (ASCII 0x20) or tab (ASCII 0x09). Since so few (none in the current snort rule set) exploits are against mail data. It will also mark the command. Configuration SMTP has the usual configuration items. SMTP will decode the buffer and find SMTP commands and responses. inspection type <stateful | stateless> Indicate whether to operate in stateful or stateless mode. SMTP handles stateless and stateful processing. a loss of coherent stream data results in a loss of state). In addition. RFC 2821 recommends 512 as a maximum command line length.. ignore data Ignore data section of mail (except for mail headers) when processing rules. 3. such as port and inspection type. Absence of this option or a ”0” means never alert on command line length. TLS-encrypted traffic can be ignored. The configuration options are described below: 1. all checks all commands none turns off normalization for all commands. data header data body sections. 6. 4. regular mail data can be ignored for an additional performance boost. ports { <port> [<port>] . Given a data buffer.2. Typically. 2. It saves state between individual packets. } This specifies on what ports to check for SMTP data.. this will include 25 and possibly 465. ignore tls data Ignore TLS-encrypted data when processing rules.ascii no \ chunk_length 500000 \ bare_byte yes \ double_decode yes \ iis_unicode yes \ iis_delimiter yes \ multi_slash no preprocessor http_inspect_server: \ server default \ profile all \ ports { 80 8080 } 2. However maintaining correct state is dependent on the reassembly of the client side of the stream (ie. which improves performance. normalize <all | none | cmds> This turns on normalization. max command line len <int> Alert if an SMTP command line is longer than this value. Normalization checks for more than one space character after a command. SMTP command lines can be normalized to remove extraneous spaces. and TLS data. cmds just checks commands listed with the normalize cmds parameter.7 SMTP Preprocessor The SMTP preprocessor is an SMTP decoder for user applications.
14. Absence of this option or a ”0” means never alert on data header line length. valid cmds { <Space-delimited list of commands> } List of valid commands. 17. alert unknown cmds Alert if we don’t recognize command. invalid cmds { <Space-delimited list of commands> } Alert if this command is sent from client side. 12. Drop if alerted. max mime depth <int> Specifies the maximum number of base64 encoded data to decode per SMTP session. RFC 2821 recommends 1024 as a maximum data header line length. max header line len <int> Alert if an SMTP DATA header line is longer than this value. print cmds List all commands understood by the preprocessor. 11. alt max command line len <int> { <cmd> [<cmd>] } Overrides max command line len for specific commands. 10. When stateful inspection is turned on the base64 encoded MIME attachments/data across multiple packets are decoded too. max response line len <int> Alert if an SMTP response line is longer than this value. 9. Multiple base64 encoded MIME attachments/data in one packet are pipelined. Default is enable. no alerts Turn off all alerts for this preprocessor. The decoding of base64 encoded attachments/data ends when either the max mime depth or maximum MIME sessions (calculated using max mime depth and max mime mem) is reached or when the encoded data ends. Default is an empty list. disabled Disables the SMTP preprocessor in a policy. RFC 2821 recommends 512 as a maximum response line length. 15. Default is off. The default value for this in snort in 1460 bytes. Default is an empty list. xlink2state { enable | disable [drop] } Enable/disable xlink2state alert. 68 . See 3. Absence of this option or a ”0” means never alert on response line length. 16. This not normally printed out with the configuration because it can print so much data. The decoded data is available for detection using the rule option file data:mime. enable mime decoding Enables Base64 decoding of Mime attachments/data. The option take values ranging from 5 to 20480 bytes. normalize cmds { <Space-delimited list of commands> } Normalize this list of commands Default is { RCPT VRFY EXPN }. 8. 19. We do not alert on commands in this list.24 rule option for more details. This is useful when specifying the max mime depth and max mime mem in default policy without turning on the SMTP preprocessor.7. 18.
For the preprocessor configuration. The default value for this option is 838860. } \ } \ HELO ETRN } \ VRFY } 69 . the preprocessor actually maps RCPT and MAIL to the correct command name. Note: It is suggested to set this value such that the max mime session calculated as follows is atleast 1. max mime mem <int> This option determines (in bytes) the maximum amount of memory the SMTP preprocessor will use for decoding base64 encode MIME attachments/data. This option along with max mime depth determines the base64 encoded MIME/SMTP sessions that will be decoded at any given instant.. respectively. max mime session = max mime mem /(max mime depth + max decoded bytes) max decoded bytes = (max mime depth/4)*3 Also note that these values for max mime mem and max mime depth need to be same across all policy.20. Within the code. they are referred to as RCPT and MAIL. This value can be set from 3276 bytes to 100MB.
whereas in stateful mode. Configuration 1.2.6). The default is to run FTP/Telnet in stateful inspection mode. Users can configure individual FTP servers and clients with a variety of options. inspection type This indicates whether to operate in stateful or stateless mode. checks for encrypted traffic will occur on every packet. meaning it looks for information and handles reassembled data correctly. The FTP/Telnet global configuration must appear before the other three areas of configuration. FTP/Telnet has a very “rich” user configuration. Within FTP/Telnet.8 FTP/Telnet Preprocessor FTP/Telnet is an improvement to the Telnet decoder and provides stateful inspection capability for both FTP and Telnet data streams. check encrypted Instructs the preprocessor to continue to check an encrypted session for a subsequent command to cease encryption. you’ll get an error if you try otherwise. and FTP Server. The presence of the option indicates the option itself is on. FTP/Telnet has the capability to handle stateless processing. Global Configuration The global configuration deals with configuration options that determine the global functioning of FTP/Telnet. 2. meaning it only looks for information on a packet-bypacket basis. FTP Client. FTP/Telnet will decode the stream. which should allow the user to emulate any type of FTP server or FTP Client. The following example gives the generic global configuration format: Format preprocessor ftp_telnet: \ global \ inspection_type stateful \ encrypted_traffic yes \ check_encrypted You can only have a single global configuration.2. 70 . identifying FTP commands and responses and Telnet escape sequences and normalize the fields. 3. there are four areas of configuration: Global. ! △NOTE Some configuration options have an argument of yes or no. This argument specifies whether the user wants the configuration option to generate a ftptelnet alert or not. encrypted traffic <yes|no> This option enables detection and alerting on encrypted Telnet and FTP command channels. FTP/Telnet works on both client requests and server responses. a particular session will be noted as encrypted and not inspected any further. ! △NOTE When inspection type is in stateless mode.2. Telnet. while the yes/no argument applies to the alerting functionality associated with that option. similar to that of HTTP Inspect (See 2.
Being that FTP uses the Telnet protocol on the control connection. Telnet supports subnegotiation. It functions similarly to its predecessor. Per the Telnet RFC. 3. 71 ... It is only applicable when the mode is stateful. This is anomalous behavior which could be an evasion case. ports {<port> [<port>< .. >]} This is how the user configures which ports to decode as telnet traffic. the telnet decode preprocessor. SSH tunnels cannot be decoded. subnegotiation begins with SB (subnegotiation begin) and must end with an SE (subnegotiation end). it is also susceptible to this behavior. 4. Configuration 1. ayt attack thresh < number > This option causes the preprocessor to alert when the number of consecutive telnet Are You There (AYT) commands reaches the number specified. Rules written with ’raw’ content options will ignore the normalized buffer that is created when this option is in use. and subsequent instances will override previously set values. certain implementations of Telnet servers will ignore the SB without a corresponding SE.. normalize This option tells the preprocessor to normalize the telnet traffic by eliminating the telnet escape sequences. detect anomalies In order to support certain options. However. so adding port 22 will only yield false positives. Typically port 23 will be included. The detect anomalies option enables alerting on Telnet SB without the corresponding SE.
>]} This option specifies which ports the SSH preprocessor should inspect traffic to. If those bytes exceed a predefined limit within a predefined number of packets.Examples/Default Configuration from snort.. Configuration By default. Secure CRT. an alert is generated..9 SSH The SSH preprocessor detects the following exploits: Challenge-Response Buffer Overflow. preprocessor ftp_telnet_protocol: \ ftp server default \ def_max_param_len 100 \ alt_max_param_len 200 { CWD } \ cmd_validity MODE < char ASBCZ > \ cmd_validity MDTM < [ date nnnnnnnnnnnnnn[. The Secure CRT and protocol mismatch exploits are observable before the key exchange. and are therefore encrypted. To detect the attacks. Set CWD to allow parameter length of 200 MODE has an additional mode of Z (compressed) Check for string formats in USER & PASS commands Check MDTM commands that set modification time on the file. The available configuration options are described below. the SSH preprocessor counts the number of bytes transmitted to the server. CRC 32. the SSH version string exchange is used to distinguish the attacks. Both attacks involve sending a large payload (20kb+) to the server immediately after the authentication challenge. 76 .2. 1. Since the Challenge-Response Overflow only effects SSHv2 and CRC 32 only effects SSHv1. Both Challenge-Response Overflow and CRC 32 attacks occur after the key exchange. server ports {<port> [<port>< . all alerts are disabled and the preprocessor checks traffic on port 22.conf preprocessor ftp_telnet: \ global \ encrypted_traffic yes \ inspection_type stateful preprocessor ftp_telnet_protocol:\ telnet \ normalize \ ayt_attack_thresh 200 # # # # # This is consistent with the FTP rules as of 18 Sept 2004. and the Protocol Mismatch exploit.
3. enable paysize Enables alerts for invalid payload sizes. 7. enable protomismatch Enables checking for the Protocol Mismatch exploit. This value can be set from 0 to 65535. Snort ignores the session to increase performance. The SSH preprocessor should work by default. max encrypted packets < number > The number of encrypted packets that Snort will inspect before ignoring a given SSH session. the preprocessor will stop processing traffic for a given session.2. enable badmsgdir Enable alerts for traffic flowing the wrong direction. enable recognition Enable alerts for non-SSH traffic on SSH ports. This value can be set from 0 to 255. Once max encrypted packets packets have been seen. or else Snort will ignore the traffic. max server version len < number > The maximum number of bytes allowed in the SSH server version string before alerting on the Secure CRT server version string overflow. try increasing the number of required client bytes with max client bytes. if the presumed server generates client traffic. Alerts at 19600 unacknowledged bytes within 20 encrypted packets for the Challenge-Response Overflow/CRC32 exploits. Example Configuration from snort. This number must be hit before max encrypted packets packets are sent. enable respoverflow Enables checking for the Challenge-Response Overflow exploit. 5. autodetect Attempt to automatically detect SSH. 11. After max encrypted packets is reached. The SSH vulnerabilities that Snort can detect all happen at the very beginning of an SSH session. or if a client generates server traffic. enable ssh1crc32 Enables checking for the CRC 32 exploit. enable srvoverflow Enables checking for the Secure CRT exploit.conf Looks for attacks on SSH server port 22. The default is set to 80. This value can be set from 0 to 65535. If Challenge-Response Overflow or CRC 32 false positive. 12. preprocessor ssh: \ server_ports { 22 } \ max_client_bytes 19600 \ max_encrypted_packets 20 \ enable_respoverflow \ enable_ssh1crc32 77 . 8. The default is set to 25. 9. The default is set to 19600. 6. For instance. max client bytes < number > The number of unanswered bytes allowed to be transferred before alerting on Challenge-Response Overflow or CRC 32. 10. 4.
Typically. Therefore. DNS looks at DNS Response traffic over UDP and TCP and it requires Stream preprocessor to be enabled for TCP decoding. only the SSL handshake of each connection will be inspected. the session is not marked as encrypted. enable rdata overflow Check for DNS Client RData TXT Overflow The DNS preprocessor does nothing if none of the 3 vulnerabilities it checks for are enabled. It will not operate on TCP sessions picked up midstream. Examples/Default Configuration from snort. Once the traffic is determined to be encrypted. 1. SSLPP looks for a handshake followed by encrypted traffic traveling to both sides. Do not alert on obsolete or experimental RData record types. ports {<port> [<port>< . Check for the DNS Client RData overflow vulnerability.2. The available configuration options are described below.11 SSL/TLS Encrypted traffic should be ignored by Snort for both performance reasons and to reduce false positives. Obsolete Record Types.2. By enabling the SSLPP to inspect port 443 and enabling the noinspect encrypted option. >]} This option specifies the source ports that the DNS preprocessor should inspect traffic. Configuration By default. all alerts are disabled and the preprocessor checks traffic on port 53. the only observed response from one endpoint will be TCP ACKs.. the user should use the ’trustservers’ option. enable experimental types Alert on Experimental (per RFC 1035) Record Types 4..2. preprocessor dns: \ ports { 53 } \ enable_rdata_overflow 2.conf Looks for traffic on DNS server port 53. and that the traffic is legitimately encrypted. and Experimental Record Types. if a user knows that server-side encrypted data can be trusted to mark the session as encrypted.10 DNS The DNS preprocessor decodes DNS Responses and can detect the following exploits: DNS Client RData Overflow. no further inspection of the data on the connection is made. Verifying that faultless encrypted traffic is sent from both endpoints ensures two things: the last client-side handshake packet was not crafted to evade Snort. enable obsolete types Alert on Obsolete (per RFC 1035) Record Types 3. In some cases. 78 . especially when packets may be missed. documented below. If one side responds with an indication that something has failed. SSL is used over port 443 as HTTPS. By default. and it will cease operation on a session if it loses state because of missing data (dropped packets). 2. The SSL Dynamic Preprocessor (SSLPP) decodes SSL and TLS traffic and optionally determines if and when Snort should stop inspection of it. such as the handshake.
>]} This option specifies which ports SSLPP will inspect traffic on.. noinspect encrypted Disable inspection on traffic that is encrypted. By default. Default is off. The list of version identifiers are below. version-list version = ["!"] "sslv2" | "sslv3" | "tls1.2" Examples 79 .Configuration 1. The option will match if any one of the OR’ed versions are used in the SSL connection. 3. via a comma separated list. Lists of identifiers are OR’ed together. Syntax ssl_version: <version-list> version-list = version | version ... Examples/Default Configuration from snort.conf Enables the SSL preprocessor and tells it to disable inspection on encrypted traffic.0" | "tls1.. Default is off. To check for two or more SSL versions in use simultaneously. This requires the noinspect encrypted option to be useful. ports {<port> [<port>< . Use this option for slightly better performance if you trust that your servers are not compromised.1" | "tls1. trustservers Disables the requirement that application (encrypted) data must be observed on both sides of the session before a session is marked encrypted. multiple ssl version rule options should be used. and more than one identifier can be specified.
2.0.2. When ”-unicast” is specified as the argument of arpspoof. and inconsistent Ethernet to IP mapping. The option will match if the connection is currently in any one of the OR’ed states. ssl state The ssl state rule option tracks the state of the SSL encryption during the process of hello and key exchange. ssl_version:!sslv2. ssl_state:!server_hello. ssl_state:client_keyx.12 ARP Spoof Preprocessor The ARP spoof preprocessor decodes ARP packets and detects ARP attacks. the preprocessor checks for unicast ARP requests. via a comma separated list. ssl_version:tls1. preprocessor arpspoof 80 . More than one state can be specified. 2. state-list state = ["!"] "client_hello" | "server_hello" | "client_keyx" | "server_keyx" | "unknown" Examples ssl_state:client_hello.tls1. Syntax ssl_state: <state-list> state-list = state | state .tls1. Format preprocessor arpspoof[: -unicast] preprocessor arpspoof_detect_host: ip mac Option ip mac Description IP address. The preprocessor will use this list when detecting ARP cache overwrite attacks. and are OR’ed together. Specify one host IP MAC combo per line. To ensure the connection has reached each of a set of states. An alert with GID 112 and SID 1 will be generated if a unicast ARP request is detected. Alert SID 4 is used in this case.ssl_version:sslv3. the preprocessor inspects Ethernet addresses and the addresses in the ARP packets. Specify a pair of IP and hardware address as the argument to arpspoof detect host.1. unicast ARP requests. The preprocessor merely looks for Ethernet address inconsistencies. The host with the IP address should be on the same layer 2 segment as Snort is. When no arguments are specified to arpspoof.server_keyx. multiple rules using the ssl state rule option should be used. The list of states are below. The Ethernet address corresponding to the preceding IP. an alert with GID 112 and SID 2 or 3 is generated. When inconsistency occurs. Example Configuration The first example configuration does neither unicast detection nor ARP mapping monitoring.
168. Samba greater than 3.168. Samba 3.168.0. The following transports are supported for DCE/RPC: SMB.13 DCE/RPC 2 Preprocessor The main purpose of the preprocessor is to perform SMB desegmentation and DCE/RPC defragmentation to avoid rule evasion using these techniques.1 and 192.2 f0:0f:00:f0:0f:01 2.40.2 f0:0f:00:f0:0f:01 The third example configuration has unicast detection enabled. Some important differences: Named pipe instance tracking A combination of valid login handle or UID. • IP defragmentation should be enabled. Transaction Secondary.e. Dependency Requirements For proper functioning of the preprocessor: • Stream session tracking must be enabled.The next example configuration does not do unicast detection but monitors ARP mapping for hosts 192.40. Target Based There are enough important differences between Windows and Samba versions that a target based approach has been implemented.40. If it is decided that a session is SMB or DCE/RPC. preprocessor arpspoof preprocessor arpspoof_detect_host: 192. The binding between these is dependent on OS/software version.168.168. the dcerpc2 preprocessor will enable stream reassembly for that session if necessary. if the TID used in creating the FID is deleted (via a tree disconnect). i. however. Write and Close. preprocessor arpspoof: -unicast preprocessor arpspoof_detect_host: 192.22 81 .0. Read.22 and earlier Any valid UID and TID. the FID that was created using this TID becomes invalid. the frag3 preprocessor should be enabled and configured. reduce false positives and reduce the count and complexity of DCE/RPC based rules.40.2. TCP. Write AndX. UDP and RPC over HTTP v.e.40.168. • Stream reassembly must be performed for TCP sessions. New rule options have been implemented to improve performance. no more requests can be written to that named pipe instance.40.1 f0:0f:00:f0:0f:00 preprocessor arpspoof_detect_host: 192. The preprocessor requires a session tracker to keep its data. stream5. either through configured ports.1 proxy and server. servers or autodetecting. along with a valid FID can be used to make a request. i. Transaction. Write Block Raw.e. SMB desegmentation is performed for the following commands that can be used to transport DCE/RPC requests and responses: Write.1 f0:0f:00:f0:0f:00 preprocessor arpspoof_detect_host: 192. share handle or TID and file/named pipe handle or FID must be used to write data to a named pipe.2. Read Block Raw and Read AndX. i.
no more requests can be written to that named pipe instance. e.g. data is written to the named pipe as it is received by the server. along with a valid FID can be used to make a request. Segments for each ”thread” are stored separately and written to the named pipe when all segments are received.e. having the same FID) are fields in the SMB header representing a process id (PID) and multiplex id (MID). does not accept: Open Write And Close Read Read Block Raw Write Block Raw Windows (all versions) Accepts all of the above commands under an IPC$ tree. Windows 2003 Windows XP Windows Vista These Windows versions require strict binding between the UID. no binding. whereas in using the Write* commands. the FID that was created using this TID becomes invalid. login/logoff and tree connect/tree disconnect. Samba. Ultimately. is very lax and allows some nonsensical combinations. An evasion possibility would be accepting a fragment in a request that the server won’t accept that gets sandwiched between an exploit.22 and earlier. Both the UID and TID used to open the named pipe instance must be used when writing data to the same named pipe instance.e. Windows 2000 Windows 2000 is interesting in that the first request to a named pipe must use the same binding as that of the other Windows versions. i. i. However. the client has to explicitly send one of the Read* requests to tell the server to send the response and (2) a Transaction request is not written to the named pipe until all of the data is received (via potential Transaction Secondary requests) whereas with the Write* commands. deleting either the UID or TID invalidates the FID.22 in that deleting the UID or TID used to create the named pipe instance also invalidates it. If the UID used to create the named pipe instance is deleted (via a Logoff AndX). It also follows Samba greater than 3. i. multiple logins and tree connects (only one place to return handles for these). the FID becomes invalid. What distinguishes them (when the same named pipe is being written to. AndX command chaining Windows is very strict in what command combinations it allows to be chained. Transaction tracking The differences between a Transaction request and using one of the Write* commands to write data to a named pipe are that (1) a Transaction performs the operations of a write and a read from the named pipe.0. If the TID used to create the FID is deleted (via a tree disconnect). on the other hand. since it is necessary in making a request to the named pipe. TID and FID used to make a request to a named pipe instance. It is necessary to track this so as not to munge these requests together (which would be a potential evasion opportunity). An MID represents different sub-processes within a process (or under a PID). The PID represents the process this request is a part of. These requests can also be segmented with Transaction Secondary commands.0. However. only the UID used in opening the named pipe can be used to make a request using the FID handle to the named pipe instance. requests after that follow the same binding as Samba 3.e. Multiple Transaction requests can be made simultaneously to the same named pipe. Samba (all versions) Under an IPC$ tree. Therefore. Accepted SMB commands Samba in particular does not recognize certain commands under an IPC$ tree. 82 . we don’t want to keep track of data that the server won’t accept.Any valid TID.
DCE/RPC Fragmented requests . The context id field in any other fragment can contain any value. all previous interface bindings are invalidated. Windows (all versions) The byte order of the stub data is that which was used in the Bind request. DCE/RPC Fragmented requests .20 Another Bind request can be made if the first failed and no interfaces were successfully bound to. The opnum field in any other fragment can contain any value. DCE/RPC Stub data byte order The byte order of the stub data is determined differently for Windows and Samba.Context ID Each fragment in a fragmented request carries the context id of the bound interface it wants to make the request to. Windows Vista The opnum that is ultimately used for the request is contained in the first fragment.Windows (all versions) Uses a combination of PID and MID to define a ”thread”. Samba (all versions) The byte order of the stub data is that which is used in the request carrying the stub data.0. Samba later than 3. Samba (all versions) Windows 2000 Windows 2003 Windows XP The opnum that is ultimately used for the request is contained in the last fragment. The opnum field in any other fragment can contain any value. Samba (all versions) The context id that is ultimately used for the request is contained in the last fragment.20 and earlier Any amount of Bind requests can be made.Operation number Each fragment in a fragmented request carries an operation number (opnum) which is more or less a handle to a function offered by the interface. all previous interface bindings are invalidated. Any binding after that must use the Alter Context request. If a Bind after a successful Bind is made. Windows (all versions) For all of the Windows versions. only one Bind can ever be made on a session whether or not it succeeds or fails. 83 . If another Bind is made. Multiple Bind Requests A Bind request is the first request that must be made in a connection-oriented DCE/RPC session in order to specify the interface/interfaces that one wants to communicate with. Samba (all versions) Uses just the MID to define a ”thread”. Windows (all versions) The context id that is ultimately used for the request is contained in the first fragment. The context id field in any other fragment can contain any value. Samba 3.0.
’ event-list "memcap" | "smb" | "co" | "cl" 0-65535 Option explanations memcap Specifies the maximum amount of run-time memory that can be allocated. If a fragment is greater than this size. Default is to do defragmentation. By default this value is turned off. disabled Disables the preprocessor. smb 84 .65535. Global Configuration preprocessor dcerpc2 The global dcerpc2 configuration is required. alert. If the memcap is reached or exceeded. ’. When the preprocessor is disabled only the memcap option is applied when specified with the configuration.) memcap Only one event. it is truncated before being added to the defragmentation module. max frag len Specifies the maximum fragment size that will be added to the defragmention module. events Specifies the classes of events to enable. Run-time memory includes any memory allocated after configuration. The global preprocessor configuration name is dcerpc2 and the server preprocessor configuration name is dcerpc2 server. disable defrag Tells the preprocessor not to do DCE/RPC defragmentation. The allowed range for this option is 1514 . Default is 100 MB. (See Events section for an enumeration and explanation of events. Default is set to -1.
A dcerpc2 server configuration must start with default or net options..Alert on events related to SMB processing. the default configuration is used if no net configurations match. Default is disabled. A value of 0 supplied as an argument to this option will. Option examples memcap 30000 max_frag_len 16840 events none events all events smb events co events [co] events [smb. Note that port and ip variables defined in snort. co] events [memcap. memcap 300000. When processing DCE/RPC traffic. in effect. A net configuration matches if the packet’s server IP address matches an IP address or net specified in the net configuration. disable this option. co Stands for connection-oriented DCE/RPC. If a net configuration matches. Alert on events related to connectionless DCE/RPC processing. events [memcap. the defaults will be used. Option syntax 85 . co. At most one default configuration can be specified. max_frag_len 14440 disable_defrag. Zero or more net configurations can be specified.. default values will be used for the default configuration. co. events smb memcap 50000. smb. For any dcerpc2 server configuration. cl Stands for connectionless DCE/RPC. If no default configuration is specified. The net option supports IPv6 addresses. events [memcap. reassemble threshold Specifies a minimum number of bytes in the DCE/RPC desegmentation and defragmentation buffers before creating a reassembly packet to send to the detection engine. cl]. This option is useful in inline mode so as to potentially catch an exploit early before full defragmentation is done. Alert on events related to connection-oriented DCE/RPC processing. it will override the default configuration. if non-required options are not specified. smb.conf CANNOT be used. The default and net options are mutually exclusive.
593 for RPC over HTTP server and 80 for RPC over HTTP proxy. rpc-over-http-server 593] autodetect [tcp 1025:. tcp 135.’. udp 135. shares with ’$’ must be enclosed quotes.’ ’"’ ’]’ ’[’ ’$’ graphical ASCII characters except ’.Option default net policy detect Argument NONE <net> <policy> <detect> Required YES YES NO Default NONE NONE policy WinXP detect [smb [139. net Specifies that this configuration is an IP or net specific configuration. udp 1025:. Option explanations default Specifies that this configuration is for the default server configuration. rpc-over-http-server 1025:] DISABLED (The preprocessor autodetects on all proxy ports by default) NONE smb max chain 3 ip | ’[’ ip-list ’]’ ip | ip ’.’ detect-list transport | transport port-item | transport ’[’ port-list ’]’ "smb" | "tcp" | "udp" | "rpc-over-http-proxy" | "rpc-over-http-server" port-item | port-item ’. detect Specifies the DCE/RPC transport and server ports that should be detected on for the transport.’ share-list word | ’"’ word ’"’ | ’"’ var-word ’"’ graphical ASCII characters except ’.0.’ ’"’ ’]’ ’[’ 0-255 Because the Snort main parser treats ’$’ as the start of a variable and tries to expand it.0.22" | "Samba-3. 86 . 135 for TCP and UDP. The configuration will only apply to the IP addresses and nets supplied as an argument.’ port-list port | port-range ’:’ port | port ’:’ | port ’:’ port 0-65535 share | ’[’ share-list ’]’ share | share ’. policy Specifies the target-based policy to use when processing.445].20" "none" | detect-opt | ’[’ detect-list ’]’ detect-opt | detect-opt ’. Defaults are ports 139 and 445 for SMB. Default is ”WinXP”.
The autodetect ports are only queried if no detect transport/ports match the packet.6005:]] smb_invalid_shares private smb_invalid_shares "private" smb_invalid_shares "C$" smb_invalid_shares [private.3003:] autodetect [tcp [2025:3001.168. tcp [135.0/24 net [192.2103]] detect [smb [139.255. tcp 135. Note that most dynamic DCE/RPC ports are above 1024 and ride directly over TCP or UDP.445].0/24.168. "C$"] smb_max_chain 1 87 . Option examples net 192. It would be very uncommon to see SMB on anything other than ports 139 and 445. feab:45b3:ab92:8ac4:d322:007f:e5aa:7845] policy Win2000 policy Samba-3.10. the preprocessor will always attempt to autodetect for ports specified in the detect configuration for rpc-over-http-proxy. Default maximum is 3 chained commands.0.0/24] net 192. This is because the proxy is likely a web server and the preprocessor should not look at all web traffic.445] detect [smb [139. feab:45b3::/32] net [192. RPC over HTTP server. rpc-over-http-server [1025:6001. A value of 0 disables this option. udp. smb invalid shares Specifies SMB shares that the preprocessor should alert on if an attempt is made to connect to them via a Tree Connect or Tree Connect AndX.168. udp 135.445]] detect [smb. Default is empty.10 net 192.22 detect none detect smb detect [smb] detect smb 445 detect [smb 445] detect smb [139.autodetect Specifies the DCE/RPC transport and server ports that the preprocessor should attempt to autodetect on for the transport. udp] autodetect [tcp 2025:.3003:]] autodetect [tcp. no autodetect http proxy ports By default. smb max chain Specifies the maximum amount of AndX command chaining that is allowed before an alert is generated.0. rpc-over-http-server [593. Default is to autodetect on RPC over HTTP proxy detect ports.255. This option is useful if the RPC over HTTP proxy configured with the detect option is only used to proxy DCE/RPC traffic. Defaults are 1025-65535 for TCP.0.0. udp 2025:] autodetect [tcp 2025:.0.0/255.168.0. "C$"] smb_invalid_shares ["private".. This value can be set from 0 to 255. tcp] detect [smb 139.168. UDP and RPC over HTTP server.0. RPC over HTTP proxy and lastly SMB.168.TCP/UDP.
rpc-over-http-proxy 8081]. policy WinVista. tcp. Memcap events SID 1 Description If the memory cap is reached and the preprocessor is configured to alert. \ detect [smb. rpc-over-http-proxy [1025:6001.11. rpc-over-http-server 593]. autodetect none Default server configuration preprocessor dcerpc2_server: default. "ADMIN$"] preprocessor dcerpc2_server: net 10. Valid types are: Message. SMB events SID 2 Description An invalid NetBIOS Session Service type was specified in the header.feab:45b3::/126].0/24. no_autodetect_http_proxy_ports preprocessor dcerpc2_server: \ net [10.445]. \ smb_invalid_shares ["C$". Negative Response (only from server). 3 88 . rpc-over-http-server 1025:]. detect smb. policy WinVista. \ detect [smb [139. policy WinXP. Request (only from client). \ autodetect [tcp 1025:.4.11.445]. An SMB message type was specified in the header. udp 135. policy Win2000 preprocessor dcerpc2_server: \ default. \ smb_invalid_shares ["C$". policy WinXP.feab:45b3::/126]. smb_max_chain 3 Events The preprocessor uses GID 133 to register events.0/24. Either a request was made by the server or a response was given by the client. policy Win2000. policy Samba.4.57]. rpc-over-http-server 1025:]. rpc-over-http-server 593]. Positive Response (only from server). tcp 135.10.4. tcp 135. udp 1025:. policy Win2000 preprocessor dcerpc2_server: \ net [10.10. Retarget Response (only from server) and Keep Alive. autodetect [tcp.4. udp 1025:.10.6005:]].Configuration examples preprocessor dcerpc2_server: \ default preprocessor dcerpc2_server: \ default. autodetect tcp 1025:.10.0/24. tcp]. smb_max_chain 1 preprocessor dcerpc2_server: \ net [10. udp 135. detect [smb. smb_max_chain 3 Complete dcerpc2 default configuration preprocessor dcerpc2: memcap 102400 preprocessor dcerpc2_server: \ default.56. "ADMIN$"]. \ detect [smb [139.4. \ autodetect [tcp 1025:. "D$".. After a client is done writing data using the Write* commands. does not contain this file id. The server response. There should be under normal circumstances no more than a few pending tree connects at a time and the preprocessor will alert if this number is excessive. There should be under normal circumstances no more than a few pending Read* requests at a time and the preprocessor will alert if this number is excessive. If multiple Read* requests are sent to the server.. however. (The byte count must always be greater than or equal to the data size. Many SMB commands have a field containing an offset from the beginning of the SMB header to where the data the command is carrying starts. Unlike the Tree Connect AndX response. the preprocessor will alert. it issues a Read* command to the server to tell it to send a response to the data it has written. The preprocessor will alert if the number of chained commands in a single request is greater than or equal to the configured amount (default is 3). The preprocessor will alert if the byte count minus a predetermined amount based on the SMB command is not equal to the data size.4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 The SMB id does not equal \xffSMB. In this case the preprocessor is concerned with the server response. The word count of the command header is invalid. The Read* request contains the file id associated with a named pipe instance that the preprocessor will ultimately send the data to. If this offset puts us before data that has already been processed or after the end of payload. For the Tree Connect command (and not the Tree Connect AndX command). they are responded to in the order they were sent.) The preprocessor will alert if the total amount of data sent in a transaction is greater than the total data count specified in the SMB command header. there is no indication in the Tree Connect response as to whether the share is IPC or not. the preprocessor will alert. the preprocessor will alert. such as Transaction. the preprocessor has to queue the requests up and wait for a server response to determine whether or not an IPC share was successfully connected to (which is what the preprocessor is interested in). so it need to be queued with the request and dequeued with the response. Note that since the preprocessor does not yet support SMB2. Some SMB commands. (Total data count must always be greater than or equal to current data size. The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command header to be decoded. the preprocessor will alert. If this field is zero. especially the commands from the SMB Core implementation require a data format field that specifies the kind of data that will be coming next. Some commands require a specific format for the data. id of \xfeSMB is turned away before an eventable point is reached.. If a command requires this and the byte count is less than the minimum required byte count for that command. Some commands require a minimum number of bytes after the command header. SMB commands have pretty specific word counts and if the preprocessor sees a command with a word count that doesn’t jive with that command. The preprocessor will alert if the NetBIOS Session Service length field contains a value less than the size of an SMB header. 89 . Some commands. The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command byte count specified in the command header. combination of a Tree Connect AndX command with a chained Tree Disconnect command. only one place in the SMB header to return a login handle (or Uid). It looks for a Tree Connect or Tree Connect AndX to the share. There is. 90 35 36 . This is anomalous behavior and the preprocessor will alert if it happens. The preprocessor will alert if a fragment is larger than the maximum negotiated fragment length. however Samba does. This is used by the client in subsequent requests to indicate that it has authenticated. essentially connects to a share and disconnects from the same share in the same request and is anomalous behavior. Windows does not allow this behavior. The preprocessor will alert if in a Bind or Alter Context request. With commands that are chained after a Session Setup AndX request. The preprocessor will alert if it sees this. A Tree Connect AndX command is used to connect to a share. When a Session Setup AndX request is sent to the server. It is anomalous behavior to attempt to change the byte order mid-session. The preprocessor will alert if in a Bind or Alter Context request. This is anomalous behavior and the preprocessor will alert if it happens. however. With AndX command chaining it is possible to chain multiple Tree Connect AndX commands within the same request. The byte order of the request data is determined by the Bind in connection-oriented DCE/RPC for Windows.) The Close command is used to close that file or named pipe. An Open AndX or Nt Create AndX command is used to open/create a file or named pipe. Most evasion techniques try to fragment the data as much as possible and usually each fragment comes well below the negotiated transmit size. The combination of a Session Setup AndX command with a chained Logoff AndX command. the login handle returned by the server is used for the subsequent chained commands. The preprocessor will alert if a non-last fragment is less than the size of the negotiated maximum fragment length.21 22 23 24 25 26 With AndX command chaining it is possible to chain multiple Session Setup AndX commands within the same request. essentially opens and closes the named pipe in the same request and is anomalous behavior. The preprocessor will alert if it sees this. however. The combination of a Open AndX or Nt Create AndX command with a chained Close command. The preprocessor will alert if the fragment length defined in the header is less than the size of the header. there are no transfer syntaxes to go with the requested interface. only one place in the SMB header to return a tree handle (or Tid). Windows does not allow this behavior. The preprocessor will alert if it sees any of the invalid SMB shares configured. There is. (The preprocessor is only interested in named pipes as this is where DCE/RPC requests are written to. A Logoff AndX request is sent by the client to indicate it wants to end the session and invalidate the login handle. The preprocessor will alert if it sees this. there are no context items specified. however Samba does. essentially logins in and logs off in the same request and is anomalous behavior. The Tree Disconnect command is used to disconnect from that share. The preprocessor will alert if the connection-oriented DCE/RPC PDU type contained in the header is not a valid PDU type. The preprocessor will alert if the remaining fragment length is less than the remaining packet size. the server responds (if the client successfully authenticates) which a user id or login handle.
The representation of the interface UUID is different depending on the endianness specified in the DCE/RPC previously requiring two rules . The context id is a handle to a interface that was bound to.. When a client sends a bind request to the server. The preprocessor will alert if the connectionless DCE/RPC PDU type is not a valid PDU type. using this rule option. Connectionless DCE/RPC events SID 40 41 42 43 Description The preprocessor will alert if the connectionless DCE/RPC major version is not equal to 4. this number should stay the same for all fragments. In testing.37 38 39 The call id for a set of fragments in a fragmented request should stay the same (it is incremented for each complete request). This can eliminate false positives where more than one service is bound to successfully since the preprocessor can correlate the bind UUID to the context id used in the request. The preprocessor will alert if the sequence number uses in a request is the same or less than a previously used sequence number on the session.one for big endian and 91 . so this should be considered anomalous behavior. If a request is fragmented. Each interface UUID is paired with a unique index (or context id) that future requests can use to reference the service that the client is making a call to. however. The operation number specifies which function the request is calling on the bound interface. specify one or more service interfaces to bind to. The preprocessor will alert if the context id changes in a fragment mid-request. it will specify the context id so the server knows what service the client is making a request to. The server will respond with the interface UUIDs it accepts as valid and will allow the client to make requests to those services. it can. It is necessary for a client to bind to a service before being able to make a call to it. whether or not the client has bound to a specific interface UUID and whether or not this client request is making a request to it. this number should stay the same for all fragments. The preprocessor will alert if the packet data length is less than the size of the connectionless header. The preprocessor will alert if the opnum changes in a fragment mid-request. Instead of using flow-bits. The preprocessor will alert if it changes in a fragment mid-request. wrapping the sequence number space produces strange behavior from the server. A DCE/RPC request can specify whether numbers are represented as big endian or little endian. When a client makes a request. Each interface is represented by a UUID. a rule can simply ask the preprocessor. If a request if fragmented.
However. equal to (’=’) or not equal to (’!’) the version specified.one for little endian. any_frag. This can be a source of false positives in fragmented DCE/RPC traffic. The any frag argument says to evaluate for middle and last fragments as well. the client specifies a list of interface UUIDs along with a handle (or context id) for each interface UUID that will be used during the DCE/RPC session to reference the interface. any_frag]. This tracking is required so that when a request is processed. will be looking at the wrong data on a fragment other than the first. Also. By default it is reasonable to only evaluate if the request is a first fragment (or full request). hexlong and hexshort will be specified and interpreted to be in big endian order (this is usually the default way an interface UUID will be seen and represented). 92 . Many checks for data in the DCE/RPC request are only relevant if the DCE/RPC request is a first fragment (or full request). This option is used to specify an interface UUID. <operator><version>][. dce_iface:4b324fc8-1670-01d3-1278-5a47bf6ee188. The preprocessor eliminates the need for two rules by normalizing the UUID..it either accepts or rejects the client’s wish to bind to a certain interface. a middle or the last fragment. dce_iface:4b324fc8-1670-01d3-1278-5a47bf6ee188. not a fragment) since most rules are written to start at the beginning of a request.e. For each Bind and Alter Context request. say 5 bytes into the request (maybe it’s a length field). This option requires tracking client Bind and Alter Context requests as well as server Bind Ack and Alter Context responses for connection-oriented DCE/RPC in the preprocessor. An interface contains a version. dce_iface:4b324fc8-1670-01d3-1278-5a47bf6ee188. Some versions of an interface may not be vulnerable to a certain exploit. As an example. a DCE/RPC request can be broken up into 1 or more fragments. any_frag. A rule which is looking for data. <2. the context id used in the request can be correlated with the interface UUID it is a handle for. by default the rule will only be evaluated for a first fragment (or full request. The server response indicates which interfaces it will allow the client to make requests to . Syntax dce_iface:<uuid>[.. greater than (’>’). i. since subsequent fragments will contain data deeper into the DCE/RPC request. if the any frag option is used to specify evaluating on all fragments. Optional arguments are an interface version and operator to specify that the version be less than (’<’). =1. Also.
in both big and little endian format will be inserted into the fast pattern matcher. 18-20. dce_opnum:15-18. it will unequivocally be used over the above mentioned patterns. It is likely that an exploit lies in the particular DCE/RPC function call. (2) if the rule option flow:from server|to client is used. (1) if the rule option flow:to server|from client is used. Syntax dce_opnum:<opnum-list>. 93 . dce stub data Since most netbios rules were doing protocol decoding only to get to the DCE/RPC stub data. For TCP rules.e. This reduces the number of rule option checks and the complexity of the rule. ! △NOTE Using this rule option will automatically insert fast pattern contents into the fast pattern matcher. This option takes no arguments. For UDP rules. dce_opnum:15. Note that a defragmented DCE/RPC request will be considered a full request. After is has been determined that a client has bound to a specific interface and is making a request to it (see above . |05 00| will be inserted into the fast pattern matcher. This option is used to specify an opnum (or operation number). i. This option matches if there is DCE/RPC stub data. 20-22. 17. If a content in the rule uses the fast pattern rule option. The opnum of a DCE/RPC request will be matched against the opnums specified with this option. the best (meaning longest) pattern will be used. opnum range or list containing either or both opnum and/or opnum-range. This option matches if any one of the opnums specified match the opnum of the DCE/RPC request. Example dce_stub_data. dce_opnum:15.’ opnum-list opnum | opnum-range opnum ’-’ opnum 0-65535 Examples dce_opnum:15. |05 00 00| will be inserted into the fast pattern matcher. There are no arguments to this option. dce opnum The opnum represents a specific function call to. the interface UUID. this option will alleviate this need and place the cursor at the beginning of the DCE/RPC stub data. opnum-list opnum-item opnum-range opnum = = = = opnum-item | opnum-item ’.dce iface) usually we want to know what function call it is making to that service. This option is used to place the cursor (used to walk the packet payload in rules processing) at the beginning of the DCE/RPC stub data. the remote procedure call or function call data. the version operation is true. Note that if the rule already has content rule options in it.This option matches if the specified interface UUID matches the interface UUID (as referred to by the context id) of the DCE/RPC request and if supplied. regardless of preceding rule options.
65535 -65535 to 65535 Example byte_jump:4.2007-1748.) 2. dce_stub_data. dce_stub_data.dce. the following normal byte jump arguments will not be allowed: big.-4. byte_test:2. 2280.-4. -10. hex. dce_opnum:0-11. little.dce. \ byte_test:4.{12}(\x00\x00\x00\x00|.{12})/sR".2. and email addresses.256.align. When using the dce argument to a byte jump. byte jump Syntax byte_jump:<convert>.2007-1748. hex.-4. byte_jump:4.byte test and byte jump with dce A DCE/RPC request can specify whether numbers are represented in big or little endian.dce.445.relative. relative. \ classtype:attempted-admin. <offset>[. align][. !=. >.139. relative][.{12})/sR". multiplier <mult_value>] \ [.1024:] \ (msg:"dns R_Dnssrv funcs2 overflow attempt". dce.relative.relative.dce. \ dce_iface:50abc2a4-574d-40b3-9d66-ee4fd5fba076. byte test Syntax byte_test:<convert>.1024:] \ (msg:"dns R_Dnssrv funcs2 overflow attempt". dce.4. These rule options will take as a new argument dce and will work basically the same as the normal byte test/byte jump. Social Security numbers. Example of rule complexity reduction The following two rules using the new rule options replace 64 (set and isset flowbit) rules that are necessary if the new rule options are not used: alert tcp $EXTERNAL_NET any -> $HOME_NET [135.256. but since the DCE/RPC preprocessor will know the endianness of the request. 0. U. \ dce_iface:50abc2a4-574d-40b3-9d66-ee4fd5fba076. reference:cve. string. <offset> [. reference:cve. sid:1000069. A limited regular expression syntax is also included for defining your own PII. 94 .to_server.593.4294967295 -65535 to 65535 Examples byte_test:4.>. When using the dce argument to a byte test. convert operator value offset = = = = 1 | 2 | 4 (only with option "dce") ’<’ | ’=’ | ’>’ | ’&’ | ’ˆ’ 0 . convert offset mult_value adjustment_value = = = = 1 | 2 | 4 (only with option "dce") -65535 to 65535 0 . 35000.14 Sensitive Data Preprocessor The Sensitive Data preprocessor is a Snort module that performs detection and filtering of Personally Identifiable Information (PII).to_server. This information includes credit card numbers. oct and from beginning.{12}(\x00\x00\x00\x00|.post_offset -4. little.) alert udp $EXTERNAL_NET any -> $HOME_NET [135. relative]. flow:established. it will be able to do the correct conversion.relative.align.align. reference:bugtraq.relative.S. string.multiplier 2. dec. \ pcre:"/ˆ.4. dce_opnum:0-11.>. [!]<operator>. post_offet <adjustment_value>]. relative. flow:established. \ byte_test:4. reference:bugtraq. dce. <value>. \ classtype:attempted-admin.23470. \ pcre:"/ˆ.23470. sid:1000068. byte_jump:4. the following normal byte test arguments will not be allowed: big.dce. dce. dec and oct.
Example preprocessor config preprocessor sensitive_data: alert_threshold 25 \ mask_output \ ssn_file ssn_groups_Jan10.Dependencies The Stream5 preprocessor must be enabled for the Sensitive Data preprocessor to work. This is only done on credit card & Social Security numbers. On a monthly basis. A new rule option is provided by the preprocessor: sd_pattern 95 . and Serial (4 digits). These numbers can be updated in Snort by supplying a CSV file with the new maximum Group numbers to use. By default. This option specifies how many need to be detected before alerting. where an organization’s regulations may prevent them from seeing unencrypted numbers. Preprocessor Configuration Sensitive Data configuration is split into two parts: the preprocessor config. ssn file A Social Security number is broken up into 3 sections: Area (3 digits).65535 Required NO NO NO Default alert threshold 25 OFF OFF Option explanations alert threshold The preprocessor will alert when any combination of PII are detected in a session. Group (2 digits). Snort recognizes Social Security numbers issued up through November 2009. mask output This option replaces all but the last 4 digits of a detected PII with ”X”s. This should be set higher than the highest individual count in your ”sd pattern” rules. and the rule options. The preprocessor config starts with: preprocessor sensitive_data: Option syntax Option alert threshold mask output ssn file alert_threshold = Argument <number> NONE <filename> 1 .csv Rule Options Snort rules are used to specify which PII the preprocessor should look for. the Social Security Administration publishes a list of which Group numbers are in use for each Area.
Discover. 96 . example: ”{3}” matches 3 digits. This covers Visa. Custom PII types are defined using a limited regex-style syntax. \} matches { and } \? matches a question mark. Group. <pattern>. Group. Unlike PCRE. and American Express. pattern This is where the pattern of the PII gets specified. ? makes the previous character or escape sequence optional. The following special characters and escape sequences are supported: matches any digit matches any non-digit matches any letter matches any non-letter matches any alphanumeric character matches any non-alphanumeric character used to repeat a character or escape sequence ”num” times.S. count = 1 . example: ” ?” matches an optional space. but the preprocessor will check matches against the list of currently allocated group numbers. There are a few built-in patterns to choose from: credit card The ”credit card” pattern matches 15. This behaves in a greedy manner. and Serial sections. us social This pattern matches against 9-digit U. SSNs have no check digits. If the pattern specified is not one of the above built-in patterns.This rule option specifies what type of PII a rule should detect.and 16-digit credit card numbers. Other characters in the pattern will be matched literally. \\ matches a backslash \{. then it is the definition of a custom PII pattern. and Serial sections. Syntax sd_pattern:<count>. Mastercard. The SSNs are expected to have dashes between the Area. Social Security numbers.S.255 pattern = any string Option Explanations count This dictates how many times a PII pattern must be matched for an alert to be generated. us social nodashes This pattern matches U. Social Security numbers without dashes separating the Area. . dashes. Credit card numbers matched this way have their check digits verified using the Luhn algorithm. or nothing in between groups. The count is tracked across all packets in a session. email This pattern matches against email addresses. \d \D \l \L \w \W {num} ! △NOTE\w in this rule option does NOT match underscores. These numbers may have spaces.
• tos type of service (differentiated services) field: clear this byte. use the following when configuring Snort: . 97 . • NOP all options octets.credit_card. rev:1. If a policy is configured for inline test or passive mode. 2. fields are cleared only if they are non-zero. Also. Alerts when 2 social security numbers (with dashes) appear in a session. it is helpful to normalize packets to help minimize the chances of evasion.) Caveats sd pattern is not compatible with other rule options. phone numbers.2.(\d{3})\d{3}-\d{4}. gid:138. Note that in the following. [rf]. This is automatically disabled if the DAQ can’t inject packets.S. • rf reserved flag: clear this bit on incoming packets. following the format (123)456-7890 Whole rule example: alert tcp $HOME_NET $HIGH_PORTS -> $EXTERNAL_NET $SMTP_PORTS \ (msg:"Credit Card numbers sent over email". sd_pattern: 5. \ sd_pattern:4. • trim truncate packets with excess payload to the datagram length specified in the IP header + the layer 2 header (eg ethernet). There are also many new preprocessor and decoder rules to alert on or drop packets with ”abnormal” encodings. sid:1000./configure --enable-normalizer The normalize preprocessor is activated via the conf as outlined below. but don’t truncate below minimum frame length. [tos].us_social. Rules using sd pattern must use GID 138. IP4 Normalizations IP4 normalizations are enabled with: preprocessor normalize_ip4: [df]. Alerts on 5 U.15 Normalizer When operating Snort in inline mode. metadata:service smtp. To enable the normalizer. Optional normalizations include: • df don’t fragment: clear this bit on incoming packets. normalizations will only be enabled if the selected DAQ supports packet replacement and is operating in inline mode. [trim] Base normalizations enabled with ”preprocessor normalize ip4” include: • TTL normalization if enabled (explained below). Trying to use other rule options with sd pattern will result in an error message. any normalization statements in the policy config are ignored.Examples sd_pattern: 2.
13 } <alt_checksum> ::= { 14. • Clear the reserved bits in the TCP header. \ [opts [allow <allowed_opt>+]] <ecn_type> ::= stream | packet <allowed_opt> ::= \ sack | echo | partial_order | conn_count | alt_checksum | md5 | <num> <sack> ::= { 4. 10 } <conn_count> ::= { 11.IP6 Normalizations IP6 normalizations are enabled with: preprocessor normalize_ip6 Base normalizations enabled with ”preprocessor normalize ip6” include: • Hop limit normalizaton if enabled (explained below). • Clear the urgent pointer if the urgent flag is not set. 5 } <echo> ::= { 6.255) Base normalizations enabled with ”preprocessor normalize tcp” include: • Remove data on SYN. • Clear the urgent pointer and the urgent flag if there is no payload. 98 . • NOP all options octets in hop-by-hop and destination options extension headers. TCP Normalizations TCP normalizations are enabled with: preprocessor normalize_tcp: \ [ips] [urp] \ [ecn <ecn_type>]. 12. 7 } <partial_order> ::= { 9.. 15 } <md5> ::= { 19 } <num> ::= (3. opts if timestamp was negotiated but not present. • Trim data to MSS. • Clear the urgent flag if the urgent pointer is not set. Any segments that can’t be properly reassembled will be dropped. NOP the timestamp octets. timestamp.255) 99 . You can allow options to pass by name or number. window scaling. • opts if timestamp is present but invalid. • Trim data to window. and any explicitly allowed with the allow keyword.. block the packet.. • opts MSS and window scale options are NOP’d if SYN flag is not set. • opts NOP all option bytes other than maximum segment size. as follows: config min_ttl: <min_ttl> config new_ttl: <new_ttl> <min_ttl> ::= (1. • Remove any data from RST packet. • urp urgent pointer: don’t adjust the urgent pointer if it is greater than payload length.. • opts clear TS ECR if ACK flag is not set.• Set the urgent pointer to the payload length if it is greater than the payload length. or valid but not negotiated. • opts trim payload length to MSS if longer. Should also enable require 3whs. • ecn packet clear ECN flags on a per packet basis (regardless of negotiation). • ecn stream clear ECN flags if usage wasn’t negotiated. Optional normalizations include: • ips ensure consistency in retransmitted data (also forces reassembly policy to ”first”). • Clear any option padding bytes.255) <new_ttl> ::= (<min_ttl>+1.
When TTL normalization is turned on the new ttl is set to 5 by default.6: preprocessor stream5_tcp: min_ttl <#> By default min ttl = 1 (TTL normalization is disabled). For example. define the path to where the rules are located and uncomment the include lines in snort.3.conf that reference the rules files. To change the rule type or action of a decoder/preprocessor rule. 2. the TTL will be set to new ttl./configure --enable-decoder-preprocessor-rules The decoder and preprocessor rules are located in the preproc rules/ directory in the top level source tree.1 Configuring The following options to configure will enable decoder and preprocessor rules: $ .8. 2. these options will take precedence over the event type of the rule. To enable these rules in snort.3 Decoder and Preprocessor Rules Decoder and preprocessor rules allow one to enable and disable decoder and preprocessor events on a rule by rule basis.conf or the decoder or preprocessor rule type is drop. then if a packet is received with a TTL ¡ min ttl. Decoder config options will still determine whether or not to generate decoder events. config enable decode drops. and have the names decoder.. decoder events will not be generated regardless of whether or not there are corresponding rules for the event.. The gen-msg.If new ttl ¿ min ttl. These files are updated as new decoder and preprocessor events are added to Snort. e. just comment it with a # or remove the rule completely from the file (commenting is recommended). They also allow one to specify the rule type or action of a decoder or preprocessor event on a rule by rule basis. if config disable decode alerts is in snort. the drop cases only apply if Snort is running inline. var PREPROC_RULE_PATH /path/to/preproc_rules . See doc/README. just replace alert with the desired rule type. Any one of the following rule types can be used: alert log pass drop sdrop reject For example one can change: 100 . A packet will be dropped if either a decoder config drop option is in snort.rules To disable any rule.decode for config options that control decoder events.conf. Of course.rules respectively.g.conf. Also note that if the decoder is configured to enable drops. Note that this configuration item was deprecated in 2.rules and preprocessor.rules include $PREPROC_RULE_PATH/decoder. include $PREPROC_RULE_PATH/preprocessor.map under etc directory is also updated with new decoder and preprocessor rules.
alert ( msg: "DECODE_NOT_IPV4_DGRAM". 2. This option applies to rules not specified and the default behavior is to alert.) to drop ( msg: "DECODE_NOT_IPV4_DGRAM". sid: 1.conf. rev: 1. otherwise they will be loaded. rev: 1.rules.3. classtype:protocol-command-decode. \ metadata: rule-type decode . classtype:protocol-command-decode. sid: 1.gre and the various preprocessor READMEs for descriptions of the rules in decoder. gid: 116.) to drop (as well as alert on) packets where the Ethernet protocol is IPv4 but version field in IPv4 header has a value other than 4. \ metadata: rule-type decode .rules and preprocessor.4 Event Processing Snort provides a variety of mechanisms to tune event processing to suit your needs: 101 .decode. README. you also have to remove the decoder and preprocessor rules and any reference to them from snort. The generator ids ( gid ) for different preprocessors and the decoder are as follows: 2.2 Reverting to original behavior If you have configured snort to use decoder and preprocessor rules.conf will make Snort revert to the old behavior: config autogenerate_preprocessor_decoder_rules Note that if you want to revert to the old behavior. See README. the following config option in snort. gid: 116.
• Event Suppression You can completely suppress the logging of unintersting events.allow a maximum of 100 successful simultaneous connections from any one IP address. seconds <s>. and the first applicable action is taken. \ count 100. Multiple rate filters can be defined on the same rule.all are required except apply to. timeout 10 Example 2 . sig_id 1.4. \ track <by_src|by_dst|by_rule>. seconds 0.allow a maximum of 100 connection attempts per second from any one IP address. • Event Filters You can use event filters to reduce the number of logged events for noisy rules. \ new_action drop. \ count <c>. • Rate Filters You can use rate filters to change a rule action when the number or rate of events indicates a possible attack. seconds 1. and block further connections from that IP address for 10 seconds: rate_filter \ gen_id 135. \ count 100. \ timeout <seconds> \ [.7. and block further connection attempts from that IP address for 10 seconds: rate_filter \ gen_id 135. \ track by_src. timeout 10 102 . in which case they are evaluated in the order they appear in the configuration file. \ new_action alert|drop|pass|log|sdrop|reject. \ track by_src. 2.10. which is optional. This can be tuned to significantly reduce false alarms.• Detection Filters You can use detection filters to specify a threshold that must be exceeded before a rule generates an event. This is covered in section 3. apply_to <ip-list>] The options are described in the table below . sig_id <sid>. \ new_action drop. sig_id 2. Examples Example 1 . Format Rate filters are used as standalone configurations (outside of a rule) and have the following format: rate_filter \ gen_id <gid>.1 Rate Filtering rate filter provides rate based attack prevention by allowing users to configure a new action to take for a specified time when a given rate is exceeded.
sdrop and reject are conditionally compiled with GIDS. \ type <limit|threshold|both>. revert to the original rule action after t seconds. reject. even if the rate falls below the configured limit.4. There are 3 types of event filters: • limit Alerts on the 1st m events during the time interval. or they are aggregated at rule level. seconds <s> threshold \ gen_id <gid>. then ignores events for the rest of the time interval. the time period over which count is accrued.Option track by src | by dst | by rule count c seconds s new action alert | drop | pass | log | sdrop | reject timeout t apply to <ip-list> Description rate is tracked either by source IP address. and sdrop can be used only when snort is used in inline mode. new action replaces rule action for t seconds. for each unique destination IP address. An event filter may be used to manage number of alerts after the rule action is enabled by rate filter. Format event_filter \ gen_id <gid>. • threshold Alerts every m times we see this event during the time interval. then ignores any additional events during the time interval. 0 seconds only applies to internal rules (gen id 135) and other use will produce a fatal error by Snort. For example. restrict the configuration to only to source or destination IP address (indicated by track parameter) determined by <ip-list>. destination IP address. For rules related to Stream5 sessions. sig_id <sid>. 0 seconds means count is a total count instead of a specific rate. \ track <by_src|by_dst>. • both Alerts once per time interval after seeing m occurrences of the event. or by rule. rate filter may be used to detect if the number of connections to a specific server exceed a specific count. Note that events are generated during the timeout period. c must be nonzero value. \ 103 . \ count <c>. track by rule and apply to may not be used together. If t is 0. sig_id <sid>. drop. the maximum number of rule matches in s seconds before the rate filter limit to is exceeded. then rule action is never reverted back. \ type <limit|threshold|both>. source and destination means client and server respectively. This means the match statistics are maintained for each unique source IP address. This can be tuned to significantly reduce false alarms. \ track <by_src|by_dst>. track by rule and apply to may not be used together. 2.2 Event Filtering Event filtering can be used to reduce the number of logged alerts for noisy rules by limiting the number of times a particular event is logged during a specified time interval.
seconds 60 Limit logging to every 3rd event: event_filter \ gen_id 1. s must be nonzero value. \ type limit. sig id 0 specifies a ”global” filter because it applies to all sig ids for the given gen id. This means count is maintained for each unique source IP addresses. (gen id 0. track by_src. or destination IP address. number of rule matching in s seconds that will cause event filter limit to be exceeded.count <c>. Type both alerts once per time interval after seeing m occurrences of the event. time period over which count is accrued. sig id != 0 is not allowed). count 1. sig_id 1852. ! △NOTE can be used to suppress excessive rate filter alerts. c must be nonzero value. Type threshold alerts every m times we see this event during the time interval. track by_src. Such events indicate a change of state that are significant to the user monitoring the network. If more than one event filter is Only one event applied to a specific gen id. sig id. then the filter applies to all rules. If gen id is also 0. Standard filtering tests are applied first. \ type threshold. Examples Limit logging to 1 event per 60 seconds: event_filter \ gen_id 1. track by src|by dst count c seconds s ! △NOTE filter may be defined for a given gen id. threshold is deprecated and will not be supported in future releases. sig id pair. Ports or anything else are not tracked. gen id 0. type limit alerts on the 1st m events during the time interval. however.all are required. then ignores any additional events during the time interval. Global event filters do not override what’s in a signature or a more specific stand-alone event filter. Thresholds in a rule (deprecated) will override a global event filter. Option gen id <gid> sig id <sid> type limit|threshold|both Description Specify the generator ID of an associated rule. the first new action event event filters of the timeout period is never suppressed. \ count 3. then ignores events for the rest of the time interval. if they do not block an event from being logged. event filters with sig id 0 are considered ”global” because they apply to all rules with the given gen id. Specify the signature ID of an associated rule. sig id 0 can be used to specify a ”global” threshold that applies to all rules. the global filtering test is applied. sig_id 1851. or for each unique destination IP addresses. Snort will terminate with an error while reading the configuration information. Both formats are equivalent and support the options described below . seconds 60 104 \ . rate is tracked either by source IP address. seconds <s> threshold is an alias for event filter.
and IP addresses via an IP list . seconds 60 Limit to logging 1 event per 60 seconds per IP triggering each rule (rule gen id is 1): event_filter \ gen_id 1. sig_id 0.Limit logging to just 1 event per 60 seconds. but only if we exceed 30 events in 60 seconds: event_filter \ gen_id 1. track by_src. SIDs. sig_id 1853. \ type both. seconds 60 Limit to logging 1 event per 60 seconds per IP.map for details on gen ids. \ count 1. Suppression are standalone configurations that reference generators.. triggering each rule for each event generator: event_filter \ gen_id 0. You may also combine one event filter and several suppressions to the same non-zero SID. \ count 1. track by_src. sig_id <sid>. Format The suppress configuration has two forms: suppress \ gen_id <gid>. sig_id <sid>. You may apply multiple suppressions to a non-zero SID. \ count 30. Suppression uses an IP list to select specific networks and users for suppression. \ type limit. track by_src. event filters are handled as part of the output system. This allows a rule to be completely suppressed. ip <ip-list> 105 . sig_id 0. Read genmsg. \ track <by_src|by_dst>. \ type limit.3 Event Suppression Event suppression stops specified events from firing without removing the rule from the rule base. seconds 60 Events in Snort are generated in the usual way.4. or suppressed when the causative traffic is going to or coming from a specific IP or group of IP addresses. \ suppress \ gen_id <gid>.
if the event queue has a max size of 8. track by_src.1. We currently have two different methods: • priority . 3.1. ip must be provided as well. ip 10. sig_id 1852.Option gen id <gid> sig id <sid> track by src|by dst ip <list> Description Specify the generator ID of an associated rule. 2. gen id 0. Restrict the suppression to only source or destination IP addresses (indicated by track parameter) determined by ¡list¿. The default value is 8. ip 10.54 Suppress this event to this CIDR block: suppress gen_id 1. 106 . Suppress by source IP address or destination IP address. For example.4 Event Logging Snort supports logging multiple events per packet/stream that are prioritized with different insertion methods. log This determines the number of events to log for a given packet or stream. but if present. ip must be provided as well. Examples Suppress this event completely: suppress gen_id 1.0/24 2. If track is provided. such as max content length or event ordering using the event queue. Specify the signature ID of an associated rule. This is optional. max queue This determines the maximum size of the event queue. sig id 0 specifies a ”global” filter because it applies to all sig ids for the given gen id. sig_id 1852.4. The default value is 3. only 8 events will be stored for a single packet or stream. 1.The highest priority (1 being the highest) events are ordered first. sig_id 1852: Suppress this event from this IP: suppress gen_id 1.’. track by_dst.1. sig id 0 can be used to specify a ”global” threshold that applies to all rules.1. You can’t log more than the max event number that was specified.
conf and Snort will print statistics on the worst (or all) performers on exit. The filenames will have timestamps appended to them.• content length .5. The method in which events are ordered does not affect rule types such as pass.Rules are ordered before decode or preprocessor alerts. When a file name is provided in profile rules or profile preprocs.5 Performance Profiling Snort can provide statistics on rule and preprocessor performance. the statistics will be saved in these files. If append is not specified) 107 . but change event order: config event_queue: order_events priority Use the default event queue values but change the number of logged events: config event_queue: log 2 2. These files will be found in the logging. you must build snort with the --enable-perfprofiling option to the configure script. 2.1 Rule Profiling Format config profile_rules: \ print [all | <num>]. The default value is content length. To use this feature. alert. and rules that have a longer content are ordered before rules with shorter contents. etc. \ sort <sort_option> \ [. Each require only a simple config option to snort. a new file will be created each time Snort is run.
0 107822 53911.txt config profile rules: filename rules stats.txt with timestamp in filename config profile rules: Output Snort will print a table much like the following at exit.0 Figure 2. and append to file rules stats.txt each time config profile rules: filename performance.0 Avg/Match Avg/Nonmatch ========= ============ 385698.0 92458 46229. sort avg ticks • Print all rules.0 0.1: Rule Profiling Example Output Examples • Print all rules.0 90054 45027. sorted by number of checks config profile rules: print all. based on total time config profile rules: print 100.0 53911. 46229.0 45027. filename perf.txt append • Print the top 10 rules.txt .0 0. based on highest average time config profile rules: print 10. sort checks • Print top 100 rules. sort total ticks • Print with default options 0. sort by avg ticks (default configuration if option is turned on) config profile rules • Print all rules. save results to performance. will be high for rules that have no options) • Alerts (number of alerts generated from this rule) • CPU Ticks • Avg Ticks per Check • Avg Ticks per Match 108 print 4.txt append • Print top 20 rules.0 0. sort total ticks print 20. sort by avg ticks. save results to perf. 112
fastpath-expensive-packets. debug-pkt config ppm: \ max-rule-time 50. These rules were used to generate the sample output that follows. threshold 5 If fastpath-expensive-packets or suspend-expensive-rules is not used. threshold 5. \ suspend-timeout 300. then no action is taken other than to increment the count of the number of packets that should be fastpath’d or the rules that should be suspended. A summary of this information is printed out when snort exits. \ pkt-log. config ppm: \ max-pkt-time 50. suspend-expensive-rules. Example 2: The following suspends rules and aborts packet inspection. 113 .
3659 usecs PPM: Process-EndPkt[62] PPM: PPM: PPM: PPM: Pkt-Event Pkt[63] used=56.0438 usecs. it is recommended that you tune your thresholding to operate optimally when your system is under load.Sample Snort Run-time Output .2675 usecs Implementation Details • Enforcement of packet and rule processing times is done after processing each rule. Hence the reason this is considered a best effort approach. • Since this implementation depends on hardware based high performance frequency counters.21764 usecs PPM: Process-EndPkt[64] .394 usecs Process-EndPkt[63] PPM: Process-BeginPkt[64] caplen=60 PPM: Pkt[64] Used= 8. 1 nc-rules tested. This was a conscious design decision because when a system is loaded.6. Therefore.... Latency control is not enforced after each preprocessor. Sample Snort Exit Output Packet Performance Summary: max packet time : 50 usecs packet events : 1 avg pkt time : 0. 0 rules. The output modules are run when the alert or logging subsystems of Snort are called.6 Output Modules Output modules are new as of version 1. Process-BeginPkt[63] caplen=60 Pkt[63] Used= 8.633125 usecs Rule Performance Summary: max rule time : 50 usecs rule events : 0 avg nc-rule time : 0. They allow Snort to be much more flexible in the formatting and presentation of output to its users.15385 usecs PPM: Process-EndPkt[61] PPM: Process-BeginPkt[62] caplen=342 PPM: Pkt[62] Used= 65. not processor usage by Snort. not just the processor time the Snort application receives. packet fastpathed. Due to the granularity of the timing measurements any individual packet may exceed the user specified packet or rule processing time limit. • Time checks are made based on the total system time. PPM: Process-BeginPkt[61] caplen=60 PPM: Pkt[61] Used= 8.. Therefore this implementation cannot implement a precise latency guarantee with strict timing guarantees. the latency for a packet is based on the total system time. after 114 . • This implementation is software based and does not use an interrupt driven timing mechanism and is therefore subject to the granularity of the software based timing tests. latency thresholding is presently only available on Intel and PPC platforms. 2.
Multiple output plugins may be specified in the Snort configuration file.the preprocessors and detection engine.6. The format of the directives in the config file is very similar to that of the preprocessors. they are stacked and called in sequence when an event occurs. alert) are specified. As with the standard logging and alerting systems. This module also allows the user to specify the logging facility and priority within the Snort config file. 115 .1 alert syslog This module sends alerts to the syslog facility (much like the -s command line switch). output plugins send their data to /var/log/snort by default or to a user directed directory (using the -l command line switch). When multiple plugins of the same type (log. giving users greater flexibility in logging alerts. Output modules are loaded at runtime by specifying the output keyword in the config file: output <name>: <options> output alert_syslog: log_auth log_alert 2.
0..1.6.fast 116 .] \ <facility> <priority> <options> Example output alert_syslog: host=10. • limit: an optional limit on file size which defaults to 128 MB. You may specify ”stdout” for terminal output.1. only brief single-line entries are logged.Options • log cons • log ndelay • log perror • log pid Format alert_syslog: \ <facility> <priority> <options> ! △NOTE As WIN32 does not run syslog servers locally by default.1.2 alert fast This will print Snort alerts in a quick one-line format to a specified output file.13 for more information. The default host is 127.0. The name may include an absolute or relative path. The minimum is 1 KB. <facility> <priority> <options> 2. Example output alert_fast: alert. a hostname and port can be passed as options. • packet: this option will cause multiline entries with full packet headers to be logged. The default name is ¡logdir¿/alert. By default. The default port is 514.1:514.6. output alert_syslog: \ [host=<hostname[:<port>]. See 2.
The alerts will be written in the default logging directory (/var/log/snort) or in the logging directory specified at the command line. • limit: an optional limit on file size which defaults to 128 MB.4 alert unixsock Sets up a UNIX domain socket and sends alert reports to it. 117 . The minimum is 1 KB. Example output alert_full: alert. Inside the logging directory.2. The name may include an absolute or relative path.full 2. The creation of these files slows Snort down considerably.6. The name may include an absolute or relative path. the aggregate size is used to test the rollover condition.6. The default name is ¡logdir¿/snort.6. See 2. Format alert_unixsock Example output alert_unixsock 2. a directory will be created per IP. This is useful for performing post-process analysis on collected traffic with the vast number of tools that are available for examining tcpdump-formatted files. This is currently an experimental interface. • limit: an optional limit on file size which defaults to 128 MB.3 alert full This will print Snort alert messages with full packet headers. External programs/processes can listen in on this socket and receive Snort alert and packet data in real time. The default name is ¡logdir¿/alert.6.log. This output method is discouraged for all but the lightest traffic situations. Format output log_tcpdump: [<filename> [<limit>]] <limit> ::= <number>[(’G’|’M’|K’)] • filename: the name of the log file.6. A UNIX timestamp is appended to the filename. When a sequence of packets is to be logged. You may specify ”stdout” for terminal output. These files will be decoded packet dumps of the packets that triggered the alerts.13 for more information. Format output alert_full: [<filename> [<limit>]] <limit> ::= <number>[(’G’|’M’|K’)] • filename: the name of the log file. See 2.5 log tcpdump The log tcpdump module logs packets to a tcpdump-formatted file.13 for more information.
Database name user . then data for IP and TCP options will still be represented as hex because it does not make any sense for that data to be ASCII. dbname . More information on installing and configuring this module can be found on the [91]incident.Log all details of a packet that caused an alert (including IP/TCP options and the payload) 118 . Format database: <log | alert>. it will connect using a local UNIX domain socket. Parameters are specified with the format parameter = argument.’. If you choose this option. If you do not specify a name.Because the packet payload and option data is binary.∼1. If a non-zero-length string is specified.Example output log_tcpdump: snort.Specify your own name for this Snort sensor. <database type>.very good Human readability .Password used if the database demands password authentication sensor name . Non-ASCII Data is represented as a ‘. see Figure 2.Represent binary data as a hex string.not readable unless you are a true geek. requires post processing base64 . You can choose from the following options. Without a host name. or socket filename extension for UNIX-domain connections. there is no one simple and portable way to store it in a database. This is the only option where you will actually lose data. Each has its own advantages and disadvantages: hex (default) .3 for example usage.log 2.6. So i leave the encoding option to you.Database username for authentication password . one will be generated automatically encoding .Port number to connect to at the server host.org web page.very good detail .Represent binary data as a base64 string.very good for searching for a text string impossible if you want to search for binary human readability .not readable requires post processing ascii . Storage requirements .How much detailed data do you want to store? The options are: full (default) . Storage requirements .2x the size of the binary Searchability .Represent binary data as an ASCII string.3x the size of the binary Searchability . <parameter list> The following parameters are available: host . TCP/IP communication is used. Storage requirements . port .6 database This module from Jed Pickel sends Snort data to a variety of SQL databases.<.>) Searchability . Blobs are not used because they are not portable across databases.Host to connect to.slightly larger than the binary because some characters are escaped (&. The arguments to this plugin are the name of the database to be logged to and a parameter list.impossible without post processing Human readability .
6. the plugin will be called on the log output chain. See section 3. destination ip. but this is still the best choice for some applications. and protocol) Furthermore. ! △NOTE The database output plugin does not have the ability to handle alerts that are generated by using the tag keyword. postgresql. source ip. There are two logging types available. destination port. The default name is ¡logdir¿/alert. There are five database types available in the current version of the plugin. source port..3: Database Output Plugin Configuration fast . – timestamp – sig generator – sig id – sig rev – msg – proto – src – srcport – dst 119 . Setting the type to log attaches the database logging functionality to the log facility within the program. and odbc. The following fields are logged: timestamp. the output is in the order of the formatting options listed..Log only a minimum amount of data.5 for more details.<field>)* <field> ::= "dst"|"src"|"ttl" . dbname=snort user=snort host=localhost password=xyz Figure 2. Set the type to match the database you are using. <limit> ::= <number>[(’G’|’M’|K’)] • filename: the name of the log file. If you set the type to log. The output fields and their order may be customized. You severely limit the potential of some analysis applications if you choose this option.csv. The name may include an absolute or relative path. tcp flags. log and alert.output database: \ log. • format: The list of formatting options is below. Format output alert_csv: [<filename> [<format> [<limit>]]] <format> ::= "default"|<list> <list> ::= <field>(. signature.7 csv The csv output plugin allows alert data to be written in a format easily importable to a database. These are mssql. there is a logging method and database type that must be defined. If the formatting option is ”default”. Setting the type to alert attaches the plugin to the alert output chain within the program. mysql. mysql. 2. You may specify ”stdout” for terminal output. oracle.7.
csv timestamp. protocol. Format output alert_unified: <base file name> [. The unified output plugin logs events in binary format.6. The log file contains the detailed packet information (a packet dump with the associated event ID). The alert file contains the high-level details of an event (eg: IPs. The minimum is 1 KB. The name unified is a misnomer.csv default output alert_csv: /var/log/alert. port. Both file types are written in a binary format described in spo unified. <limit <file size limit in MB>] 120 . an alert file. and a log file.8 unified The unified output plugin is designed to be the fastest possible method of logging Snort events. message id). Example output alert_csv: /var/log/alert. ! △NOTE Files have the file creation time (in Unix Epoch format) appended to each file when it is created.h. as the unified output plugin creates two different files. msg 2. allowing another programs to handle complex logging mechanisms that would otherwise diminish the performance of Snort.13 for more information.–.6. See 2. <limit <file size limit in MB>] output log_unified: <base file name> [.
See section 2. The alert prelude output plugin is used to log to a Prelude database. mpls_event_types] Example output output output output alert_unified2: filename snort.log. limit 128 2. nostamp unified2: filename merged. nostamp. Packet logging includes a capture of the entire packet and is specified with log unified2.10 alert prelude ! △NOTE support to use alert prelude is not built in by default. Likewise. unified 2 files have the file creation time (in Unix Epoch format) appended to each file when it is created. Unified2 can work in one of three modes. limit 128. but a slightly different logging format. nostamp] [. limit 128.alert. Use option mpls event types to enable this. nostamp] [. nostamp unified2: filename merged.log. limit 128. To include both logging styles in a single. ! △NOTE By default. mpls_event_types] output log_unified2: \ filename <base filename> [. limit 128.alert.6. <limit <size in MB>] [./configure. then MPLS labels will be not be included in unified2 events. unified file. <limit <size in MB>] [.or Format output alert_prelude: \ 121 .8 on unified logging for more information. snort must be built with the –enable-prelude argument passed to . nostamp log_unified2: filename snort. or true unified logging.6.log. see. simply specify unified2. alert logging will only log events and is specified with alert unified2. limit 128 output log_unified: snort.Example output alert_unified: snort.9 unified 2 The unified2 output plugin is a replacement for the unified output plugin. Format output alert_unified2: \ filename <base filename> [. <limit <size in MB>] [. For more information on Prelude.6.log. It has the same performance characteristics. packet logging. To use alert prelude.prelude-ids. When MPLS support is turned on. MPLS labels can be included in unified2 events. If option mpls event types is not used. alert logging. mpls_event_types 2. nostamp] output unified2: \ filename <base file name> [.
For more information on Aruba Networks access control.com/.2. Format output log_null Example output log_null # like using snort -n ruletype info { type alert output alert_fast: info.arubanetworks. secrettype . To use alert aruba action.Aruba mobility controller address. This is equivalent to using the -n command line option but it is able to work within a ruletype. ”md5” or ”cleartext”. Communicates with an Aruba Networks wireless mobility controller to change the status of authenticated users.12 alert aruba action ! △NOTE Support to use alert aruba action is not built in by default.8.6.alert output log_null } 2.profile=<name of prelude profile> \ [ info=<priority number for info priority alerts>] \ [ low=<priority number for low priority alerts>] \ [ medium=<priority number for medium priority alerts>] Example output alert_prelude: profile=snort info=4 low=3 medium=2 2. one of ”sha1”. snort must be built with the –enable-aruba argument passed to . Format output alert_aruba_action: \ <controller address> <secrettype> <secret> <action> The following parameters are required: controller address . see. This allows Snort to take action against users on the Aruba controller to control their network privilege levels. 122 .11 log null Sometimes it is useful to be able to create rules that will alert to certain types of traffic but will not cause packet log entries.6./configure.Secret type. In Snort 1. the log null plugin was introduced.
alert full.Blacklist the station by disabling all radio communication.3. Snort associates a given packet with its attribute data from the table. unified and unified2 also may be given limits.9. Those limits are described in the respective sections. For rule evaluation. s Example output alert_aruba_action: \ 10. Snort must be configured with the –enable-targetbased flag. 2. represented as a sha1 or md5 hash. service information is used instead of the ports when the protocol metadata in the rule matches the service corresponding to the traffic. or a cleartext password.13 Log Limits This section pertains to logs produced by alert fast. alert csv. action .8.6 cleartext foobar setrole:quarantine_role 2. the rule relies on the port information. and IP-Frag policy (see section 2. and log tcpdump. The table is re-read during run time upon receipt of signal number 30. setrole:rolename . blacklist .2. If the rule doesn’t have protocol metadata.Action to apply to the source IP address of the traffic generating an alert.7 Host Attribute Table Starting with version 2.1.Authentication secret configured on the Aruba mobility controller with the ”aaa xml-api client” configuration command. if applicable. When a configured limit is reached.. the current log is closed and a new log is opened with a UNIX timestamp appended to the configured log name. which is loaded at startup. 2.Change the user´ role to the specified rolename. This information is stored in an attribute table. or the traffic doesn’t have any matching service information.secret . Snort has the capability to use information from an outside source to determine both the protocol for use with Snort rules. ! △NOTE To use a host attribute table.1) and TCP Stream reassembly policies (see section 2.2.7. Rollover works correctly if snort is stopped/restarted.6.2).1 Configuration Format attribute_table filename <path to file> 123 .
a mapping section. The mapping section is optional.2 Attribute Table File Format The attribute table uses an XML format and consists of two sections.9p1</ATTRIBUTE_VALUE> <CONFIDENCE>93</CONFIDENCE> 124 .7. <SNORT_ATTRIBUTES> <ATTRIBUTE_MAP> <ENTRY> <ID>1</ID> <VALUE>Linux</VALUE> </ENTRY> <ENTRY> <ID>2</ID> <VALUE>ssh</VALUE> </ENTRY> </ATTRIBUTE_MAP> <ATTRIBUTE_TABLE> <HOST> <IP>192. An example of the file format is shown below.2. used to reduce the size of the file for common data elements. and the host attribute section.
the stream and IP frag information are both used. only the IP protocol (tcp.8. They will be used in a future release. and protocol (http. udp. port. The application and version for a given service attribute. A DTD for verification of the Host Attribute Table XML file is provided with the snort packages. 125 . That field is not currently used by Snort.0</ATTRIBUTE_VALUE> <CONFIDENCE>89</CONFIDENCE> </VERSION> </APPLICATION> </CLIENT> </CLIENTS> </HOST> </ATTRIBUTE_TABLE> </SNORT_ATTRIBUTES> ! △NOTE2. The confidence metric may be used to indicate the validity of a given service or client application and its respective elements. ssh. for a given host entry.<> <VERSION> <ATTRIBUTE_VALUE>6. etc) are used. but may be in future releases.1. Of the service With Snort attributes. and any client attributes are ignored. etc).
7.) • Alert: Rule Has Multiple Service Metadata. Connection Service Matches The following rule will be inspected and alert on traffic to host 192.6 is described. if. Below is a list of the common services used by Snort’s application layer preprocessors and Snort rules (see below). etc) make use of the SERVICE information for connections destined to that host on that port.1 and 2. Conversely. sid:10000001.234 port 2300 as telnet. FTP. sid:10000002.established.1.2. a host running Red Hat 2. For example.3 Attribute Table Example In the example above. • Application Layer Preprocessors The application layer preprocessors (HTTP. SMTP. Snort uses the service rather than the port. HTTP Inspect is configured to inspect traffic on port 2300.. for example.234 port 2300 because it is identified as telnet. TCP port 22 is ssh (running Open SSH). flow:to_server. metadata: service telnet.1. The IP stack fragmentation and stream reassembly is mimicked by the ”linux” configuration (see sections 2.168.168. service smtp. If there are rules that use the service and other rules that do not but the port matches.2.) 126 .2. The following few scenarios identify whether a rule will be inspected or not.168. • Alert: Rule Has Service Metadata.234. Telnet.2).1. alert tcp any any -> any 23 (msg:"Telnet traffic". This host has an IP address of 192. even if the telnet portion of the FTP/Telnet preprocessor is only configured to inspect port 23.168.234 port 2300 because it is identified as telnet. alert tcp any any -> any 23 (msg:"Telnet traffic". flow:to_server.established. On that host. Snort will ONLY inspect the rules that have the service that matches the connection.168. When both service metadata is present in the rule and in the connection. HTTP Inspect will NOT process the packets on a connection to 192. metadata: service telnet. Connection Service Matches One of them The following rule will be inspected and alert on traffic to host 192 Attribute Table Affect on rules Similar to the application layer preprocessors. and TCP port 2300 is telnet. Snort will inspect packets for a connection to 192.234 port 2300 because it is identified as telnet. rules configured for specific ports that have a service metadata will be processed based on the service identified by the attribute table.
metadata: service telnet.234 port 2300 because the service is identified as telnet and there are other rules with that service.168.established. sid:10000005.234 port 2300 because the port matches. specify directory. alert tcp any any -> any 2300 (msg:"Port 2300 traffic".1 Format <directive> <parameters> 2.conf or via command-line options. flow:to_server. sid:10000006. Packet has service + other rules with service The first rule will NOT be inspected and NOT alert on traffic to host 192. 2. alert tcp any any -> any 2300 (msg:"SSH traffic". Port Matches The following rule will NOT be inspected and NOT alert on traffic to host 192.established. metadata: service ssh. flow:to_server. followed by the full or relative path to the shared library. flow:to_server.established. followed by the full or relative path to a directory of preprocessor shared libraries.2 Directives Syntax dynamicpreprocessor [ file <shared library path> | directory <directory of shared libraries> ] Description Tells snort to load the dynamic preprocessor shared library (if file is used) or all dynamic preprocessor shared libraries (if directory is used).) alert tcp any any -> any 2300 (msg:"Port 2300 traffic". sid:10000007. (Same effect as --dynamic-preprocessor-lib or --dynamic-preprocessor-lib-dir options).) 2. alert tcp any any -> any 23 (msg:"Port 23 traffic". Specify file.168.1. sid:10000004. flow:to_server. Port Matches The following rule will be inspected and alert on traffic to host 192.) • Alert: Rule Has No Service Metadata.234 port 2300 because that traffic is identified as telnet. flow:to_server. ! △NOTE To disable use of dynamic modules.1.• No Alert: Rule Has Service Metadata. See chapter 4 for more 127 information on dynamic preprocessor libraries. . They can be loaded via directives in snort.) • No Alert: Rule Has No Service Metadata.8. Port Does Not Match The following rule will NOT be inspected and NOT alert on traffic to host 192.established. sid:10000003.168.168.established.234 port 2300 because the port does not match. Snort must be configured with the --disable-dynamicplugin flag.6. alert tcp any any -> any 2300 (msg:"Port 2300 traffic".8.8 Dynamic Modules Dynamically loadable modules were introduced with Snort 2. Connection Service Does Not Match.1.1.) • Alert: Rule Has No Service Metadata. but the service is ssh. Or.
specify directory. There is also an ancillary option that determines how Snort should behave if any non-reloadable options are changed (see section 2.2 Reloading a configuration First modify your snort. See chapter 4 for more information on dynamic detection rules libraries. followed by the full or relative path to a directory of preprocessor shared libraries. When a swappable configuration object is ready for use.9. specify directory. Note that for some preprocessors. Or. Specify file. add --disable-reload-error-restart in addition to --enable-reload to configure when compiling.9. 2. add --enable-reload to configure when compiling. followed by the full or relative path to a directory of detection rules shared libraries. $ kill -SIGHUP <snort pid> ! △NOTE If reload support is not enabled.. e. A separate thread will parse and create a swappable configuration object while the main Snort packet processing thread continues inspecting traffic under the current configuration). (Same effect as --dynamic-detection-lib or --dynamic-detection-lib-dir options). 2. See chapter 4 for more information on dynamic engine libraries. 2. send Snort a SIGHUP signal.1 Enabling support To enable support for reloading a configuration. Then. Or.conf (the file passed to the -c option on the command line).3 below).9. Snort will restart (as it always has) upon receipt of a SIGHUP. (Same effect as --dynamic-engine-lib or --dynamic-preprocessor-lib-dir options). existing session data will continue to use the configuration under which they were created in order to continue with proper state for that session. followed by the full or relative path to the shared library. however. To disable this behavior and have Snort exit instead of restart. ! △NOTE This functionality is not currently supported in Windows. the main Snort packet processing thread will swap in the new configuration to use and will continue processing under the new configuration.g. This option is enabled by default and the behavior is for Snort to restart if any nonreloadable options are added/modified/removed. use the new configuration. to initiate a reload. Specify file. 128 . Tells snort to load the dynamic detection rules shared library (if file is used) or all dynamic detection rules shared libraries (if directory is used).
$ snort -c snort.conf -T 2. only some of the parameters to a config option or preprocessor configuration are not reloadable. Those parameters are listed below the relevant config option or preprocessor.9.g. Changes to the following options are not reloadable: attribute_table config alertfile config asn1 config chroot. config ppm: max-rule-time <int> rule-log config profile_rules 129 . etc. • Adding/modifying/removing preprocessor configurations are reloadable (except as noted below). • Any changes to output will require a restart. Modifying any of these options will cause Snort to restart (as a SIGHUP previously did) or exit (if --disable-reload-error-restart was used to configure Snort). e. startup memory allocations. any new/modified/removed shared objects will require a restart. i. so you should test your new configuration An invalid before issuing a reload. Reloadable configuration options of note: • Adding/modifying/removing text rules and variables are reloadable.! △NOTEconfiguration will still result in Snort fatal erroring. dynamicengine and dynamicpreprocessor are not reloadable.
A maximum of 512 individual IPv4 or IPv6 addresses or CIDRs can be specified 2. Each unique snort configuration file will create a new configuration instance within snort. Negative vland Ids and alphanumeric are not supported.conf> net <ipList> path to snort. using the following configuration line: config binding: <path_to_snort.conf> vlan <vlanIdList> config binding: <path_to_snort. 130 .1 Creating Multiple Configurations Default configuration for snort is specified using the existing -c option. Valid vlanId is any number in 0-4095 range. ipList . The format for ranges is two vlanId separated by a ”-”. Subnets can be CIDR blocks for IPV6 or IPv4.10. vlanIdList .Refers to the comma seperated list of vlandIds and vlanId ranges.conf for specific configuration. A default configuration binds multiple vlans or networks to non-default configurations. 2..conf .Refers to the absolute or relative path to the snort.Refers to ip subnets. Spaces are allowed within ranges.
If not defined in a configuration. those variables must be defined in that configuration. they are included as valid in terms of configuring Snort. 131 .e. Even though 2. the default values of the option (not the default configuration values) take effect. A rule shares all parts of the rule options. Configurations can be applied based on either Vlans or Vlan and Subnets Subnets not both. If the rules in a configuration use variables. and post-detection options.! △NOTE can not be used in the same line. Variables Variables defined using ”var”.2 Configuration Specific Elements Config Options Generally config options defined within the default configuration are global by default i. Parts of the rule header can be specified differently across configurations. The following config options are specific to each configuration. ”portvar” and ”ipvar” are specific to configurations. their value applies to all other configurations. policy_id policy_mode policy_version. including the general options.10. ! △NOTE Vlan Ids 0 and 4095 are reserved. If a rule is not specified in a configuration then the rule will never raise an event for the configuration. payload detection options. limited to: Source IP address and port Destination IP address and port Action A higher revision of a rule in one configuration will override other revisions of the same rule in other configurations. non-payload detection options.
These options are ignored in non-default policies without raising an error.9 includes a number of changes to better handle inline operation. Options controlling specific preprocessor memory usage.Refers to the absolute or relative filename. output alert_unified2: vlan_event_types (alert logging only) output unified2: filename <filename>.When this option is set. default configuration is used if no other matching configuration is found. are processed only in default policy. If the bound configuration is the default configuration. snort will use the first configuration in the order of definition. 2.10.. snort will use unified2 event type 104 and 105 for IPv4 and IPv6 respectively.Refers to a 16-bit unsigned value. through specific limit on memory usage or number of instances. In the end. then the innermost VLANID is used to find bound configuration. In this case. The packet is assigned non-default configuration if found otherwise the check is repeated using source IP address. snort assigns 0 (zero) value to the configuration.3 How Configuration is applied? Snort assigns every incoming packet to a unique configuration based on the following criteria. vlan_event_types (true unified logging) filename . If VLANID is present. This is required as some mandatory preprocessor configuration options are processed only in default configuration.11 Active Response Snort 2. this can lead to conflicts between configurations if source address is bound to one configuration and destination address is bound to another. ! △NOTE If no policy id is specified. to each configuration using the following config line: config policy_id: <id> id . ! △NOTE Each event logged will have the vlanId from the packet if vlan headers are present otherwise 0 will be used. including: 132 . vlan event types . The options control total memory usage for a preprocessor across all policies. that can be applied to the packet. 2. For addressed based configuration binding. A preprocessor must be configured in default configuration before it can be configured in non-default configuration.
This sequence ”strafing” is really only useful in passive mode.11./configure --enable-active-response config response: attempts <att> <att> ::= (1. . 2. if and only if attempts ¿ 0. In inline mode the reset is put straight into the stream in lieu of the triggering packet so strafing is not necessary.11.. non-functional.. \ min_response_seconds <min_sec> <max_rsp> ::= (0.20) 2.25) <min_sec> ::= (1. these features are no longer avaliable: . these features are deprecated.11. * Flexresp is deleted.1 Enabling Active Response This enables active responses (snort will send TCP RST or ICMP unreachable/port) when dropping a session. 2.• a single mechanism for all responses • fully encoded reset or icmp unreachable packets • updated flexible response rule option • updated react rule option • added block and sblock rule actions These changes are outlined below. . TCP data (sent for react) is multiplied similarly. and will be deleted in a future release: 133 . TTL will be set to the value captured at session pickup.3 Flexresp Flexresp and flexresp2 are replaced with flexresp3../configure --enable-active-response / -DACTIVE_RESPONSE preprocessor stream5_global: \ max_active_responses <max_rsp>. Each attempt (sent in rapid succession) has a different sequence number. At most 1 ICMP unreachable is sent.300) Active responses will be encoded based on the triggering packet./configure --enable-flexresp / -DENABLE_RESPOND -DENABLE_RESPONSE config flexresp: attempts 1 * Flexresp2 is deleted.
4 React react is a rule option keyword that enables sending an HTML page on a session and then resetting it.w3. You could craft a binary payload of arbitrary content. charset=utf-8\r\n" "\r\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.org/1999/xhtml\" xml:lang=\"en\">\r\n" \ "<head>\r\n" \ "<meta http-equiv=\"Content-Type\" content=\"text/html. the page is loaded and the selected message.org/TR/xhtml11/DTD/xhtml11. which defaults to: 134 . sid:1..1//EN\"\r\n" \ " \".) * resp t includes all flexresp and flexresp2 options: <resp_t> ::= \ rst_snd | rst_rcv | rst_all | \ reset_source | reset_dest | reset_both | icmp_net | \ icmp_host | icmp_port | icmp_all 2. When the rule is configured. .. resp:<resp_t>. In fact.11.1 403 Forbidden\r\n" "Connection: close\r\n" "Content-Type: text/html. the response isn’t strictly limited to HTTP. including any HTTP headers. Note that the file must contain the entire response.w3. This is built with: . charset=UTF-8\" />\r\n" \ "<title>Access Denied</title>\r\n" \ "</head>\r\n" \ "<body>\r\n" \ "<h1>Access Denied</h1>\r\n" \ "<p>%s</p>\r\n" \ "</body>\r\n" \ "</html>\r\n".dtd\">\r\n" \ "<html xmlns=\"> or else the default is used: <default_page> ::= \ "HTTP/1./configure --enable-react / -DENABLE_REACT The page to be sent can be read from a file: config react: <block./configure --enable-flexresp3 / -DENABLE_RESPOND -DENABLE_RESPONSE3 alert tcp any any -> any 80 (content:"a".
sid:4. 2. msg:"Unauthorized Access Prohibited!". 135 . This is an example rule: drop tcp any any -> any $HTTP_PORTS ( \ content: "d". If no page should be sent.) <react_opts> ::= [msg] [. The deprecated options are ignored.<br />" \ "Consult your system administrator for details.". The new version always sends the page to the client.<default_msg> ::= \ "You are attempting to access a forbidden site. \ react: <react_opts>. <dep_opts>] These options are deprecated: <dep_opts> ::= [block|warn]. [proxy <port#>] The original version sent the web page to one end of the session only if the other end of the session was port 80 or the optional proxy port.11.
Most Snort rules are written in a single line.Chapter 3 Writing Snort Rules 3. msg:"mountd access".1 Rule Actions The rule header contains the information that defines the who. This was required in versions prior to 1.0/24 111 \ (content:"|00 01 86 a5|". The text up to the first parenthesis is the rule header and the section enclosed in parenthesis contains the rule options. as well as what to do in the event that a packet with all the attributes indicated in the rule should show up.1: Sample Snort Rule 136 .1. and the source and destination ports information. rules may span multiple lines by adding a backslash \ to the end of the line.8. The rule option section contains alert messages and information on which parts of the packet should be inspected to determine if the rule action should be taken. the various rules in a Snort rules library file can be considered to form a large logical OR statement. Snort rules are divided into two logical sections. and what of a packet. ! △NOTE Note that the rule options section is not specifically required by any rule. There are a number of simple guidelines to remember when developing Snort rules that will help safeguard your sanity.1 The Basics Snort uses a simple. 3. for that matter). All of the elements in that make up a rule must be true for the indicated rule action to be taken. The rule header contains the rule’s action. The first item in a rule is the rule alert tcp any any -> 192.168. Figure 3. The words before the colons in the rule options section are called option keywords. the elements can be considered to form a logical AND statement. When taken together. they are just used for the sake of making tighter definitions of packets to collect or alert on (or drop.2. protocol. lightweight rules description language that is flexible and quite powerful.1 illustrates a sample Snort rule. At the same time. the rule header and the rule options. source and destination IP addresses and netmasks.2 Rules Headers 3. where. In current versions of Snort.) Figure 3.
the address/CIDR combination 192. You can then use the rule types as actions in Snort rules.action.2.alert and then turn on another dynamic rule 5. and then send a TCP reset if the protocol is TCP or an ICMP port unreachable message if the protocol is UDP. The CIDR block indicates the netmask that should be applied to the rule’s address and any incoming packets that are tested against the rule.log the packet 3. then act as a log rule 6. The CIDR designations give us a nice short-hand way to designate large address spaces with just a few characters. In the future there may be more. The keyword any may be used to define any address. activate .block the packet but do not log it.168. and /32 indicates a specific machine address. and IP. sdrop . pass.3 IP Addresses The next portion of the rule header deals with the IP address and port information for a given rule. log . You can also define your own rule types and associate one or more output plugins with them.ignore the packet 4. In addition. 3. and then log the packet 2.log } This example will create a rule type that will log to syslog and a MySQL database: ruletype redalert { type alert output alert_syslog: LOG_AUTH LOG_ALERT output database: log.2 Protocols The next field in a rule is the protocol. OSPF. GRE. /16 a Class B network.1.1 to 192. There are four protocols that Snort currently analyzes for suspicious behavior – TCP. user=snort dbname=snort host=localhost } 3.remain idle until activated by an activate rule . reject . 1. say. mysql.block and log the packet 7. The rule action tells Snort what to do when it finds a packet that matches the rule criteria.1. A CIDR block mask of /24 indicates a Class C network. Any rule that used this designation for.generate an alert using the selected alert method. Snort does not have a mechanism to provide host name lookup for the IP address fields in the config file. IGRP. UDP. This example will create a type that will log to just tcpdump: ruletype suspicious { type log output log_tcpdump: suspicious. alert . activate. log. you have additional options which include drop. 8. drop .1. ICMP. There are 5 available default actions in Snort. such as ARP. IPX. For example.168. etc.168. RIP. alert.block the packet.255. 137 . dynamic . if you are running Snort in inline mode. reject.0/24 would signify the block of addresses from 192. and dynamic. and sdrop. the destination address would match on any address in that range.2. log it. The addresses are formed by a straight numeric IP address and a CIDR[3] block. pass .
\ msg:"external mountd access".168.168.1. This rule’s IP addresses indicate any tcp packet with a source IP address not originating from the internal network and a destination address on the internal network. meaning literally any port. an easy modification to the initial example is to make it alert on any traffic that originates outside of the local net with the negation operator as shown in Figure 3.0/24] 111 (content:"|00 01 86 a5|".1. Port negation is indicated by using the negation operator !. the negation operator..0/24 500: log tcp traffic from privileged ports less than or equal to 1024 going to ports greater than or equal to 500 Figure 3. The range operator may be applied in a number of ways to take on different meanings.2. or 80 for http. 23 for telnet. if for some twisted reason you wanted to log everything except the X Windows ports. This operator tells Snort to match any IP address except the one indicated by the listed IP address.1.1.2. such as in Figure 3.1.1. An IP list is specified by enclosing a comma separated list of IP addresses and CIDR blocks within square brackets.0/24 any -> 192. For example.2: Example IP Address Negation Rule alert tcp ![192. msg:"external mountd access". or direction.2. including any ports. You may also specify lists of IP addresses.168. and by negation. and the destination address was set to match on the 192.3: IP Address Lists In Figure 3. For example. such as 111 for portmapper. you could do something like the rule in Figure 3.4.4 Port Numbers Port numbers may be specified in a number of ways.168.1.) Figure 3.0/24] any -> \ [192.5.1.10. For the time being.1.10.alert tcp !192.1.) Figure 3. The negation operator is indicated with a !.0/24 111 \ (content:"|00 01 86 a5|".5 The Direction Operator The direction operator -> indicates the orientation.).0/24. 3.168. ranges.1.168. See Figure 3.168. Port ranges are indicated with the range operator :.168. which would translate to none. etc. of the traffic that the rule applies to. 3.0/24 1:1024 log udp traffic coming from any port and destination ports ranging from 1 to 1024 log tcp any any -> 192. how Zen.. the source IP address was set to match for any computer talking. The IP address and port numbers on the left side of the direction operator is considered to be the traffic coming from the source log udp any any -> 192.0/24 :6000 log tcp traffic from any port going to ports less than or equal to 6000 log tcp any :1024 -> 192.0 Class C network. The negation operator may be applied against any of the other rule types (except any.0/24.4: Port Range Examples 138 . static port definitions. the IP list may not include spaces between the addresses. Static ports are indicated by a single port number.1. Any ports are a wildcard value. There is an operator that can be applied to IP addresses.1.3 for an example of an IP list in action.
\ msg:"IMAP buffer overflow!".operator. This is handy for recording/analyzing both sides of a conversation.7. In Snort versions before 1.1.7. Activate rules act just like alert rules. \ content:"|E8C0FFFFFF|/bin". combining ease of use with power and flexibility. and the address and port information on the right side of the operator is the destination host. Activate/dynamic rule pairs give Snort a powerful capability.1.0/24 any <> 192. The reason the <. There is also a bidirectional operator. Activate rules are just like alerts but also tell Snort to add a rule when a specific network event occurs. but they have a different option field: activated by. All Snort rule options are separated from each other using the semicolon (. Put ’em together and they look like Figure 3.0/24 23 Figure 3. Dynamic rules have a second required field as well. note that there is no <.7: Activate/Dynamic Rule Example 139 . the direction operator did not have proper error checking and many people used an invalid token.6.does not exist is so that rules always read consistently.6. You can now have one rule activate another when it’s action is performed for a set number of packets.6 Activate/Dynamic Rules ! △NOTE Activate and Dynamic rules are being phased out in favor of a combination of tagging (3.) character. 3. This is very useful if you want to set Snort up to perform follow on recording when a specific rule goes off.) Figure 3. so there’s value in collecting those packets for later analysis. which is indicated with a <> symbol. such as telnet or POP3 sessions. If the buffer overflow happened and was successful. except they have a *required* option field: activates.8. Rule option keywords are separated from their arguments with a colon (:) character.7. activates:1.0/24 !6000:6010 Figure 3. count:50.) dynamic tcp !$HOME_NET any -> $HOME_NET 143 (activated_by:1.168. count. An example of the bidirectional operator being used to record both sides of a telnet session is shown in Figure 3.168.2.3 Rule Options Rule options form the heart of Snort’s intrusion detection engine.5) and flowbits (3. there’s a very good possibility that useful data will be contained within the next 50 (or whatever) packets going to that same service port on the network.168.1. Also. activate tcp !$HOME_NET any -> $HOME_NET 143 (flags:PA. This tells Snort to consider the address/port pairs in either the source or destination orientation. These rules tell Snort to alert when it detects an IMAP buffer overflow and collect the next 50 packets headed for port 143 coming from outside $HOME NET headed to $HOME NET.6: Snort rules using the Bidirectional Operator host. Dynamic rules act just like log rules.5: Example of Port Negation log tcp !192. Dynamic rules are just like log rules except are dynamically enabled when the activate rule id goes off.10).log tcp any any -> 192. 3.
It is a simple text string that utilizes the \ as an escape character to indicate a discrete character that might otherwise confuse Snort’s rules parser (such as the semi-colon . This plugin is to be used by output plugins to provide a link to additional information about the alert produced.com/vil/content/v.” 3.com/bid/. <id>.com/info/IDS.] Examples alert tcp any any -> any 7070 (msg:"IDS411/dos-realaudio".1 msg The msg rule option tells the logging and alerting engine the message to print along with a packet dump or to an alert.nai.org/show/osvdb/ http:// System bugtraq cve nessus arachnids mcafee osvdb url Format reference:<id system>.php3?id= (currently down). Table 3. \ flags:AP. <id>.org/plugins/dump. reference:arachnids.2 reference The reference keyword allows rules to include references to external attack identification systems.There are four major categories of rule options. \ 140 . character).4 General Rule Options 3.cgi?name=. Make sure to also take a look at. 3.securityfocus.4.4.nessus. [reference:<id system>. content:"|fff4 fffd 06|".4.org/cgi-bin/cvename.4).snort. Format msg:"<message.mitre.1: Supported Systems URL Prefix.) alert tcp any any -> any 21 (msg:"IDS287/ftp-wuftp260-venglin-linux".IDS411.cgi/ for a system that is indexing descriptions of alerts based on of the sid (See Section 3. The plugin currently supports several specific systems as well as unique URLs.
\ reference:cve. Example This example is a rule with the Snort Rule ID of 1000983.4.999 Rules included with the Snort distribution • >=1. Note that the gid keyword is optional and if it is not specified in a rule.000 be used. To avoid potential conflict with gids defined in Snort (that for some reason aren’t noted it etc/generators).map contains contains more information on preprocessor and decoder gids. \ reference:arachnids. For example gid 1 is associated with the rules subsystem and various gids over 100 are designated for specific preprocessors and the decoder.) 3. gid:1000001. rev:1. This option should be used with the sid keyword. rev:1. content:"|31c031db 31c9b046 cd80 31c031db|". For general rule writing.4) The file etc/gen-msg. alert tcp any any -> any 80 (content:"BOB".5) • <100 Reserved for future use • 100-999. (See section 3. Format gid:<generator id>.1387. This information is useful when postprocessing alert to map an ID to an alert message.IDS287.4.4 sid The sid keyword is used to uniquely identify Snort rules. it will default to 1 and the rule will be part of the general rule subsystem. sid:1.000.map contains a mapping of alert messages to Snort rule IDs.CAN-2000-1574.000.) 3. (See section 3. it is recommended that values starting at 1.flags:AP. Format sid:<snort rules id>. it is not recommended that the gid keyword be used.000 Used for local rules The file sid-msg. This option should be used with the rev keyword. See etc/generators in the source tree for the current generator ids in use. Example This example is a rule with a generator id of 1000001. alert tcp any any -> any 80 (content:"BOB".4.4. reference:bugtraq. This information allows output plugins to identify rules easily.) 141 .3 gid The gid keyword (generator id) is used to identify what part of Snort generates the event when a particular rule fires. sid:1000983.
The file uses the following syntax: config classification: <class name>.) Attack classifications defined by Snort reside in the classification 142 Priority high high high high high high high high high high . Table 3.config file.<class description>. Defining classifications for rules provides a way to better organize the event data Snort produces. Revisions.4) Format rev:<revision integer>. classtype:attempted-recon.2. Snort provides a default set of attack classes that are used by the default set of rules it provides. nocase.4. flags:A+.4.6 classtype The classtype keyword is used to categorize a rule as detecting an attack that is part of a more general type of attack class. A priority of 1 (high) is the most severe and 4 (very low) is the least severe. They are currently ordered with 4 default priorities. \ content:"expn root".) 3. Format classtype:<class name>. alert tcp any any -> any 80 (content:"BOB".4. Example This example is a rule with the Snort Rule Revision of 1. This option should be used with the sid keyword. allow signatures and descriptions to be refined and replaced with updated information.5 rev The rev keyword is used to uniquely identify revisions of Snort rules. rev:1. (See section 3. Example alert tcp any any -> any 25 (msg:"SMTP expn root". sid:1000983. along with Snort rule id’s.3.<default priority> These attack classifications are listed in Table 3.
Examples alert tcp any any -> any 80 (msg:"WEB-MISC phf attempt". Examples of each case are given below. classtype:attempted-admin. flags:A+.conf by using the config classification option.) alert tcp any any -> any 80 (msg:"EXPLOIT ntpdx overflow". \ dsize:>128. \ content:"/cgi-bin/phf".7 priority The priority tag assigns a severity level to rules. Snort provides a default set of classifications in classification.4. priority:10 ). priority:10. 143 . A classtype rule assigns a default priority (defined by the config classification option) that may be overridden with a priority rule. Format priority:<priority integer>.config that are used by the rules it provides for details on the Host Attribute Table.3.8 metadata The metadata tag allows a rule writer to embed additional information about the rule. \ metadata:service http. Format The examples below show an stub rule from a shared library rule. while keys and values are separated by a space. Multiple keys are separated by a comma.) alert tcp any any -> any 80 (msg:"Shared Library Rule Example".) alert tcp any any -> any 80 (msg:"HTTP Service Rule Example". The first uses multiple metadata keywords. with a key and a value.4. metadata:key1 value1. otherwise.4: General rule option keywords Keyword msg reference gid Description The msg keyword tells the logging and alerting engine the message to print with the packet dump or alert. with keys separated by commas.4. .) 3. the second a single metadata keyword. Keys other than those listed in the table are effectively ignored by Snort and can be free-form. the rule is not applied (even if the ports specified in the rule match). \ metadata:engine shared. Certain metadata keys and values have meaning to Snort and are listed in Table 3. soid 3|12345. typically in a key-value format. When the value exactly matches the service ID as specified in the table. \ metadata:engine shared. See Section 2. key2 value2. metadata:key1 value1. the rule is applied to that packet.9 General Rule Quick Reference Table 3. 144 . The reference keyword allows rules to include references to external attack identification systems. Examples alert tcp any any -> any 80 (msg:"Shared Library Rule Example".3. Table 3. The gid keyword (generator id) is used to identify what part of Snort generates the event when a particular rule fires. metadata:soid 3|12345.
The example below shows use of mixed text and binary data in a Snort rule. The option data for the content keyword is somewhat complex.5. Be aware that this test is case sensitive. the result will return a match.) ! △NOTE A ! modifier negates the results of the entire content search. The priority keyword assigns a severity level to rules. Bytecode represents binary data as hexadecimal numbers and is a good shorthand method for describing complex binary data. Examples alert tcp any any -> any 139 (content:"|5c 00|P|00|I|00|P|00|E|00 5c|". This is useful when writing rules that want to alert on packets that do not match a certain pattern ! △NOTE Also note that the following characters must be escaped inside a content rule: . 145 . This allows rules to be tailored for less false positives. The binary data is generally enclosed within the pipe (|) character and represented as bytecode. If the rule is preceded by a !. it can contain mixed text and binary data. If data exactly matching the argument data string is contained anywhere within the packet’s payload. The rev keyword is used to uniquely identify revisions of Snort rules. \ " Format content:[!]"<content string>". For example. modifiers included. The metadata keyword allows a rule writer to embed additional information about the rule. Note that multiple content rules can be specified in one rule. It allows the user to set rules that search for specific content in the packet payload and trigger response based on that data. 3.sid rev classtype priority metadata The sid keyword is used to uniquely identify Snort rules. if using content:!"A".5 Payload Detection Rule Options 3. within:50. and there are only 5 bytes of payload and there is no ”A” in those 5 bytes.) alert tcp any any -> any 80 (content:!"GET".1 content The content keyword is one of the more important features of Snort. If there must be 50 bytes for a valid match. the test is successful and the remainder of the rule option tests are performed. Whenever a content option pattern match is performed. The classtype keyword is used to categorize a rule as detecting an attack that is part of a more general type of attack class. typically in a key-value format. the alert will be triggered on packets that do not contain this content. use isdataat as a pre-cursor to the content. the Boyer-Moore pattern match function is called and the (rather computationally expensive) test is performed against the packet contents.
9 http raw cookie 3.5.11 http raw header 3.5.6 within 3.5.5.5.13 http uri 3. 146 .10 http header 3.3 rawbytes The rawbytes keyword allows rules to look at the raw packet data.16 http stat msg 3.3 depth 3. These modifier keywords are: Table 3.5. nocase modifies the previous content keyword in the rule.8 http cookie 3.Changing content behavior The content keyword has a number of modifier keywords.5: Content Modifiers Modifier Section nocase 3.5.5.2 rawbytes 3. Example alert tcp any any -> any 21 (msg:"FTP ROOT".5.7 http client body 3.5. The modifier keywords change how the previously specified content works. ignoring any decoding that was done by preprocessors. ignoring case.15 http stat code 3.2 nocase The nocase keyword allows the rule writer to specify that the Snort should look for the specific pattern. Format nocase. nocase.) 3.1 option.5.5. This acts as a modifier to the previous content 3.14 http raw uri 3.5.5.5.5.5.4 offset 3.5.5.12 http method 3.5.17 fast pattern 3. content:"USER root". format rawbytes.5 distance 3.19 3.
alert tcp any any -> any 21 (msg:"Telnet NOP". depth modifies the previous ‘content’ keyword in the rule. there must be a content in the rule before depth is specified. You can not use offset with itself. or within (to modify the same content). Example The following example shows use of a combined content. The maximum allowed value for this keyword is 65535. offset. offset:4. alert tcp any any -> any 80 (content:"cgi-bin/phf".) 147 .4 depth The depth keyword allows the rule writer to specify how far into a packet Snort should search for the specified pattern. Format offset:[<number>|<var_name>]. As this keyword is a modifier to the previous content keyword. distance. A depth of 5 would tell Snort to only look for the specified pattern within the first 5 bytes of the payload. instead of the decoded traffic provided by the Telnet decoder. The offset and depth keywords may be used together.5.Example This example tells the content pattern matcher to look at the raw traffic.5 offset The offset keyword allows the rule writer to specify where to start searching for a pattern within a packet. The offset and depth keywords may be used together. 3. content:"|FF F1|". Format depth:[<number>|<var_name>]. depth:20.) 3. rawbytes. there must be a content in the rule before offset is specified. The value can also be set to a string value referencing a variable extracted by the byte extract keyword in the same rule. and depth search rule. This keyword allows values greater than or equal to the pattern length being searched. An offset of 5 would tell Snort to start looking for the specified pattern after the first 5 bytes of the payload. As the depth keyword is a modifier to the previous content keyword. The minimum allowed value is 1.5. distance. The value can also be set to a string value referencing a variable extracted by the byte extract keyword in the same rule. This keyword allows values from -65535 to 65535. You can not use depth with itself. offset modifies the previous ’content’ keyword in the rule. or within (to modify the same content).
1 ).) 148 . The distance and within keywords may be used together. This keyword allows values from -65535 to 65535. alert tcp any any -> any any (content:"ABC". Format distance:[<byte_count>|<var_name>].5.{1}DEF/. The distance and within keywords may be used together. It’s designed to be used in conjunction with the distance (Section 3.5). This keyword allows values greater than or equal to pattern length being searched.6) rule option. alert tcp any any -> any any (content:"ABC".5. or depth (to modify the same content). The value can also be set to a string value referencing a variable extracted by the byte extract keyword in the same rule. or depth (to modify the same content). content:"DEF".7 within The within keyword is a content modifier that makes sure that at most N bytes are between pattern matches using the content keyword ( See Section 3.6 distance The distance keyword allows the rule writer to specify how far into a packet Snort should ignore before starting to search for the specified pattern relative to the end of the previous pattern match. distance:1. You can not use within with itself. offset. except it is relative to the end of the last pattern match instead of the beginning of the packet. Examples This rule constrains the search of EFG to not go past 10 bytes past the ABC match.5. Example The rule below maps to a regular expression of /ABC.5.) 3. You can not use distance with itself.5. The maximum allowed value for this keyword is 65535. within:10. content:"EFG". offset. Format within:[<byte_count>|<var_name>]. This can be thought of as exactly the same thing as offset (See Section 3.3.. http_cookie. As this keyword is a modifier to the previous content keyword. 3. Pattern matches with this keyword wont work when post depth is set to -1. When enable cookie is not specified. Examples This rule constrains the search for the pattern ”EFG” to the extracted Cookie Header field of a HTTP client request.2. As this keyword is a modifier to the previous content keyword. alert tcp any any -> any 80 (content:"ABC".8 http client body The http client body keyword is a content modifier that restricts the search to the body of an HTTP client request. The extracted Cookie Header field may be NORMALIZED. Examples This rule constrains the search for the pattern ”EFG” to the raw body of an HTTP client request.) ! △NOTE The http client body modifier is not allowed to be used with the rawbytes modifier for the same content. Format http_client_body. using http cookie is the same as using http header. The Cookie Header field will be extracted only when this option is configured. The cookie buffer also includes the header name (Cookie for HTTP requests or Set-Cookie for HTTP responses). Format http_cookie. there must be a content in the rule before http cookie is specified.5.6). 149 .) ! △NOTE The http cookie modifier is not allowed to be used with the rawbytes or fast pattern modifiers for the same content. The amount of data that is inspected with this option depends on the post depth config option of HttpInspect. content:"EFG".3. per the configuration of HttpInspect (see 2. http_client_body.5.6). there must be a content in the rule before ’http client body’ is specified. alert tcp any any -> any 80 (content:"ABC". content:"EFG". This keyword is dependent on the enable cookie config option. If enable cookie is not specified. the cookie still ends up in HTTP header.2.
2.2. http cookie or fast pattern modifiers for the same content.6).3. there must be a content in the rule before http header is specified. per the configuration of HttpInspect (see 2.. Examples This rule constrains the search for the pattern ”EFG” to the extracted Unnormalized Cookie Header field of a HTTP client request. The extracted Header fields may be NORMALIZED. there must be a content in the rule before http raw cookie is specified. content:"EFG". As this keyword is a modifier to the previous content keyword.6).) ! △NOTE The http raw cookie modifier is not allowed to be used with the rawbytes. alert tcp any any -> any 80 (content:"ABC".5. 3. Format http_raw_cookie. The Cookie Header field will be extracted only when this option is configured. http_raw_cookie. http_header. alert tcp any any -> any 80 (content:"ABC".2.) ! △NOTE The http header modifier is not allowed to be used with the rawbytes modifier for the same content. Format http_header. 150 .5.6). As this keyword is a modifier to the previous content keyword.
Examples This rule constrains the search for the pattern ”GET” to the extracted Method from a HTTP client request. As this keyword is a modifier to the previous content keyword. Using a content rule option followed by a http uri modifier is the same as using a uricontent by itself (see: 3.6).) ! △NOTE modifier is not allowed to be used with the rawbytes modifier for the same content.5.3. http_raw_header.14 http uri The http uri keyword is a content modifier that restricts the search to the NORMALIZED request URI field . http header or fast pattern The http raw modifiers for the same content. there must be a content in the rule before http raw header is specified.5. Format http_raw_header. there must be a content in the rule before http uri is specified. Format http_method. there must be a content in the rule before http method is specified. 151 . As this keyword is a modifier to the previous content keyword. The http method 3.5. content:"EFG".) ! △NOTE header modifier is not allowed to be used with the rawbytes. alert tcp any any -> any 80 (content:"ABC". 3. alert tcp any any -> any 80 (content:"ABC". content:"GET". http_method. Examples This rule constrains the search for the pattern ”EFG” to the extracted Header fields of a HTTP client request or a HTTP server response.2.5.20).13 http method The http method keyword is a content modifier that restricts the search to the extracted Method from a HTTP client request. As this keyword is a modifier to the previous content keyword.
3.6). http_raw_uri. As this keyword is a modifier to the previous content keyword. alert tcp any any -> any 80 (content:"ABC".Format http_uri. Examples This rule constrains the search for the pattern ”EFG” to the NORMALIZED URI. As this keyword is a modifier to the previous content keyword. Examples This rule constrains the search for the pattern ”EFG” to the UNNORMALIZED URI. there must be a content in the rule before http stat code is specified. 3.5.) ! △NOTE The http uri modifier is not allowed to be used with the rawbytes modifier for the same content.2. content:"EFG".16 http stat code The http stat code keyword is a content modifier that restricts the search to the extracted Status code field from a HTTP server response. Format http_stat_code. Format http_raw_uri. http uri or fast pattern modifi . content:"EFG".5.) ! △NOTE The http raw uri modifier is not allowed to be used with the rawbytes. there must be a content in the rule before http raw uri is specified. http_uri. The Status Code field will be extracted only if the extended reponse inspection is configured for the HttpInspect (see 2. 152 .
6). alert tcp any any -> any 80 (content:"ABC". 3. The Status Message field will be extracted only if the extended reponse inspection is configured for the HttpInspect (see 2. ’double encode’. http_stat_msg.2. content:"Not Found".6). ’base36’. Negation is allowed on these keywords. The keywords ’uri’. This rule option will not be able to detect encodings if the specified HTTP fields are not NORMALIZED. ’iis encode’ and ’bare byte’ determine the encoding type which would trigger the alert. ’non ascii’. 153 . http_stat_code. There are eleven keywords associated with http encode.6).2. The config option ’normalize headers’ needs to be turned on for rules to work with the keyword ’header’. ’uencode’.5. content:"200".) ! △NOTE The http stat msg modifier is not allowed to be used with the rawbytes or fast pattern modifiers for the same content. 3. ’ascii’.Examples This rule constrains the search for the pattern ”200” to the extracted Status Code field of a HTTP server response.2. These keywords can be combined using a OR operation.18 http encode The http encode keyword will enable alerting based on encoding type present in a HTTP client request or a HTTP server response (per the configuration of HttpInspect 2. ’header’ and ’cookie’ determine the HTTP fields used to search for a particular encoding type. Examples This rule constrains the search for the pattern ”Not Found” to the extracted Status Message field of a HTTP server response. alert tcp any any -> any 80 (content:"ABC". The keyword ’cookie’ is dependent on config options ’enable cookie’ and ’normalize cookies’ (see 2. The keywords ’utf8’. there must be a content in the rule before http stat msg is specified. Format http_stat_msg.) ! △NOTE The http stat code modifier is not allowed to be used with the rawbytes or fast pattern modifiers for the same content.5.
5. http raw cookie. As this keyword is a modifier to the previous content keyword. 154 . the less likely the rule will needlessly be evaluated.) ! △NOTE Negation(!) and OR(|) operations cannot be used in conjunction with each other for the http encode keyword. however. The better the content used for the fast pattern matcher. there must be a content rule option in the rule before fast pattern is specified. it can significantly reduce the number of rules that need to be evaluated and thus increases performance. meaning the shorter content is less likely to be found in a packet than the longer content. that it is okay to use the fast pattern modifier if another http content modifier not mentioned above is used in combination with one of the above to modify the same content. http raw header. [!]<encoding type> http_encode:[uri|header|cookie]. http stat msg. ! △NOTE The fast pattern modifier cannot be used with the following http content modifiers: http cookie. it is useful if a shorter content is more ”unique” than the longer content.19 fast pattern The fast pattern keyword is a content modifier that sets the content within a rule to be used with the fast pattern matcher. Though this may seem to be overhead. Since the default behavior of fast pattern determination is to use the longest content in the rule. The fast pattern option may be specified only once per rule. http_encode:uri.utf8|uencode.) alert tcp any any -> any any (msg:"No UTF8". http stat code. 3. The OR and negation operations work only on the encoding type field and not on http buffer type field. Note. fast pattern matcher is used to select only those rules that have a chance of matching by using a content in the rule for selection and only evaluating that rule if the content is found in the payload. [!][<utf8|double_encode|non_ascii|base36|uencode|bare_byte|ascii|iis_e Examples alert tcp any any -> any any (msg:"UTF8/UEncode Encoding present". http_encode:uri.!utf8. http raw uri.
for example.<length> can be used to specify that only a portion of the content should be used for the fast pattern matcher. ! △NOTE arguments only and <offset>. the meaning is simply to use the specified content as the fast pattern content for the rule.5. the URI: 155 . As such if you are writing rules that include things that are normalized.) This rule says to use ”JKLMN” as the fast pattern content. When used alone. fast_pattern:1. if a known content must be located in the payload independent of location in the payload. The optional argument only can be used to specify that the content should only be used for the fast pattern matcher and should not be evaluated as a rule option.! △NOTE modifier can be used with negated contents only if those contents are not modified with The fast pattern offset. distance or within.5.<length>. depth. fast_pattern:only. fast_pattern:only. This is useful if the pattern is very long and only a portion of the pattern is necessary to satisfy ”uniqueness” thus reducing the memory required to store the entire pattern in the fast pattern matcher. depth. For example. fast_pattern. even though it is shorter than the earlier pattern ”ABCDEFGH”. The reason is that the things you are looking for are normalized out of the URI buffer. The optional argument <offset>. content:"IJKLMNO". content:"IJKLMNO". but still evaluate the content rule option as ”IJKLMNO”.20 uricontent The uricontent keyword in the Snort rule language searches the NORMALIZED request URI field. fast_pattern.<length> are mutually exclusive. fast_pattern:<offset>. alert tcp any any -> any 80 (content:"ABCDEFGH". The optional Examples This rule causes the pattern ”IJKLMNO” to be used with the fast pattern matcher. content:"IJKLMNO". these rules will not alert. This is equivalent to using the http uri modifier to a content keyword.) 3. Note that (1) the modified content must be case insensitive since patterns are inserted into the pattern matcher in a case insensitive manner. as it saves the time necessary to evaluate the rule option. alert tcp any any -> any 80 (content:"ABCDEFGH". distance or within. Format The fast pattern option can be used alone or optionally take arguments. alert tcp any any -> any 80 (content:"ABCDEFGH". such as %2f or directory traversals. nocase. This is useful.) This rule says to use the content ”IJKLMNO” for the fast pattern matcher and that the content should only be used for the fast pattern matcher and not evaluated as a content rule option. (2) negated contents cannot be used and (3) contents cannot have any positional modifiers such as offset.
2 depth 3.exe?/c+ver Another example. You can write rules that look for the non-normalized content by using the content option.%c0%af.6: Uricontent Modifiers Modifier Section nocase 3. write the content that you want to find in the context that the URI will be normalized..7 fast pattern 3. ! △NOTE cannot be modified by a rawbytes modifier or any of the other HTTP modifiers. the minimum length.5. The following example will match URIs that are 5 bytes long: 156 .%252fp%68f? will get normalized into: /cgi-bin/phf? When writing a uricontent rule.6 within 3.19 This option works in conjunction with the HTTP Inspect preprocessor specified in Section 2.2.21 urilen The urilen keyword in the Snort rule language specifies the exact length. or range of URI lengths to match.6.5. 3. the maximum length./winnt/system32/cmd.5.5. Format uricontent:[!]"<content string>". If you wish to uricontent search the UNNORMALIZED request URI field../scripts/. (See Section 3. These include: Table 3.4 offset 3.5.exe?/c+ver will get normalized into: /winnt/system32/cmd.. if Snort normalizes directory traversals.1) uricontent can be used with several of the modifiers available to the content keyword. use the http raw uri modifier with a content option. Format urilen:min<>max. do not include directory traversals. the URI: /cgi-bin/aaaaaaaaaaaaaaaaaaaaaaaaaa/.5. For example.5. urilen:[<|>]<number>.5 distance 3.5.
The following example will match URIs that are shorter than 5 bytes: urilen:<5. and 3.5. relative|rawbytes]. P. S and Y. The following example will match URIs that are greater than 5 bytes and less than 10 bytes: urilen:5<>10.org Format pcre:[!]"(/<regex>/|m<delim><regex><delim>)[ismxAEGRUBPHMCOIDKYS]". D. 3. See tables 3. For more detail on what can be done via a pcre regular expression.relative. When the rawbytes modifier is specified with isdataat.7. The modifiers H. K.22 isdataat Verify that the payload has data at a specified location.urilen:5.5. ignoring any decoding that was done by the preprocessors.9 for descriptions of each modifier. 3.) This rule looks for the string PASS exists in the packet. ! △NOTE R (relative) and B (rawbytes) are not allowed with any of the HTTP modifiers such as U. M.6. within:50. would alert if there were not 10 bytes after ”foo” before the payload ended. then verifies that there is not a newline character within 50 bytes of the end of the PASS string.relative. I. C. isdataat:50. This modifier will work with the relative modifier as long as the previous content match was in the raw packet data. A ! modifier negates the results of the isdataat test. check out the PCRE web site. This option works in conjunction with the HTTP Inspect preprocessor specified in Section 2. Format isdataat:[!]<int>[.2.pcre. For example. isdataat:!10. it looks at the raw packet data. 3. then verifies there is at least 50 bytes after the end of the string PASS. The post-re modifiers set compile time flags for the regular expression. 157 .23 pcre The pcre keyword allows rules to be written using perl compatible regular expressions. \ content:!"|0a|". the rule with modifiers content:"foo". Example alert tcp any any -> any 111 (content:"PASS". It will alert if a certain amount of data is not present within the payload.8. optionally looking for data relative to the end of the previous content match.
When m is set.6 for more details. Example This example performs a case-insensitive search for the string BLAH in the payload. PCRE when used without a uricontent only evaluates the first URI. whitespace data characters in the pattern are ignored except when escaped or inside a character class A E G Table 3. Inverts the ”greediness” of the quantifiers so that they are not greedy by default.2.24 file data This option is used to place the cursor (used to walk the packet payload in rules processing) at the beginning of either the entity body of a HTTP response or the SMTP body data. certain HTTP Inspect options such as extended response inspection and inspect gzip (for decompressed gzip data) needs to be turned on. as well as the very start and very end of the buffer. Without E. pcre) to use. See 2. byte jump. This option matches if there is HTTP response body or SMTP body or SMTP MIME base64 decoded data.8: PCRE compatible modifiers for pcre the pattern must match only at the start of the buffer (same as ˆ ) Set $ to match only at the end of the subject string.) ! △NOTE Snort’s handling of multiple URIs with PCRE does not work as expected. file_data:mime.7: Perl compatible modifiers for pcre case insensitive include newlines in the dot metacharacter By default. alert ip any any -> any any (pcre:"/BLAH/i". Format file_data. In order to use pcre to inspect all URIs. 158 . ˆ and $ match at the beginning and ending of the string. This file data can point to either a file or a block of data. See 2.i s m x Table 3. $ also matches immediately before the final character if it is a newline (but not before any other newlines). but become greedy if followed by ”?”. When used with argument mime it places the cursor at the beginning of the base64 decoded MIME attachment or base64 decoded MIME body. ˆ and $ match immediately following or immediately before any newline in the buffer. you must use either a content or a uricontent.5.2. This option will operate similarly to the dce stub data option added with DCE/RPC2. the string is treated as one big line of characters. For this option to work with HTTP response.7 for more details. in that it simply sets a reference for other relative rule options ( byte test. 3. This is dependent on the SMTP config option enable mime decoding.
25 base64 decode This option is used to decode the base64 encoded data. content:"foo".9: Snort specific modifiers for pcre Match relative to the end of the last pattern match. Match the unnormalized HTTP request uri buffer (Similar to http raw uri). This modifier is not allowed with the HTTP request uri buffer modifier(U) for the same content. ][offset <offset>[. \ file_data. This modifier is not allowed with the normalized HTTP request or HTTP response cookie modifier(C) for the same content. nocase. (Similar to distance:0. This option unfolds the data before decoding it. Format base64_decode[:[bytes <bytes_to_decode>][.R U I P H D M C K S Y B O Table 3. Match normalized HTTP request method (Similar to http method) Match normalized HTTP request or HTTP response cookie (Similar to http cookie). This modifier is not allowed with the normalized HTTP request or HTTP response header modifier(H) for the same content. Example alert tcp any 80 -> any any(msg:"foo at the start of http response body". This modifier is not allowed with the unnormalized HTTP request or HTTP response header modifier(D) for the same content. Match unnormalized HTTP request body (Similar to http client body) Match normalized HTTP request or HTTP response header (Similar to http header). ! △NOTE Multiple base64 encoded attachments in one packet are pipelined.5. This modifier is not allowed with the unnormalized HTTP request uri buffer modifier(I) for the same content. Match unnormalized HTTP request or HTTP response cookie (Similar to http raw cookie).3). This option is particularly useful in case of HTTP headers such as HTTP authorization headers.) alert tcp any any -> any any(msg:"MIME BASE64 Encoded Data". It completely ignores the limits while evaluating the pcre pattern specified. within:10. This modifier is not allowed with the unnormalized HTTP request or HTTP response cookie modifier(K) for the same content. within.) 3.\ file_data:mime. Match unnormalized HTTP request or HTTP response header (Similar to http raw header). relative]]]. 159 . content:"foo".) Match the decoded URI buffers (Similar to uricontent and http uri).1.
This option will operate similarly to the file data option. pcre) to use. within:8. \ content:"foo bar". byte jump. ! △NOTE Any non-relative rule options in the rule will reset the cursor(doe ptr) from base64 decode buffer. The rule option base64 decode needs to be specified before the base64 data option. The above arguments to base64 decode are optional. base64_data. within:20. offset 6. content:"Authorization: NTLM". Specifies the inspection for base64 encoded data is relative to the doe ptr. This option matches if there is base64 decoded buffer.) 3. 160 . If folding is not present the search for base64 encoded data will end when we see a carriage return or line feed or both without a following space or tab. base64_data. base64_decode:relative. \ base64_decode:bytes 12. in that it simply sets a reference for other relative rule options ( byte test. content:"NTLMSSP". \ content:"NTLMSSP". base64_data. This argument takes positive and non-zero values only. This option does not take any arguments. http_header. \ content:"Authorization:". This argument takes positive and non-zero values only. Determines the offset relative to the doe ptr when the option relative is specified or relative to the start of the packet payload to begin inspection of base64 encoded data. This option needs to be used in conjunction with base64 data for any other relative rule options to work on base64 decoded buffer.Option bytes offset relative Description Number of base64 encoded bytes to decode. base64_decode. relative. \ within:20. Format base64_data. ! △NOTE This option can be extended to protocols with folding similar to HTTP.) alert tcp any any -> any any (msg:"Authorization NTLM". Examples alert tcp $EXTERNAL_NET any -> $HOME_NET any \ (msg:"Base64 Encoded Data".5. Fast pattern content matches are not allowed with this buffer.) alert tcp $EXTERNAL_NET any -> $HOME_NET any \ (msg:"Authorization NTLM".
4294967295 -65535 to 65535 Description Number of bytes to pick up from the packet. See section 2. then it would be the same as using if (data & value) { do something().13 for a description and examples (2. please read Section 3. \ content:"Authorization:". For a more detailed explanation.Converted string data is represented in decimal • oct . Format byte_test:<bytes to convert>. dce].5.2. then the operator is set to =.less than • > . Option bytes to convert operator Any of the operators can also include ! to check if the operator is not true.10 ’<’ | ’=’ | ’>’ | ’&’ | ’ˆ’ 0 .greater than • = . If the & operator is used. Capable of testing binary values or converting representative byte strings to their binary equivalent and testing them. offset 6. <value>. The allowed values are 1 to 10 when used without dce. \ content:"NTLMSSP". If ! is specified without an operator.bitwise AND • ˆ . string. Operation to perform to test the value: • < .27 byte test Test a byte field against a specific value (with operator).Process data as big endian (default) • little . <offset> \ [.Process data as little endian string number type Data is stored in string format in packet Type of number being read: • hex .equal • & .} Examples alert udp $EXTERNAL_NET any -> $HOME_NET any \ 161 . bytes operator value offset = = = = 1 . base64_data. 2 and 4. [!]<operator>. <endian>][.) 3.Example alert tcp any any -> any any (msg:"Authorization NTLM". \ base64_decode:bytes 12.2.5. ! △NOTE Snort uses the C operators for each of these operators.9.13 for quick reference). http_header. <number type>][. If used with dce allowed values are 1.Converted string data is represented in octal dce Let the DCE/RPC 2 preprocessor determine the byte order of the value to be converted. relative. within:8. relative][.bitwise OR value offset relative endian Value to test the converted value against Number of bytes into the payload to start processing Use an offset relative to last pattern match Endian type of the number being read: • big .Converted string data is represented in hexadecimal • dec .
0xdeadbeef. within:4. 0. 20. dec. =.) alert udp any any -> any 1238 \ (byte_test:8.10 -65535 to 65535 0 . <endian>][. 1000. dec. please read Section 3. =. within:4. hex. 12. dec.) alert udp any any -> any 1235 \ (byte_test:3. The byte jump option does this by reading some number of bytes. 1234567890. \ msg:"got 123!".) alert udp any any -> any 1234 \ (byte_test:4. string.9. from_beginning][. \ byte_test:4. 0. dce]. or doe ptr. >. post_offset <adjustment value>][. move that many bytes forward and set a pointer for later detection. relative. 0. relative. 0.5. \ content:"|00 00 00 07|". \ byte_test:4. 123. <number_type>]\ [. 0. string. \ msg:"got 12!".) alert udp any any -> any 1236 \ (byte_test:2. \ msg:"got 1234567890!". convert them to their numeric representation. =. \ content:"|00 00 00 07|". <offset> \ [. 1234.) 3. \ msg:"got DEADBEEF!". distance:4. =. 20. =. \ msg:"got 1234!". For a more detailed explanation. This pointer is known as the detect offset end pointer.) alert udp any any -> any 1237 \ (byte_test:10. then skips that far forward in the packet.65535 -65535 to 65535 162 . string. By having an option that reads the length of a portion of data. Format byte_jump:<bytes_to_convert>.(msg:"AMD procedure 7 plog overflow". align][. string.28 byte jump The byte jump keyword allows rules to be written for length encoded protocols trivially. string. \ content:"|00 04 93 F3|". >. relative][. \ content:"|00 04 93 F3|". distance:4. bytes offset mult_value post_offset = = = = 1 . multiplier <mult_value>][.) alert tcp $EXTERNAL_NET any -> $HOME_NET any \ (msg:"AMD procedure 7 plog overflow". rules can be written that skip over specific portions of length-encoded protocols and perform detection in very specific locations. string.5. 1000. dec.
relative. \ content:"|00 00 00 01|". Its use is in extracting packet data for use in other rule options. It reads in some number of bytes from the packet payload and saves it to a variable. Data is stored in string format in packet Converted string data is represented in hexadecimal Converted string data is represented in decimal Converted string data is represented in octal Round the number of converted bytes up to the next <value>-byte boundary. 20. This will be used to reference the variable in other rule options. Number of bytes into the payload to start processing Use an offset relative to last pattern match Multiply the number of calculated bytes by <value> and skip forward that number of bytes. Process data as big endian (default) Process data as little endian Use the DCE/RPC 2 preprocessor to determine the byte-ordering. They can be re-used in the same rule any number of times. <value> may be 2 or 4.). distance:4. \ byte_jump:4. <offset>. within:4. ! △NOTE Only two byte extract variables may be created per rule. instead of using hard-coded values.29 byte extract The byte extract keyword is another useful option for writing rules against length-encoded protocols. Here is a list of places where byte extract variables can be used: 163 .2. \ msg:"statd format string buffer overflow". Let the DCE/RPC 2 preprocessor determine the byte order of the value to be converted. 900. Format byte_extract:<bytes_to_extract>. These variables can be referenced later in the rule. See section 2. If used with dce allowed values are 1. Skip forward or backwards (positive of negative value) by <value> number of bytes after the other jump options have been applied. <number_type>][. align <align value>][. string. 2 and 4. dce] Option bytes to convert offset name relative multiplier <value> big little dce string hex dec oct align <value> Description Number of bytes to pick up from the packet Number of bytes into the payload to start processing Name of the variable. \ byte_test:4. Other options which use byte extract variables A byte extract rule option detects nothing by itself.2. >. The DCE/RPC 2 preprocessor must be enabled for this option to work. <name> \ [. <endian>]\ [. relative.5. Use an offset relative to last pattern match Multiply the bytes read from the packet by <value> and save that number into the variable. multiplier <multiplier value>][.13 for a description and examples (2. relative][|". 12. align.13 for quick reference).
asn1:bitstring_overflow. the offset value.) 3. distance.31 asn1 The ASN. depth. depth:str_depth. This is the relative offset from the last content match or byte test/jump. Format asn1:[bitstring_overflow][. Offset may be positive or negative.1 type is greater than 500.\ classtype:misc-attack. So if you wanted to start decoding and ASN. Compares ASN. Option bitstring overflow double overflow oversize length <value> Description Detects invalid bitstring encodings that are known to be remotely exploitable. absolute offset has one argument.Rule Option content/uricontent byte test byte jump isdataat Arguments that Take Variables offset.1 options provide programmatic detection capabilities as well as some more dynamic type detection. you would specify ’content:"foo".1 detection plugin decodes a packet or a portion of a packet. the whole option evaluates as true. \ flow:to_server. but it is unknown at this time which services may be exploitable. oversize_length <value>][.established. This is known to be an exploitable function in Microsoft. Offset values may be positive or negative. • Read the depth of a string from a byte at offset 1. relative_offset 0’. \ content:"bad stuff".30 ftpbounce The ftpbounce keyword detects FTP bounce attacks. This is the absolute offset from the beginning of the packet. str_depth. Multiple options can be used in an ’asn1’ option and the implied logic is boolean OR.5. then this keyword is evaluated as true. Example alert tcp $EXTERNAL_NET any -> $HOME_NET 21 (msg:"FTP PORT bounce attempt". The syntax looks like. and looks for various malicious encodings. \ msg:"Bad Stuff detected within field". rev:1. double_overflow][. if you wanted to decode snmp packets. For example. Detects a double ASCII encoding that is larger than a standard buffer. This keyword must have one argument which specifies the length to compare against. absolute_offset <value>|relative_offset <value>]. within offset. pcre:"/ˆPORT/smi". • Use these values to constrain a pattern match to a smaller area. \ byte_extract:1.1 sequence right after the content “foo”. sid:3441. absolute offset <value> relative offset <value> 164 . The preferred usage is to use a space between option and argument. alert tcp any any -> any any (byte_extract:1. the offset number. This means that if an ASN. str_offset. value offset offset Examples This example uses two variables to: • Read the offset of a string from a byte at offset 0. ftpbounce. nocase. the option and the argument are separated by a space or a comma. So if any of the arguments evaluate as true. If an option has an argument. content:"PORT".) 3. Format ftpbounce. 1. “oversize length 500”.1 type lengths with the supplied argument. The ASN.5. relative offset has one argument. you would say “absolute offset 0”. 0. offset:str_offset.
5.13 for a description and examples of using this rule option.Examples alert udp any any -> any 161 (msg:"Oversize SNMP Length".13 for a description and examples of using this rule option. absolute_offset 0.2.5. Option invalid-entry Description Looks for an invalid Entry string.2. 3. ! △NOTE This plugin cannot do detection over encrypted sessions.15 and before.11 for a description and examples of using this rule option. 165 . CVE-2004-0396: ”Malformed Entry Modified and Unchanged flag insertion”.10: Payload detection rule option keywords Keyword content Description The content keyword allows the user to set rules that search for specific content in the packet payload and trigger response based on that data.11 for a description and examples of using this rule option. relative_offset 0.2.13 for a description and examples of using this rule option.32 cvs The CVS detection plugin aids in the detection of: Bugtraq-10384.38 Payload Detection Quick Reference Table 3. 3. Examples alert tcp any any -> any 2401 (msg:"CVS Invalid-entry". \ flow:to_server.11.5. 3.2. SSH (usually port 22). \ asn1:bitstring_overflow.5. 3.) 3.established. Default CVS server ports are 2401 and 514 and are included in the default ports for stream reassembly.) alert tcp any any -> any 80 (msg:"ASN1 Relative Foo". Format cvs:<option>.5. \ asn1:oversize_length 10000.35 dce stub data See the DCE/RPC 2 Preprocessor section 2.37 ssl state See the SSL/TLS Preprocessor section 2.36 ssl version See the SSL/TLS Preprocessor section 2. cvs:invalid-entry. which is a way of causing a heap overflow (see CVE-2004-0396) and bad pointer derefenece in versions of CVS 1.2. e.5.) 3.34 dce opnum See the DCE/RPC 2 Preprocessor section 2. content:"foo".33 dce iface See the DCE/RPC 2 Preprocessor section 2.5.g. 3.
The uricontent keyword in the Snort rule language searches the normalized request URI field. ttl:[<number>]-[<number>]. The within keyword is a content modifier that makes sure that at most N bytes are between pattern matches using the content keyword. Example This example checks for a time-to-live value that is less than 3.2 ttl The ttl keyword is used to check the IP time-to-live value. >=]<number>.2. fragoffset:0. ttl:<3. The offset keyword allows the rule writer to specify where to start searching for a pattern within a packet.13. The byte test keyword tests a byte field against a specific value (with operator). you could use the fragbits keyword and look for the More fragments option in conjunction with a fragoffset of 0. See the DCE/RPC 2 Preprocessor section 2. Format ttl:[<.1 fragoffset The fragoffset keyword allows one to compare the IP fragment offset field against a decimal value.6 Non-Payload Detection Rule Options 3.2. The byte jump keyword allows rules to read the length of a portion of data.6. Format fragoffset:[!|<|>]<number>. To catch all the first fragments of an IP session. See the DCE/RPC 2 Preprocessor section 2. >. The distance keyword allows the rule writer to specify how far into a packet Snort should ignore before starting to search for the specified pattern relative to the end of the previous pattern match. This example checks for a time-to-live value that between 3 and 5. The isdataat keyword verifies that the payload has data at a specified location. <=. The ftpbounce keyword detects FTP bounce attacks. 166 . The asn1 detection plugin decodes a packet or a portion of a packet. =. The cvs keyword detects invalid entry strings. then skip that far forward in the packet. and looks for various malicious encodings. fragbits:M.) 3. See the DCE/RPC 2 Preprocessor section 2. This keyword takes numbers from 0 to 255. The depth keyword allows the rule writer to specify how far into a packet Snort should search for the specified pattern. Example alert ip any any -> any any \ (msg:"First Fragment". The pcre keyword allows rules to be written using perl compatible regular expressions. 3.13.2.6. This option keyword was intended for use in the detection of traceroute attempts. ignoring any decoding that was done by preprocessors.13.
Few other examples are as follows: ttl:<=5. ttl:-5. the value 31337 is very popular with some hackers. This example checks for a time-to-live value that between 5 and 255. ttl:=<5. 3. ttl:=5. This example checks for a time-to-live value that between 0 and 5. ttl:>=5. The following examples are NOT allowed by ttl keyword: ttl:=>5. 167 . id:31337. Example This example looks for a tos value that is not 4 tos:!4. 3. Some tools (exploits. Format id:<number>. Format tos:[!]<number>.3 tos The tos keyword is used to check the IP TOS field for a specific value. ttl:5-3.6.6.4 id The id keyword is used to check the IP ID field for a specific value. scanners and other odd programs) set this field specifically for various purposes. Example This example looks for the IP ID of 31337.ttl:3-5. for example. ttl:5-.
Don’t Fragment R .More Fragments D .Strict Source Routing satid .No Op ts .Loose Source Routing (For MS99-038 and CVE-1999-0909) ssrr .6. plus any others * match if any of the specified bits are set ! match if the specified bits are not set Format fragbits:[+*!]<[MDR]>.any IP options are set The most frequently watched for IP options are strict and loose source routing which aren’t used in any widespread internet applications. 3.6 fragbits The fragbits keyword is used to check if fragmentation and reserved bits are set in the IP header.IP Security esec .Record Route eol . The following bits may be checked: M .6. fragbits:MD+. Format ipopts:<rr|eol|nop|ts|sec|esec|lsrr|lsrre|ssrr|satid|any>.Stream identifier any . 168 . Warning Only a single ipopts keyword may be specified per rule.5 ipopts The ipopts keyword is used to check if a specific IP option is present. Example This example looks for the IP Option of Loose Source Routing. The following options may be checked: rr .Reserved Bit The following modifiers can be set to change the match criteria: + match on the specified bits.3.Loose Source Routing lsrre .Time Stamp sec .End of list nop . ipopts:lsrr.IP Extended Security lsrr . Example This example checks if the More Fragments bit and the Do not Fragment bit are set.
alert tcp any any -> any any (flags:SF.Urgent 1 . In many cases. plus any others * .3.Reset P .<FSRPAU12>].FIN . Format flags:[!|*|+]<FSRPAU120>[.ECE .Synchronize sequence numbers R . then ECN capable. This may be used to check for abnormally sized packets. Warning dsize will fail on stream rebuilt packets. A rule could check for a flags value of S.match if the specified bits are not set To handle writing rules for session initiation packets such as ECN where a SYN packet is sent with the previously reserved bits 1 and 2 set. CE flag in IP header is set) 0 .URG .Acknowledgment U .ACK .match if any of the specified bits are set ! .match on the specified bits.12 if one wishes to find packets with just the syn bit. Else.6. Example This example looks for a dsize that is between 300 and 400 bytes.RST .SYN . dsize:[<|>]<number>. 3.12. Format dsize:min<>max. an option mask may be specified.) 169 .ECN-Echo (If SYN.No TCP Flags Set The following modifiers can be set to change the match criteria: + . ignoring reserved bit 1 and reserved bit 2. Example This example checks if just the SYN and the FIN bits are set.6.8 flags The flags keyword is used to check if specific TCP flag bits are present.Congestion Window Reduced (MSB in TCP Flags byte) 2 .PSH . The following bits may be checked: F . regardless of the size of the payload.Finish (LSB in TCP Flags byte) S .7 dsize The dsize keyword is used to test the packet payload size. dsize:300<>400. regardless of the values of the reserved bits.Push A .CWR . it is useful for detecting buffer overflows.
as it allows rules to generically track the state of an application protocol.(to_client|to_server|from_client|from_server)] [. nocase. Most of the options need a user-defined name for the specific state that is being checked. regardless of the rest of the detection options..(no_stream|only_stream)] [. Checks if the specified state is not set.2. Checks if the specified state is set. content:"CWD incoming". When no group name is specified the flowbits will belong to a default group. Cause the rule to not generate an alert. 170 . This allows packets related to $HOME NET clients viewing web pages to be distinguished from servers running in the $HOME NET. Unsets the specified state for the current flow. \ flow:stateless.3. There are eight keywords associated with flowbits. This string should be limited to any alphanumeric string including periods. Reset all states on a given flow.2). Examples alert tcp !$HOME_NET any -> $HOME_NET 21 (msg:"cd incoming detected". All the flowbits in a particular group (with an exception of default group) are mutually exclusive. \ flow:from_client. The keywords set and toggle take an optional argument which specifies the group to which the keywords will belong.6. The established keyword will replace the flags:+A used in many places to show established TCP connections.) alert tcp !$HOME_NET 0 -> $HOME_NET 0 (msg:"Port 0 TCP traffic". dashes.(no_frag|only_frag)]. The flowbits option is most useful for TCP sessions.9 flow The flow keyword is used in conjunction with TCP stream reassembly (see Section 2. otherwise unsets the state if the state is set. It allows rules to track states during a transport protocol session.) 3.10 flowbits The flowbits keyword is used in conjunction with conversation tracking from the Stream preprocessor (see Section2. It allows rules to only apply to certain directions of the traffic flow. A particular flow cannot belong to more than one group. Sets the specified state if the state is unset and unsets all the other flowbits in a group when a GROUP NAME is specified.2).2. and underscores.6. This allows rules to only apply to clients or servers.)] [.
ack:0. 171 .6.logged_in. seq:0. Example This example looks for a TCP acknowledge number of 0. 3. content:"OK LOGIN". flowbits:noalert. flowbits:isset.Format flowbits:[set|unset|toggle|isset|isnotset|noalert|reset][. <STATE_NAME>][. Format ack:<number>.logged_in. Format seq:<number>. <GROUP_NAME>]. Example This example looks for a TCP sequence number of 0. flowbits:set. Example This example looks for a TCP window size of 55808. content:"LIST". Examples alert tcp any 143 -> any any (msg:"IMAP login".13 window The window keyword is used to check for a specific TCP window size. 3.) alert tcp any any -> any 143 (msg:"IMAP LIST". window:55808.11 seq The seq keyword is used to check for a specific TCP sequence number.6.) 3.6. Format window:[!]<number>.12 ack The ack keyword is used to check for a specific TCP acknowledge number.
3. This is useful because some covert channel programs use static ICMP fields when they communicate. Format itype:min<>max.6. This particular plugin was developed to detect the stacheldraht DDoS agent.6.6. 172 . Format icmp_id:<number>. Format icode:min<>max. itype:[<|>]<number>. This particular plugin was developed to detect the stacheldraht DDoS agent. Example This example looks for an ICMP code greater than 30.3. 3.16 icmp id The icmp id keyword is used to check for a specific ICMP ID value.14 itype The itype keyword is used to check for a specific ICMP type value. itype:>30.15 icode The icode keyword is used to check for a specific ICMP code value. Example This example looks for an ICMP ID of 0. Format icmp_seq:<number>.6. 3. icmp_id:0. Example This example looks for an ICMP type greater than 30. icode:>30. This is useful because some covert channel programs use static ICMP fields when they communicate. icode:[<|>]<number>.17 icmp seq The icmp seq keyword is used to check for a specific ICMP sequence value.
Wildcards are valid for both version and procedure numbers by using ’*’.6. 3. icmp_seq:0.19 ip proto The ip proto keyword allows checks against the IP protocol header. alert ip any any -> any any (ip_proto:igmp. 3. Format ip_proto:[!|>|<] <name or number>. and procedure numbers in SUNRPC CALL requests. Format rpc:<application number>.6.) 3. see /etc/protocols. Example The following example looks for an RPC portmap GETPORT request. Format sameip.). Example This example looks for IGMP traffic. *.20 sameip The sameip keyword allows rules to check if the source ip is the same as the destination IP.18 rpc The rpc keyword is used to check for a RPC application. alert ip any any -> any any (sameip.) 173 . alert tcp any any -> any 111 (rpc:100000. Warning Because of the fast pattern matching engine. version. 3. Example This example looks for any traffic where the Source IP and the Destination IP is the same. [<version number>|*].6. For a list of protocols that may be specified by name.Example This example looks for an ICMP Sequence of 0. the RPC keyword is slower than looking for the RPC values by using normal content matching. [<procedure number>|*]>.
• The optional noalert parameter causes the rule to not generate an alert when it matches. fastpath].3.equal • != . ! △NOTE The stream reassemble option is only available when the Stream5 preprocessor is enabled. as determined by the TCP sequence numbers.6.6.less than or equal • >= .11: Non-payload detection rule option keywords Keyword fragoffset ttl tos Description The fragoffset keyword allows one to compare the IP fragment offset field against a decimal value. established.not equal • <= . noalert][. 174 .21 stream reassemble The stream reassemble keyword allows a rule to enable or disable TCP stream reassembly on matching traffic. to disable TCP reassembly for client traffic when we see a HTTP 200 Ok Response message. content:"200 OK". • The optional fastpath parameter causes Snort to ignore the rest of the connection. <number>. Where the operator is one of the following: • < . <operator>. Format stream_size:<server|client|both|either>.<. <server|client|both>[. The tos keyword is used to check the IP TOS field for a specific value.6.greater than • = . Example For example.22 stream size The stream size keyword allows a rule to match traffic according to the number of bytes observed. The ttl keyword is used to check the IP time-to-live value. stream_reassemble:disable. ! △NOTE The stream size option is only available when the Stream5 preprocessor is enabled.) 3. use: alert tcp any 80 -> any any (flow:to_client.23 Non-Payload Detection Quick Reference Table 3. Format stream_reassemble:<enable|disable>.client.6.noalert.greater than or equal Example For example.less than • > . use: alert tcp any any -> any any (stream_size:client.) 3. to look for a session that is less that 6 bytes from the client side.
7. There are three available argument keywords for the session rule option: printable. The fragbits keyword is used to check if fragmentation and reserved bits are set in the IP header. The dsize keyword is used to test the packet payload size. The binary keyword prints out data in a binary format. ftp. The rpc keyword is used to check for a RPC application. or even web sessions is very useful. The icmp id keyword is used to check for a specific ICMP ID value. HTTP CGI scans. Format session:[printable|binary|all]. session:binary. The ipopts keyword is used to check if a specific IP option is present. The flow keyword allows rules to only apply to certain directions of the traffic flow. The icode keyword is used to check for a specific ICMP code value. The window keyword is used to check for a specific TCP window size. and procedure numbers in SUNRPC CALL requests. The flowbits keyword allows rules to track states during a transport protocol session. rlogin.) Given an FTP data session on port 12345. The printable keyword only prints out data that the user would normally see or be able to type. etc. this example logs the payload bytes in binary form. log tcp any any <> any 23 (session:printable. Format logto:"filename". The flags keyword is used to check if specific TCP flag bits are present. binary.1 logto The logto keyword tells Snort to log all packets that trigger this rule to a special output log file. The seq keyword is used to check for a specific TCP sequence number.) 175 . version. The itype keyword is used to check for a specific ICMP type value. The ip proto keyword allows checks against the IP protocol header.7. Example The following example logs all printable strings in a telnet packet. It should be noted that this option does not work when Snort is in binary logging mode. The icmp seq keyword is used to check for a specific ICMP sequence value.2 session The session keyword is built to extract user data from TCP Sessions. 3. This is especially handy for combining data from things like NMAP activity. The all keyword substitutes non-printable characters with their hexadecimal equivalents. log tcp any any <> any 12345 (metadata:service ftp-data. 3. There are many cases where seeing what users are typing in telnet. The ack keyword is used to check for a specific TCP acknowledge number.7 Post-Detection Rule Options 3. The sameip keyword allows rules to check if the source ip is the same as the destination IP. or all.
3 on how to use the tagged packet limit config option). See 2. • src .1.3 for details.1.> .Log packets in the session that set off the rule • host . flowbits:set.conf file (see Section 2.packets.0.Tag the host/session for <count> packets • seconds . <metric>[. and Stream reassembly will cause duplicate data when the reassembled packets are logged. but it is the responsibility of the output plugin to properly handle these special alerts.4 for details. 3. tagged alerts will be sent to the same output plugins as the original alert. Currently.seconds.7.11.1.1. described in Section 2.7.src.seconds.conf to 0).Tag the host/session for <count> seconds • bytes .tagged. tag:host.600. Units are specified in the <metric> field. does not properly handle tagged alerts. so it should not be used in heavy load situations. Format tag:<type>. 3. <count>.3 resp The resp keyword enables an active response that kills the offending session.1. the database output plugin. Note that neither subsequent alerts nor event filters will prevent a tagged packet from being logged. tag:host. type • session .Tag the host/session for <count> bytes direction .6. a tagged packet limit will be used to limit the number of tagged packets regardless of whether the seconds or bytes count has been reached.1 any (flowbits:isnotset. additional traffic involving the source and/or destination host is tagged.4 react The react keyword enables an active response that includes sending a web page or other content to the client and then closing the connection.) 176 .) alert tcp 10. Tagged traffic is logged to allow analysis of response codes and post-attack traffic. The binary keyword does not log any protocol headers below the application layer. Doing this will ensure that packets are tagged for the full amount of seconds or bytes and will not be cut off by the tagged packet limit. • dst . alert tcp any any <> 10.1. The session keyword is best suited for post-processing binary (pcap) log files.) Also note that if you have a tag option in a rule that uses a metric other than packets.1 any \ (content:"TAGMYPACKETS".only relevant if host type is used.Tag packets containing the destination IP address of the packet that generated the initial event.Warnings Using the session keyword can slow Snort down considerably. (Note that the tagged packet limit was introduced to avoid DoS situations on high bandwidth sensors for tag rules with a high seconds or bytes counts. Resp can be used in both passive or inline modes.5 tag The tag keyword allow rules to log more than just the single packet that triggered the rule.4 any -> 10.6.Tag packets containing the source IP address of the packet that generated the initial event. Once a rule is triggered.11. direction]. 3.600.1.tagged.src. React can be used in both passive and inline modes. See 2.7. metric • packets . Subsequent tagged alerts will cause the limit to reset.
after evaluating all other rule options (regardless of the position of the filter within the rule source).7.7. flow:established.9 replace The replace keyword is a feature available in inline mode which will cause Snort to replace the prior matching content with the given string. 3.1.100 any > 10.6 for more information.6 for more information. Snort evaluates a detection filter as the last step of the detection phase.this rule will fire on every failed login attempt from 10.100 during one sampling period of 60 seconds.2. See Section 3. Format activated_by:1.1.6 activates The activates keyword allows the rule writer to specify a rule to add when a specific network event occurs. 3.2. one per content. \ detection_filter:track by_src.100 22 ( \ msg:"SSH Brute Force Attempt".7.8 count The count keyword must be used in combination with the activated by keyword.12. 3. after the first 30 failed login attempts: drop tcp 10. 3.) 3.seconds.Example This example logs the first 10 seconds or the tagged packet limit (whichever comes first) of any telnet session. Format activates:1. Both the new string and the content it is to replace must have the same length.to_server. \ content:"SSH". Example . count:50. It allows the rule writer to specify how many packets to leave the rule enabled for after it is activated. See Section 3. See Section 3.2. You can have multiple replacements within a rule. alert tcp any any -> any 23 (flags:s.7.) 177 .1.1.10 detection filter detection filter defines a rate which must be exceeded by a source or destination host before a rule can generate an event. count 30. replace:"<string>".7 activated by The activated by keyword allows the rule writer to dynamically enable a rule when a specific activate rule is triggered. At most one detection filter is permitted per rule. tag:session.7. Format activated_by:1. offset:0. seconds <s>.6 for more information.10. \ sid:1000001. seconds 60.2. detection filter has the following format: detection_filter: \ track <by_src|by_dst>.2. \ count <c>. rev:1. depth:4. nocase.
8 Rule Thresholds ! △NOTE Rule thresholds are deprecated and will not be supported in a future release. or using a standalone threshold applied to the same rule. Some rules may only make sense with a threshold. This keyword allows the rule writer to specify a rule to add when a specific network event occurs. The session keyword is built to extract user data from TCP Sessions. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. threshold can be included as part of a rule. or you can use standalone thresholds that reference the generator and SID they are applied to. It makes sense that the threshold feature is an integral part of this rule. \ classtype:web-application-activity.10302. or event filters (2. Since potentially many events will be generated.txt access". 3.2) as standalone configurations instead. \ uricontent:"/robots.7. reference:nessus. seconds <s>. The resp keyword is used attempt to close sessions when an alert is triggered. The value must be nonzero. a detection filter would normally be used in conjunction with an event filter to reduce the number of logged events. There is a logical difference. Examples This rule logs the first event of this SID every 60 seconds.. This keyword allows the rule writer to dynamically enable a rule when a specific activate rule is triggered. a rule for detecting a too many login password attempts may require more than 5 attempts. This means count is maintained for each unique source IP address or each unique destination IP address. 3. Time period over which count is accrued. Track by source or destination IP address and if the rule otherwise matches more than the configured rate it will fire. nocase. \ count <c>.Option track by src|by dst count c seconds s Description Rate is tracked either by source IP address or destination IP address.txt". \ track <by_src|by_dst>. Format threshold: \ type <limit|threshold|both>. It allows the rule writer to specify how many packets to leave the rule enabled for after it is activated. track \ 178 .4. threshold:type limit. This can be done using the ‘limit’ type of threshold. The tag keyword allow rules to log more than just the single packet that triggered the rule. These should incorporate the threshold into the rule. The maximum number of rule matches in s seconds allowed before the detection filter limit to be exceeded.7.11 Post-Detection Quick Reference Table 3. For instance. Replace the prior matching content with the given string of the same length. established. C must be nonzero. Available in inline mode only. Use detection filters (3.10) within rules. This keyword must be used in combination with the activated by keyword. This keyword implements an ability for users to react to traffic that matches a Snort rule by closing connection and sending a notice. flow:to_server.
Type threshold alerts every m times we see this event during the time interval. to send the username.2 Catch the Vulnerability. c must be nonzero value. Selecting rules for evaluation via this ”fast” pattern matcher was found to increase performance. reference:nessus. Not the Exploit Try to write rules that target the vulnerability.10302. Ports or anything else are not tracked. especially when applied to large rule groups like HTTP. Type both alerts once per time interval after seeing m occurrences of the event. then ignores events for the rest of the time interval. instead of shellcode that binds a shell. then by ports (ip and icmp use slightly differnet logic).9. nocase. If at all possible. the less likely that rule and all of it’s rule options will be evaluated unnecessarily .9 Writing Good Rules There are some general concepts to keep in mind when developing Snort rules to maximize efficiency and speed. This means count is maintained for each unique source IP addresses. or for each unique destination IP addresses.txt". 3. icmp).3 Catch the Oddities of the Protocol in the Rule Many services typically send the commands in upper case letters. perform detection in the payload section of the packet. nocase. udp. seconds 60 . then ignores any additional events during the time interval. \ uricontent:"/robots. the client sends: user username_here A simple rule to look for FTP root login attempts could be: 179 .txt access". 3. established. FTP is a good example. rev:1.Option type limit|threshold|both track by src|by dst count c seconds s Description type limit alerts on the 1st m events during the time interval. seconds 60. or destination IP address. number of rule matching in s seconds that will cause event filter limit to be exceeded. instead of a specific exploit. \ uricontent:"/robots. rate is tracked either by source IP address. rev:1. Rules without content are always evaluated (relative to the protocol and port group in which they reside).10302. While some detection options. threshold:type both. sid:1000852. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. track \ by_dst. In FTP. a multi-pattern matcher is used to select rules that have a chance at matching based on a single content. reference:nessus. then by those with content and those without. The longer and more unique a content is. count 10 . \ track by_dst. For example. 3.) 3. \ classtype:web-application-activity. tcp. they are not used by the fast pattern matching engine. potentially putting a drag on performance. such as pcre and byte test. time period over which count is accrued. \ classtype:web-application-activity. By writing rules for the vulnerability. count 10. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. try and have at least one content (or uricontent) rule option in your rule. s must be nonzero value. flow:to_server. look for a the vulnerable command with an argument that is too large. threshold:type threshold.) This rule logs at most one event every 60 seconds if at least 10 events on this SID are fired.1 Content Matching Snort groups rules by protocol (ip.txt". sid:1000852.9. For rules with content. flow:to_server.it’s safe to say there is generally more ”good” traffic than ”bad”. established. the rule is less vulnerable to evasion when an attacker changes the exploit slightly.txt access".9.
because the first ”a” is not immediately followed by “b”. and because of recursion. looking for user.) While it may seem trivial to write a rule that looks for the username root. \ content:"root". ignoring case. take the following rule: alert ip any any -> any any (content:"a". dsize:1. By looking at this rule snippit. even though it is obvious that the payload “aab” has “a” immediately followed by “b”. • The rule has a content option. Reordering the rule options so that discrete checks (such as dsize) are moved to the beginning of the rule speed up Snort. the following rule options are not optimized: content:"|13|". Rules that are not properly written can cause Snort to waste time duplicating checks. the rule needs more smarts than a simple string match. a packet with 1024 bytes of 0x13 could cause 1023 too many pattern match attempts and 1023 too many dsize checks. it is obvious the rule looks for a packet with a single byte of 0x13. The optimized rule snipping would be: dsize:1. then look for the pattern again after where it was found the previous time. For example. then the dsize option would fail. However. because of recursion. content:"|13|". The following rule options are discrete and should generally be placed at the beginning of any rule: • dsize • flags • flow 180 . most unique string in the attack. 3.4 Optimizing Rules The content matching portion of the detection engine has recursion to handle a few evasion cases. For example. which is the longest. the content 0x13 would be found again starting after where the previous 0x13 was found.9. Repeat until the pattern is not found again or the opt functions all succeed. each of the following are accepted by most FTP servers: user root user root user root user root user<tab>root To handle all of the cases that the FTP server might handle. that may not sound like a smart idea. but it is needed. and if any of the detection options after that pattern fail. Without recursion. A packet of 1024 bytes of 0x13 would fail immediately.alert tcp any any -> any any 21 (content:"user root".) This rule would look for “a”.) There are a few important things to note in this rule: • The rule has a flow option.established. the payload “aab” would fail. followed by root. Why? The content 0x13 would be found in the first byte. • The rule has a pcre option. then check the dsize again. immediately followed by “b”. within:1. verifying this is traffic going to the server on an established session. For example. On first read. content:"b". a good rule will handle all of the odd things that the protocol might handle when accepting the user command. followed at least one space character (which includes tab). as the dsize check is the first option checked and dsize is a discrete check without recursion. once it is found. The way the recursion works now is if a pattern matches. While recursion is important for detection. pcre:"/user\s+root/i". A good rule that looks for root login on ftp would be: alert tcp any any -> any 21 (flow:to_server. This option is added to allow the fast pattern matcher to select this rule for evaluation only if the content root is found in the payload. the recursion implementation is not very smart. looking for root. repeating until 0x13 is not found in the payload again.
.. as RPC uses simple length based encoding for passing data......... • Strings are written as a uint32 specifying the length of the string.. the string..5 Testing Numerical Values The rule options byte test and byte jump were written to support writing rules for protocols that have length encoded data........../ . . The string “bob” would show up as 0x00000003626f6200. @(:.......... ....... Let’s break this up...@(:........../... and then null bytes to pad the length of the string to end on a 4 byte boundary......metasplo it.................. a random uint32........9.. .. describe each of the fields..• fragbits • icmp id • icmp seq • icode • id • ipopts • ip proto • itype • seq • session • tos • ttl • ack • window • resp • sameip 3.............. RPC was the protocol that spawned the requirement for these two rule options....system.. and figure out how to write a rule to catch this exploit...../............. unique to each request rpc type (call = 0..... . ....... 89 00 00 00 00 00 00 00 09 00 00 01 00 00 00 00 9c 00 00 87 00 00 00 00 e2 00 02 88 0a 01 01 20 the request id.metasplo it. .. ...... The number 26 would show up as 0x0000001a. taking four bytes.e./. let’s go through an exploit attempt against the sadmind service. ..... ...... .. ............ In order to understand why byte test and byte jump are useful....................... ....... 181 .... ........... There are a few things to note with RPC: • Numbers are written as uint32s.........../bin/sh........ ..........
within:4. content:"|00 00 00 00|". Then. depth:4. depth:4. and jump that many bytes forward. we use: byte_jump:4. content:"|00 00 00 01|".length of verifier (0. However. we need to make sure that our packet is an RPC call.36. content:"|00 01 87 88|". sadmind runs any request where the client’s uid is 0 as root. Then. depth:4. we need to make sure that our packet has auth unix credentials. content:"|00 01 87 88|". then we want to look for the uid of 0. aka none) . turn it into a number. but we want to skip over it and check a number value after the hostname. Now that we have all the detection capabilities for our rule. To do that in a Snort rule. content:"|00 00 00 01|". depth:4. we have decoded enough of the request to write our rule. making sure to account for the padding that RPC requires on strings. If we do that. offset:4. we need to make sure that our packet is a call to sadmind. offset:20. 36 bytes from the beginning of the packet. 182 .gid of requesting user (0) 00 00 00 00 . Starting at the length of the hostname.extra group ids (0) 00 00 00 00 00 00 00 00 .length of the client machine name (0x0a = 10) 4d 45 54 41 53 50 4c 4f 49 54 00 00 . In english. we need to make sure that our packet is a call to the procedure 1. offset:16. As such. offset. This is where byte test is useful. let’s put them all together. we are now at: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 which happens to be the exact location of the uid. Then. content:"|00 00 00 00|". content:"|00 00 00 01|". aligning on the 4 byte boundary. offset:16.unix timestamp (0x40283a10 = 1076378128 = feb 10 01:55:28 2004 gmt) 00 00 00 0a . we want to read 4 bytes. we know the vulnerability is that sadmind trusts the uid coming from the client. the value we want to check. within:4.verifier flavor (0 = auth\_null. First.uid of requesting user (0) 00 00 00 00 . content:"|00 00 00 01|". We don’t care about the hostname. aka none) The rest of the packet is the request that gets passed to procedure 1 of sadmind.36. the vulnerable procedure. depth:4. depth:4. offset:4. byte_jump:4. depth:4. offset:20. offset:12. and turn those 4 bytes into an integer and jump that many bytes forward.40 28 3a 10 . content:"|00 00 00 00|".align. content:"|00 00 00 00|". depth:4.metasploit 00 00 00 00 .align.
content:"|00 00 00 00|". 00 00 01|". To do that. offset:4. offset:12.align. turn it into a number. we would read 4 bytes. depth:4. so we should combine those patterns. within:4. content:"|00 00 00 01 00 byte_jump:4. offset:16. depth:4. content:"|00 01 87 88|".36. offset:12.The 3rd and fourth string match are right next to each other.>. depth:8. we would check the length of the hostname to make sure it is not too large.200. depth:8. we do: byte_test:4. byte_test:4. depth:4. 183 . instead of reading the length of the hostname and jumping that many bytes forward. We end up with: content:"|00 00 00 00|". content:"|00 00 00 01 00 00 00 01|".>. Our full rule would be: content:"|00 00 00 00|". starting 36 bytes into the packet. and then make sure it is not too large (let’s say bigger than 200 bytes). content:"|00 01 87 88|". offset:16.200. If the sadmind service was vulnerable to a buffer overflow when reading the client’s hostname.36.36. offset:4. In Snort. depth:4.
This includes functions to register the preprocessor’s configuration parsing. the version information. It includes function to log messages. and rules can now be developed as dynamically loadable module to snort. and it provides access to the normalized http and alternate data buffers. When enabled via the –enabledynamicplugin configure option. exit. The definition of each is defined in the following sections. Check the header file for the current definition. the dynamic API presents a means for loading dynamic libraries and allowing the module to utilize certain functions within the main snort code.1. fatal errors. 184 . but typically is limited to a single functionality such as a preprocessor.h as: #define MAX_NAME_LEN 1024 #define TYPE_ENGINE 0x01 #define TYPE_DETECTION 0x02 #define TYPE_PREPROCESSOR 0x04 typedef struct _DynamicPluginMeta { int type. int minor. and debugging info. access to the StreamAPI. and path to the shared library. It also includes information for setting alerts. It is defined in sf dynamic preprocessor. errors. This data structure should be initialized when the preprocessor shared library is loaded. and processing functions. char uniqueName[MAX_NAME_LEN].1 Data Structures A number of data structures are central to the API. } DynamicPluginMeta. rules. The remainder of this chapter will highlight the data structures and API functions used in developing preprocessors. handling Inline drops.1 DynamicPluginMeta The DynamicPluginMeta structure defines the type of dynamic module (preprocessor. detection capabilities.Chapter 4 Dynamic Modules Preprocessors.2 DynamicPreprocessorData The DynamicPreprocessorData structure defines the interface the preprocessor uses to interact with snort itself. restart.1. 4.h. int build. and rules as a dynamic plugin to snort. check the appropriate header files for the current definitions. It is defined in sf dynamic meta. Beware: the definitions herein may be out of date. or detection engine). 4. 4. char *libraryPath. int major. detection engines. A shared library can implement all three types.
3 DynamicEngineData The DynamicEngineData structure defines the interface a detection engine uses to interact with snort itself. 4. } DynamicEngineData. Additional data structures may be defined to reference other protocol fields. UriInfo *uriBuffers[MAX_URIINFOS]. RuleInformation info. int *debugMsgLine. GetPreprocRuleOptFuncs getPreprocOptFuncs. Rule The Rule structure defines the basic outline of a rule and contains the same set of information that is seen in a text rule. RuleOption **options. It and the data structures it incorporates are defined in sf snort packet.h. That includes protocol. LogMsgFunc fatalMsg. GetRuleData getRuleData. LogMsgFunc logMsg. errors. 4. DetectAsn1 asn1Detect. RegisterRule ruleRegister.1.1. #ifdef HAVE_WCHAR_H DebugWideMsgFunc debugWideMsg.h. generator and signature IDs. LogMsgFunc errMsg. classification. It is defined in sf dynamic engine. PCREExecFunc pcreExec. priority. PCRECompileFunc pcreCompile. CheckFlowbit flowbitCheck. /* NULL terminated array of RuleOption union */ ruleEvalFunc evalFunc.h as: typedef struct _DynamicEngineData { int version.4 SFSnortPacket The SFSnortPacket structure mirrors the snort Packet structure and provides access to all of the data contained in a given packet. The following structures are defined in sf snort plugin api. and a list of references). PCREStudyFunc pcreStudy. #endif char **debugMsgFile. and it provides access to the normalized http and alternate data buffers. Check the header file for the current definitions.4.1. revision. It also includes a list of rule options and an optional evaluation function. DebugMsgFunc debugMsg.5 Dynamic Rules A dynamic rule should use any of the following data structures. 185 . char *dataDumpDirectory. RegisterBit flowbitRegister. and debugging info as well as a means to register and check flowbits. u_int8_t *altBuffer. fatal errors. address and port information and rule information (classification. #define RULE_MATCH 1 #define RULE_NOMATCH 0 typedef struct _Rule { IPInfo ip. SetRuleData setRuleData. This includes functions for logging messages. It also includes a location to store rule-stubs for dynamic rules that are loaded.
#define #define #define #define #define #define #define ANY_NET HOME_NET EXTERNAL_NET ANY_PORT HTTP_SERVERS HTTP_PORTS SMTP_SERVERS "any" "$HOME_NET" "$EXTERNAL_NET" "any" "$HTTP_SERVERS" "$HTTP_PORTS" "$SMTP_SERVERS" 186 . char * src_port. priority. typedef struct _IPInfo { u_int8_t protocol. /* String format of classification name */ u_int32_t priority. /* NULL terminated array of references */ RuleMetaData **meta. RuleInformation The RuleInformation structure defines the meta data for a rule and includes generator ID. HTTP PORTS. char * dst_port. RuleReference The RuleReference structure defines a single rule reference. /* non-zero is bi-directional */ char * dst_addr. IPInfo The IPInfo structure defines the initial matching criteria for a rule and includes the protocol. message text. and direction. /* 0 for non TCP/UDP */ char direction. where the parameter is a pointer to the SFSnortPacket structure. /* } Rule.any. void *ruleData. destination address and port. signature ID. u_int32_t numOptions.char initialized. u_int32_t sigID. used internally */ /* Flag with no alert. char noAlert. revision. HOME NET. typedef struct _RuleInformation { u_int32_t genID. src address and port. RuleReference **references. used internally */ /* Rule option count. HTTP SERVERS. /* Rule Initialized. u_int32_t revision. including the system name and rereference identifier. char *message. typedef struct _RuleReference { char *systemName. Some of the standard strings and variables are predefined . char *refIdentifier. /* 0 for non TCP/UDP */ } IPInfo. /* NULL terminated array of references */ } RuleInformation. etc. char * src_addr. used internally */ Hash table for dynamic data pointers */ The rule evaluation function is defined as typedef int (*ruleEvalFunc)(void *). classification. char *classification. } RuleReference. and a list of references.
int32_t offset. FlowBitsInfo *flowBit. union { void *ptr. ByteData *byte. Boyer-Moore content information. PCREInfo *pcre. depth and offset. typedef struct _ContentInfo { u_int8_t *pattern. the one with the longest content length will be used. that which distinguishes this rule as a possible match to a packet. OPTION_TYPE_SET_CURSOR. } RuleOption. etc. the integer ID for a flowbit. The ”Not” flag is used to negate the results of evaluating that option. OPTION_TYPE_BYTE_EXTRACT. It includes the pattern. OPTION_TYPE_FLOWBIT. } option_u. typedef struct _RuleOption { int optionType. #define CONTENT_NOCASE #define CONTENT_RELATIVE #define CONTENT_UNICODE2BYTE 0x01 0x02 0x04 187 . URI or normalized – to search). Additional flags include nocase. OPTION_TYPE_PCRE. The most unique content. u_int8_t *patternByteForm. FlowFlags *flowFlags. ByteExtract *byteExtract. and a designation that this content is to be used for snorts fast pattern evaluation.RuleOption The RuleOption structure defines a single rule option as an option type and a reference to the data specific to that option. such as the compiled PCRE information. OPTION_TYPE_BYTE_TEST. Asn1Context *asn1. typedef enum DynamicOptionType { OPTION_TYPE_PREPROCESSOR. u_int32_t flags. OPTION_TYPE_MAX }. Each option has a flags field that contains specific flags for that option as well as a ”Not” flag. unicode. should be marked for fast pattern evaluation. if no ContentInfo structure in a given rules uses that flag. } ContentInfo. relative. OPTION_TYPE_HDR_CHECK. OPTION_TYPE_BYTE_JUMP. PreprocessorOption *preprocOpt. The option types and related structures are listed below. OPTION_TYPE_ASN1. u_int32_t incrementLength. OPTION_TYPE_LOOP. OPTION_TYPE_CURSOR. HdrOptCheck *hdrData. and flags (one of which must specify the buffer – raw. OPTION_TYPE_CONTENT. In the dynamic detection engine provided with Snort. #define NOT_FLAG 0x10000000 Some options also contain information that is initialized at run time. /* must include a CONTENT_BUF_X */ void *boyer_ptr. • OptionType: Content & Structure: ContentInfo The ContentInfo structure defines an option for a content search. ContentInfo *content. OPTION_TYPE_FLOWFLAGS. CursorInfo *cursor. u_int32_t depth. u_int32_t patternByteFormLength. LoopInfo *loop.
1 & Structure: Asn1Context The Asn1Context structure defines the information for an ASN1 option. void *compiled_extra. u_int32_t flags. to server).h. It includes the PCRE expression. /* pcre. as defined in PCRE. It includes the flags. established session. } FlowBitsInfo. and flags to specify the buffer. u_int32_t id. isnotset). u_int8_t operation. isset. toggle. pcre flags such as caseless. It mirrors the ASN1 rule option and also includes a flags field. Flags & Structure: FlowFlags The FlowFlags structure defines a flow option. unset. void *compiled_expr. It includes the name of the flowbit and the operation (set. etc. u_int32_t flags.h provides flags: PCRE_CASELESS PCRE_MULTILINE PCRE_DOTALL PCRE_EXTENDED PCRE_ANCHORED PCRE_DOLLAR_ENDONLY PCRE_UNGREEDY */ typedef struct _PCREInfo { char *expr. } FlowFlags. • OptionType: ASN. #define ASN1_ABS_OFFSET 1 188 . • OptionType: Flowbit & Structure: FlowBitsInfo The FlowBitsInfo structure defines a flowbits option. u_int32_t compile_flags. /* must include a CONTENT_BUF_X */ } PCREInfo..
¡. a value. • OptionType: Protocol Header & Structure: HdrOptCheck The HdrOptCheck structure defines an option to check a protocol header for a specific value.¿. u_int32_t flags. int offset. int double_overflow. Field to check */ Type of comparison */ Value to compare value against */ bits of value to ignore */ • OptionType: Byte Test & Structure: ByteData The ByteData structure defines the information for both ByteTest and ByteJump operations -. int length. similar to the isdataat rule option. multiplier. /* u_int32_t flags. The flags must specify the buffer. an operation (for ByteTest. a mask to ignore that part of the header field. /* u_int32_t op. } Asn1Context. /* u_int32_t value. unsigned int max_length. u_int32_t flags.etc). an offset. int print. and flags.=. It includes an offset and flags that specify the buffer. /* u_int32_t mask_value. It includes the header field. /* specify one of CONTENT_BUF_X */ } CursorInfo. int offset_type. as related to content and PCRE searches. The cursor is the current position within the evaluation buffer. #define #define #define #define #define #define #define #define #define CHECK_EQ CHECK_NEQ CHECK_LT CHECK_GT CHECK_LTE CHECK_GTE CHECK_AND CHECK_XOR CHECK_ALL 0 1 2 3 4 5 6 7 8 189 . typedef struct _CursorInfo { int32_t offset. • OptionType: Cursor Check & Structure: CursorInfo The CursorInfo structure defines an option for a cursor evaluation. a value. It includes the number of bytes.#define ASN1_REL_OFFSET 2 typedef struct _Asn1Context { int bs_overflow. -. as well as byte tests and byte jumps.=. } HdrOptCheck.etc). and flags. This can be used to verify there is sufficient data to continue evaluation.¿. the operation (¡.
/* /* /* /* /* /* * /* /*. It includes the number of bytes.2 Required Functions Each dynamic module must define a set of functions and data objects to work within this framework. /* reference ID (NULL if static) */ union { void *voidPtr. u_int32_t value. } ByteData. /* char *refId. a reference to a RuleInfo structure that defines the RuleOptions are to be evaluated through each iteration. It includes a cursor adjust that happens through each iteration of the loop. 4.#define CHECK_ATLEASTONE #define CHECK_NONE typedef struct _ByteData { u_int32_t bytes. int32_t offset. u_int32_t multiplier. struct _Rule *subRule. /* } ByteExtract. /* int32_t offset. /* void *memoryLocation. For a dynamic element. end. } DynamicElement. specifies * relative. /* Pointer to value of dynamic */ } data. DynamicElement *end. } LoopInfo.DynamicElement The LoopInfo structure defines the information for a set of options that are to be evaluated repeatedly. u_int8_t initialized. and a reference to the DynamicElement. One of those options may be a ByteExtract. an offset. #define DYNAMIC_TYPE_INT_STATIC 1 #define DYNAMIC_TYPE_INT_REF 2 typedef struct _DynamicElement { char dynamicType. • OptionType: Set Cursor & Structure: CursorInfo See Cursor Check above. typedef struct _LoopInfo { DynamicElement *start. or extracted value */ Offset from cursor */ Used for byte jump -. and increment values as well as the comparison operation for termination.. u_int32_t op. for checkValue.ByteExtract. u_int32_t flags. /* Value of static */ int32_t *dynamicInt. /* u_int32_t multiplier. flags specifying the buffer. 9 10 /* /* /* /* /* /* Number of bytes to extract */ Type of byte comparison. DynamicElement *increment. multiplier. for checkValue */ Value to compare value against. • OptionType: Loop & Structures: LoopInfo. /* type of this field . the value is filled by a related ByteExtract option that is part of the loop.32bits is MORE than enough */ must include a CONTENT_BUF_X */ • OptionType: Byte Jump & Structure: ByteData See Byte Test above. u_int32_t flags. 190 .static or reference */ char *refId. /* u_int32_t flags. It includes whether the element is static (an integer) or dynamic (extracted from a buffer in the packet) and the value. The loop option acts like a FOR loop and includes start. /* Holder */ int32_t staticInt. */ The ByteExtract structure defines the information to use when extracting bytes for a DynamicElement used a in Loop evaltion. typedef struct _ByteExtract { u_int32_t bytes. u_int32_t op.
as specified by ByteExtract and delimited by cursor. It handles bounds checking for the specified buffer and returns RULE NOMATCH if the cursor is moved out of bounds. • int ruleMatch(void *p. • int DumpRules(char *. u int8 t **cursor) This function adjusts the cursor as delimited by CursorInfo. • int InitializeEngineLib(DynamicEngineData *) This function initializes the data structure for use by the engine. u int8 t *cursor) This is a wrapper for extractValue() followed by checkValue(). – int setCursor(void *p. ByteData *byteData. Cursor position is updated and returned in *cursor. New cursor position is returned in *cursor. – int byteJump(void *p. as specified by FlowBitsInfo. With a text rule. etc). – int byteTest(void *p. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library. and register flowbits. – int checkValue(void *p.4. u int8 t **cursor) This is a wrapper for extractValue() followed by setCursor(). CursorInfo *cursorInfo. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library. – int detectAsn1(void *p. Each of the functions below returns RULE MATCH if the option matches based on the current criteria (cursor position. – int processFlowbits(void *p. dpd and invokes the setup function. ContentInfo* content. initialize it to setup content searches. u int8 t **cursor) This function evaluates a single content for a given packet. – int pcreMatch(void *p. u int8 t *cursor) This function compares the value to the value stored in ByteData. ByteData *byteData. – int contentMatch(void *p. byteJump. PCRE evalution data. and the distance option corresponds to offset. Cursor position is updated and returned in *cursor. u int8 t *cursor) This function evaluates an ASN.2.Rule **) This is the function to iterate through each rule in the list and write a rule-stop to be used by snort to control the action of the rule (alert. – int extractValue(void *p. checking for the existence of that content as delimited by ContentInfo and cursor. u int8 t **cursor) This function evaluates a single pcre for a given packet. It is also used by contentMatch. etc). • int RegisterRules(Rule **) This is the function to iterate through each rule in the list. checking for the existence of the expression as delimited by PCREInfo and cursor. FlowFlags *flowflags) This function evaluates the flow for a given packet. CursorInfo *cursorInfo. The metadata and setup function for the preprocessor should be defined sf preproc info. It will interact with flowbits used by text-based rules. • int InitializePreprocessor(DynamicPreprocessorData *) This function initializes the data structure for use by the preprocessor into a library global variable. FlowBitsInfo *flowbits) This function evaluates the flowbits for a given packet.c.1 Preprocessors Each dynamic preprocessor library must define the following functions. and pcreMatch to adjust the cursor position after a successful match. as delimited by Asn1Context and cursor. Value extracted is stored in ByteExtract memoryLocation parameter. u int8 t *cursor) This function validates that the cursor is within bounds of the specified buffer.h. 191 . u int32 t value. the with option corresponds to depth. Asn1Context *asn1. ByteExtract *byteExtract.1 check for a given packet. u int8 t *cursor) This function extracts the bytes from a given packet. 4. These are defined in the file sf dynamic preproc lib. Rule *rule) This is the function to evaluate a rule if the rule does not have its own Rule Evaluation Function. drop. log.2 Detection Engine Each dynamic detection engine library must define the following functions. – int checkCursor(void *p. The sample code provided with Snort predefines those functions and defines the following APIs to be used by a dynamic rules library. This uses the individual functions outlined below for each of the rule options and handles repetitive content issues. ByteData *byteData. PCREInfo *pcre.2. – int checkFlow(void *p.
3 Examples This section provides a simple example of a dynamic preprocessor and a dynamic rule. If you decide to write you own rule evaluation function. register flowbits. – void setTempCursor(u int8 t **temp cursor. • int DumpSkeletonRules() This functions writes out the rule-stubs for rules that are loaded. The remainder of the code is defined in spp example. This preprocessor always alerts on a Packet if the TCP port matches the one configured.h. • int EngineVersion(DynamicPluginMeta *) This function defines the version requirements for the corresponding detection engine library. as delimited by LoopInfo and cursor.3. Cursor position is updated and returned in *cursor. It should set up fast pattern-matcher content. ! △NOTE 4.h. HdrOptCheck *optData) This function evaluates the given packet’s protocol headers. 192 .2. • int InitializeDetection() This function registers each rule in the rules library. patterns that occur more than once may result in false negatives.c. u int8 t **cursor) This function is used to revert to a previously saved temporary cursor position. LoopInfo *loop.c and sf dynamic preproc lib. etc.so. Take extra care to handle this situation and search for the matched pattern again if subsequent rule options fail to match. The sample code provided with Snort predefines those functions and uses the following data within the dynamic rules library. This assumes the the files sf dynamic preproc lib. – void revertTempCursor(u int8 t **temp cursor. The metadata and setup function for the preprocessor should be defined in sfsnort dynamic detection lib.c into lib sfdynamic preprocessor example. Cursor position is updated and returned in *cursor. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library.1 Preprocessor Example The following is an example of a simple preprocessor.– int checkHdrOpt(void *p. – int loopEval(void *p. as specified by HdrOptCheck. defined in sf preproc info. u int8 t **cursor) This function iterates through the SubRule of LoopInfo. u int8 t **cursor) This function is used to handled repetitive contents to save off a cursor position temporarily to be reset at later point. This is the metadata for this preprocessor. Rules Each dynamic rules library must define the following functions.h are used. Examples are defined in the file sfnort dynamic detection lib. 4. 4.c and is compiled together with sf dynamic preproc lib. u int8 t **cursor) This function evaluates the preprocessor defined option. – int preprocOptionEval(void *p. PreprocessorOption *preprocOpt. • Rule *rules[] A NULL terminated list of Rule structures that this library defines. This should be done for both content and PCRE options. as spepcifed by PreprocessorOption.
void ExampleInit(unsigned char *args) { char *arg. void ExampleSetup() { _dpd. } The function to process the packet and log an alert if the either port matches. arg). arg)) { arg = strtok(NULL. } portToCheck = port. } Port: %d\n".logMsg(" } else { _dpd.logMsg("Example dynamic preprocessor configuration\n").). port). DEBUG_WRAP(_dpd. &argEnd. void *). _dpd. u_int16_t portToCheck.). _dpd. unsigned long port.conf.addPreproc(ExampleProcess. #define SRC_PORT_MATCH 1 #define SRC_PORT_MATCH_STR "example_preprocessor: src port match" #define DST_PORT_MATCH 2 #define DST_PORT_MATCH_STR "example_preprocessor: dest port match" void ExampleProcess(void *pkt. if(!strcasecmp("port". PRIORITY_TRANSPORT. 193 . "\t\n\r"). ExampleInit). Transport layer. } The initialization function to parse the keywords from snort. 10000). } /* Register the preprocessor function.fatalMsg("ExamplePreproc: Invalid port %d\n". return */ return. "Preprocessor: Example is setup\n"). char *argEnd. arg = strtok(args. void ExampleProcess(void *. if (!p->ip4_header || p->ip4_header->proto != IPPROTO_TCP || !p->tcp_header) { /* Not for me.debugMsg(DEBUG_PLUGIN. void *context) { SFSnortPacket *p = (SFSnortPacket *)pkt.fatalMsg("ExamplePreproc: Missing port\n"). portToCheck). if (!arg) { _dpd. if (port < 0 || port > 65535) { _dpd. } port = strtoul(arg. "Preprocessor: Example is initialized\n").#define GENERATOR_EXAMPLE 256 extern DynamicPreprocessorData _dpd. ID 10000 */ _dpd. " \t\n\r"). DEBUG_WRAP(_dpd.debugMsg(DEBUG_PLUGIN. 10). void ExampleInit(unsigned char *).registerPreproc("dynamic_example".fatalMsg("ExamplePreproc: Invalid option %s\n".
3. It is implemented to work with the detection engine provided with snort. DST_PORT_MATCH. \ content:"NetBus". Declaration of the data structures. } } 4. log alert */ _dpd. /*". 1. Search on the normalized buffer by default. static FlowFlags sid109flow = { FLOW_ESTABLISHED|FLOW_TO_CLIENT }.401.c.h. 0. SRC_PORT_MATCH. SRC_PORT_MATCH_STR. case sensitive. 0. rev:5. 194 . and non-relative. • Flow option Define the FlowFlags structure and its corresponding RuleOption. take from the current rule set.alertAdd(GENERATOR_EXAMPLE.if (p->src_port == portToCheck) { /* Source port matched. 0).alertAdd(GENERATOR_EXAMPLE. { &sid109flow } }. static RuleOption sid109option1 = { OPTION_TYPE_FLOWFLAGS. • Content Option Define the ContentInfo structure and its corresponding RuleOption. Per the text version. SID 109. flow is from server. content is ”NetBus”. return. 3. reference:arachnids. NOTE: This content will be used for the fast pattern matcher since it is the longest content option for this rule and no contents have a flag of CONTENT FAST PATTERN. flow:from_server.established.2 Rules The following is an example of a simple rule.established. defined in detection lib meta. 0).) This is the metadata for this rule library. return. } if (p->dst_port == portToCheck) { /* Destination port matched. \ sid:109. no depth or offset. Per the text version. classtype:misc-activity.3. log alert */ _dpd. DST_PORT_MATCH_STR. 1.
RuleOption *sid109options[] = { &sid109option1. NULL }. The rule itself. no alert. /* pattern to 0. used internally */ 195 . /* flags */ NULL. /* ptr to rule options */ NULL. static RuleOption sid109option2 = { OPTION_TYPE_CONTENT. used internally */ 0. /* proto */ HOME_NET. /* revision */ "misc-activity". /* Use internal eval func */ 0. used internally for flowbits */ NULL /* Holder.static ContentInfo sid109content = { "NetBus". /* offset */ CONTENT_BUF_NORMALIZED. static RuleReference sid109ref_arachnids = { "arachnids". Rule options are evaluated in the order specified. { &sid109content } }. /* Holder. message. sid109options. /* sigid */ 5. /* holder for 0. Rule sid109 = { /* protocol header. with the protocol header. /* Holder. rule data. NULL }. /* source IP */ "12345:12346". /* message */ sid109refs /* ptr to references */ }. /* Holder. used internally */ 0. /* priority */ "BACKDOOR netbus active". search for */ boyer/moore info */ byte representation of "NetBus" */ length of byte representation */ increment length */ The list of rule options. /* depth */ 0. /* destination IP */ ANY_PORT. not yet initialized. &sid109option2. static RuleReference *sid109refs[] = { &sid109ref_arachnids. akin to => tcp any any -> any any */ { IPPROTO_TCP.use 3 to distinguish a C rule */ 109. option count. classification. /* classification */ 0. meta data (sid. /* holder for NULL. /* Type */ "401" /* value */ }. /* metadata */ { 3. /* source port(s) */ 0. /* destination port */ }. /* Direction */ EXTERNAL_NET. /* genid -. /* holder for 0 /* holder for }. • Rule and Meta Data Define the references. etc).
flowbits. etc. &sid637. extern Rule sid637. The InitializeDetection iterates through each Rule in the list and initializes the content. pcre. extern Rule sid109. 196 . NULL }.• The List of rules defined by this rules library The NULL terminated list of rules. Rule *rules[] = { &sid109.
197 .2. Similarly. This is intended to help developers get a basic understanding of whats going on quickly. We’ve had problems in the past of people submitting patches only to the stable branch (since they are likely writing this stuff for their own IDS purposes).1 Submitting Patches Patches to Snort should be sent to the snort-devel@lists.2. We are currently cleaning house on the available output options. Each of the keyword options is a plugin. look at an existing output plugin and copy it to a new item and change a few things. 5. Features go into HEAD. Check out src/decode. Patches should done with the command diff -nu snort-orig snort-new. The detection engine checks each packet against the various options listed in the Snort config files. If you are going to be helping out with Snort development.2 Detection Plugins Basically. Packets are passed through a series of decoder routines that first fill out the packet structure for link level protocols then are further decoded for things like TCP and UDP ports. It can do this by checking: if (p->tcph==null) return.sourceforge. Bug fixes are what goes into STABLE. please use the HEAD branch of cvs.1 Preprocessors For example.3 Output Plugins Generally. new output plugins should go into the barnyard project rather than the Snort project. It will someday contain references on how to create new detection plugins and preprocessors. Packets are then sent through the registered set of preprocessors. Each preprocessor checks to see if this packet is something it should look at. there are a lot of packet flags available that can be used to mark a packet as “reassembled” or logged. 5.net mailing list. 5.Chapter 5 Snort Development Currently.2 Snort Data Flow First.h for the list of pkt * constants. Later. 5. traffic is acquired from the network link via libpcap. a TCP analysis preprocessor could simply return if the packet does not have a TCP header. 5. This allows this to be easily extensible. this chapter is here as a place holder.2. End users don’t really need to be reading this section. Packets are then sent through the detection engine. we’ll document what these few things are..5. 198 .
whitehats.org/snortdb [6] [5] 199 .incident.org [3] [2] [1] [4].
This action might not be possible to undo. Are you sure you want to continue? | https://www.scribd.com/doc/70508813/Snort-Manual | CC-MAIN-2015-48 | refinedweb | 57,754 | 60.72 |
Log audit events in Django
Project description
Django Audit Events
Extensible custom audit events for humans! This Django app allows you to easily create your own events in your project. Currently only works on PostgreSQL.
Let's have a look:
def awesome_view(request): foo_obj = Foo.objects.get(pk=1) # Do something with foo_obj... request.audit_context.create_event( foo_obj, something="done", bar="baz" )
This will create an audit event, including the request URL, logged-in user, remote IP address, and the following event content:
>>> event.content {"something": "done", "bar: "baz"}
For more information about installation and usage, check out the documentation!
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-audit-events/ | CC-MAIN-2020-05 | refinedweb | 126 | 50.23 |
KOffice 1.2beta2 is out, sporting an impressive number of changes, with improvements all around the board including substantial filter enhancements, footnotes in KWord, and templates in KSpread. "This release, which is available in
56
languages, includes
a frame-based, full-featured word processor
(KWord);
a presentation application;
(KPresenter);
a spreadsheet application;
(KSpread);
a flowchart application;
(Kivio);
business quality reporting software;
(Kugar);
and two vector-drawing applications (alpha)
(Kontour and
Karbon14).
Additionally, KOffice includes robust embeddable charts
(KChart)
and formulas
(KFormula)
as well as a built-in thesaurus (KThesaurus)
and numerous import and export
filters." Read the full announcement for details. Huge congrats to the KOffice team for their hard work and dedication, and kudos to Dre for writing the announcement. Wooo!
KOffice 1.2beta2 is Out!
KOffice 1.2beta2 is out, sporting an impressive number of changes, with improvements all around the board including substantial filter enhancements, footnotes in KWord, and templates in KSpread. "This release, which is available in
It's also been released to Fink unstable (no binary packages, those will be released with the upcoming KDE 3.0.2 release, doing lots of building right now =).
what causes the difference?
I doubt any of these languages is up-to-date yet as there was no message freeze before the beta was tagged.
FOOTNOTES ! yay! Finally, Kword is coming to the scientists....
Marc
Well neither the word *.doc filter nor the *.rtf filter import any footnotes at all.
Also the GUI for footnotes sucks, you have to configure EVERY SINGLE fottnote, instead of just entering it and changiong sensible defaults where appropriate. Well, that will hopefully be corrected. [HINT: Standard for Insert footnote should be autmatically numbering, nothing else!]
Well, I guess that's why it is a beta... :-)
Too bad and I was really looking forward to write a short paper with Kword :(
Marc
Huh? You don't have to configure every single footnote. Press Enter on the dialog that comes up when inserting a footnote - just like in e.g. openoffice (and probably other suites too).
The "configure" button in that dialog does bring up a GLOBAL footnote config dialog, where you can choose the type of numbering they should have etc.
Some footnotes can have a custom text (like (*) or (i)), and the other still have 1, 2, 3... that's why that's in the dialog for every footnote.
But pressing Enter does what you want, anyway.
> Well neither the word *.doc filter nor the *.rtf filter import any footnotes at all.
Well, one thing at a time. How could they do that before, since KWord didn't have footnotes at all? Now they _can_, as soon as someone makes them.
Yup, looks nice. A keyboard-shotcut without the menu and press an extra enter-key would be nice ;-) Is there an easy way to go back to the main text after entering the footnote?
Bye
Thorsten
You can always associate a shortcut with a menu item ("configure shortcuts"), but you'll still get the dialog of course.
Does any other word processor have a shortcut for inserting a footnote without showing the dialog?
For reference, openoffice and MSWord both show a similar 'small dialog' when doing Insert / Footnote.
In the impossible-to-figure-out Word shortcut dialog, there is an extra 'insert-footnote-automatically' (or something like that) that doesn't pop up the dialog. This doesn't appear anywhere outside of the shortcut dialog though, however it is very very useful. So just making another KAction with no dialog would be fine.
Jason
Ah, forgot to answer about jumping back. That's in the RMB menu (anywhere on the footnote frameset IIRC). No keyboard shortcut though - although here again "configure shortcuts" might even work for this action.
OK, maybe I was too fast in handing out judgement. I am normally using lyx and there entering a footnote means I start writing the footnote, not choosing the numbering type in my 20th footnote in a row. Why configure it at all? 90% of the time people want numbers.¹ If they don't, let those 10% go to the menue to configure the footnote.
This is the same concept as the starting dialog of kword, which I don't like either, even though I understand the rationale behind it.
I think the other post about a way to jump back and forth between text and footnote is insightful (clicking on the footnote number is used in OO.o I think).
Apart from the filters deficits kword looks excellent and is a speedy sob.
--
¹ Totally grabbed out of the air number.... :-)
Look at openoffice and msword - they both have that dialog when inserting a footnote.
I'm happy to remove it (and let it be accessible on RMB only), if that's what people want, though.
File a bug report...
Well neither the word *.doc filter nor the *.rtf filter import any footnotes at all.
I don't know what about beta2 but KWord from current CVS can import footnotes from RTF documents. I implemented it a few days ago.
More like anyone above 3rd grade
Sometimes I wonder about some scientists. They will know how to cure cancer soon, but how do I format that floppy disk again?
But if 3rd Graders can understand it then maybe there is hope for my supervisor !
Marc
Well, that's what they call 'division of labor'. For a top-notch cancer researcher it's just easier to give that floppy to one of his graduate students than to format it by himself. Nothing wrong with that. And who still uses floppies anyways?
> And who still uses floppies anyways?
Lots of people use floppies. For example, anyone trying to install an OS on a box without a CD drive, or without a BIOS that supports CD booting. Or, anyone who wants to get a few hundred kilobytes of data to an unnetworked box and doesn't want to waste time looking for a machine with a CD burner. Or, anyone with an old unnetworked box who wants to get data out of that machine and into something else. Or, someone wanting to set up a diskless terminal server system without an expensive bootrom writer. Floppies are great because they're expendible and universal. They aren't perfect, but they don't have to be.
Long live the floppy! :-)
You're begging the question. Who has a box without a CD drive? Or without a BIOS that supports CD booting? Or an unnetworked box?
I do. Next question? ;-)
I bought a 12 year old SparcStation IPC last weekend, and spent a night installing debian with 2 floppies. (the only 2 good ones I could find)
Its only 25mhz, but hell, I even got the BNC (thinnet) tranceiver working, and installed X4. ;)
Heh, kinda cool considering it only has a monochrome video card, and that I have to use mousekeys in X since the mouse it broke. Elephant 19" monitor though ;)
Cool, how does XFree86 perform on this machine?
Marc
What I miss the most is something on the line of endnote/reference manager for linux. Something that can download references from the web databases (such as), manage these references in one or many databases and format them in the document for a given journal. I would do it myself, but I lack both the time and expertise do build such a thing.
It would also be good to have embeded latex in koffice. You could use it to build complex symbols and equations in documents, legends in graphics, etc... Something like the TeX plugins for sketch.
BTW: Congrats for the LaTeX export filter! That is something I was craving for quite some time :)
Ever heard of pybliographic? Combined with LyX it's a dream.
It has pubmed searching and works very well with my 300 citations and lyx. It is of course bibtex based.
Yes, I know pybib and latex. But why not include something like that for koffice? A pybibliographer frontend, I belive, would be much apreciated.
It's just a naïve sugestion.
I know this is an old old thread, but hey.
OpenOffice does have the possiblity to create footnotes on the fly w/o the dialog (i mapped this to Ctrl-F in German Version of it (Choose->Tools->Customize->Keyboard->Insert->Footnote directly or sth like that), in EN use sth else as this is taken bei "Find/Replace")..
Also, jumping from text to footnote can be mapped in a similar way using "Navigation->To Anchor/Footnote" e.g. to Ctrl-J. Just highlight the fn you want to work on and hit it :)
To go back, use Pg-Up and that's it.
I think that's the way it should be, though in don't know how it's done in KWord, sorry. So this is a bit on the off-topic-side-of-things.
Cheers
Jeremias
Koffice beta2 is out.. great news! On the other side I simple ask:
are there people interested in development of kparts to link every
koffice applications (especially Kspread) with R (..from R-Project -)?
Could be great too.. have an app like SPSS or S-Plus.. or an external extension
to Kspread to do this.
Developers hurry up! R need a GUI.. and KDE/QT is perfectly for this! ;)
Rohan Sadler ([email protected]) posted this:
What I want to know is this: can anyone give me a quote on what it will
cost to develop a RWindows clone of the Minitab GUI. This GUI would
support initially the simple six (EDA, probabilities and quantiles of
distributions, t-tests,one-way anova, chi-square, and simple linear
regression), and have the potential to develop into the next level of
statistical analysis (glms, multivariate methods, time series and
spatial - analytical problems common across our faculty). If the cost of
development is comparable to present licence maintenance fees at FNAS
then I think our small group can argue for its adoption.
To the r-help mailing list. If anyone is interested in kludging up and supporting a simple GUI, on windows for money, email him, not me.
Cool! I'm a statistician student and actually we work with SPSS. I'm surprising
that universities pays a lot of money with fee and didn't realize a basic tool for this
purpose. R exists but is unusable from console; i think that a simple GUI could
solve a lot of problem and all the KDE apps could benefit of statistical models
and a stabilized-killerapp like R with script capabilities.
GNOME gui exists.. mmm well, if this could be called gui! Why not KDE?
I'm not a developer but i think that existing code is there for the other
R-gui project, how many time could be spent to do this KDE/Qt gui?
GNOME gui for R: blah..
Well.. look these:
Developers info:
Possibility:
GDAL - R bindings to Frank Warmerdam's Geospatial Data Abstraction Library
-
I am at work now, so I am anxious to get home and try out the new KOffice beta2. I do have a question though about KSpread. In 1.2beta1, I can't figure out how to center a spreadsheet on the page when priniting. I've looked in the page setup but can't seem to find it anywhere. This should be easy, but either it's not possible (which I can't believe since I consider this a basic feature) or I am a dummy and can't find it (most likely this option lol). At any rate, can someone tell me how this is done?
Congrats KOffice team on the new release, and thank you for continuing to give us a better office suite with each release.
Paul.....
I have added some more print functionality to KSpread, but couldn't finish all of what I wanted to in time.
Sorry, centerd output is on my list but wasn't ready when we encountered feature and message freeze. This has to wait for KO 1.3 :-/
Dito for "fit to nxm pages".
Thanks for the reply Phillip. At least now I know it's not something I was overlooking. Things are looking good though, and I appreciate all you guys work. Any suggestions of an easy workaround to get my sheets centered? Thanks again for all you guys hard work.
Paul.....
There is no direct way to center.
You can only do it manually either by adjusting the page borders or by a "dummy" column (no borders, white background). Yes, this is no fun and everything but professional.
But you should at least place a wish item in the buck tracking system, so you get informed when this function is in cvs.
...I'm still waiting for a decent SVG support.
How can I wait to user ksvg on kde 3.1 if I have to use a gnome app to create svg icons?
Karbon14 has svg export. It's not perfect but only bugreports and suggestions helps improve it.
And about import?
SVG import was already on the last beta, but I could not open any svg file, so I can't work directaly with svg files.
Functional RedHat RPMS can be found at. They're automated CVS builds, but I've installed them and preliminary testing shows that they seem to work okay.
Thank you Bero-Wan Kenobi. You're our only hope.
First impressions: way better than 1.1. Lack of true WYSIWYG turned me off to KWord until just now. It is a very welcome improvement. And not as crashy! That's always nice (maybe that was RedHat packaging). Import filters aren't perfect. There was no filter for the MIME type application/x-msword! I certainly hope that was packaging problem! The WP filter isn't pretty, but it's better than nothing. Excel filters are better but still not wonderful, but natively, it seems to work great. Then again, I'm not exactly pushing the limits yet. KWord and KSpread are all I need to be happy. Import/export filters are really my only complaint so far.
About filters, yes it could be really improved. However, we're lack of developers here. Reading format spec, coding the filter, testing, and stuff like take a quite amount of time. If you understand C++ and Qt/KDE and are willing to help, you're very welcomed. Documentation writers and QA people are also very valuable. At minimum, should you experienced bugs, please report to bugs.kde.org. And join us at [email protected]
I'm probably most qualified to file bugs and leave it at that. I'm an English major. I can read code within limits, though. Maybe I'll try to look at the filter code and see if it's dumb enough for me ;)
I do realize, though, that it's unfair to criticize a product due to its inability to correctly reverse-engineer a competitor's complicated and always-changing formula, when basically the competitor doesn't have to worry about reverse-engineering anything from anyone else and can just spend its time tweaking the formula to piss everyone off.
Nevertheless, filters remain KOffice's most noticeable shortcoming. Not that it's the end of the world. But it does mean two word processors for me. One to use personally, and another to open attachments from other people.
To make you happy: KSpread will get WYSIWYG in 1.3, too.
We didn't have the time to put it in this release.
About filter: I think enhancing the Excel filter is easier. So have fun with it :-)
We would like to hear from you :-)
> Import filters aren't perfect. There was no filter for the MIME type
> application/x-msword! I certainly hope that was packaging problem!
It seems that the input fiter is for application/msword instead of x-msword
Try to add a new mimetype application/msword and it should work.
Andrea
I suppose that all of these 'filters' are useful to some.
But, what I would really like is PostScript input.
I presume that this would need to use GhostScript.
--
JRT
Karbon14 has PS/EPS import by the way. The screeny at the bottom shows the
import of a "dynamic" PostScript file (with loops and rotations):
And yes, we use ghostscript and don't have our own ps-interpreter (yet). ;)
Dumb!
But, I can't figure out how to do that on 1.2Beta2.
So, I can't say if that will do what I need or not.
--
JRT
First: most postscript files work, but for example the famous tiger.eps doesn't work yet.
Second: it may help if you rename *.ps to *.eps. This needs to be fixed, that's right.
Ah, ok. Werner found a bug. Please check the next beta. | https://dot.kde.org/2002/06/27/koffice-12beta2-out | CC-MAIN-2022-40 | refinedweb | 2,806 | 75.3 |
1) Google App Engine RegistrationIf you have already registered yourself with GAE then skip this step otherwise just click on the link and register yourself for GAE.
You can create up to 10 applications. Click on the Create Application button to create a new application. The application Id that you choose have to available as it creates a sub-domain for the appspot.com with that name so that you can access your application later using http://{your_app_Id}.appspot.com
2) Setup Eclipse for Python programmingDepending on what your current setup is you may have to download one or more of the following, Python Interpreter, Eclipse, Java and PyDev plugin for Python Eclipse development. If you already have this setup done just skip over to the next step otherwise follow this link: Python beginner Tutorial using Eclipse PyDev Plugin
Important Note: The above tutorial downloads the Python 3.2 version, in your case download the Python 2.7 version as GAE currently doesn't support version 3.2
3) Download and Install Google App Engine SDK for PythonIn case of Windows you can use the native installer file GoogleAppEngine-1.7.2.msi. Here is the link
4) Hello World Project using EclipseCreate a new project in Eclipse. File -> New -> Project. Search for PyDev and Select PyDev Google App Engine Project
Set the project name to HelloWorld and select the option "Create 'src' folder and add it to PYTHONPATH?". Click Next...
Click on the Browse Button and point it to where Google App Engine is installed on your computer.
Specify the same Application Id that you created in your Step 1. You can change the Application Id of the Project later in the config file. Also choose the "Hello Webapp World" template to generate our sample project.
The project generates 2 files. app.yaml is the Python configuration file for running and deploying your application. For detailed information click here Python Application Configuration.
application: my-sample-code version: 1 runtime: python api_version: 1 handlers: - url: /.* script: helloworld.pyhelloworld.py is our Web Application. It just prints hello world on the web page.()
5) Run our Hello World Application LocallyRight click on the helloworld.py file -> Run As –> Run Configuration. Create a new PyDev Google App Run launch configuration and name it Run Python Hello World. Also specify the Main Module as dev_appserver.py
It is available under the GAE installed directory, you have to type the path for some reason the Browse functionality doesn't work.
In Arguments tab for the Program arguments specify ${project_loc}/src. Click Run.
The application will deploy to port 8080 on the localhost. You can access it by typing on the browser.
Tip: To change the port to say 8081, you have to specify that in your program arguments.
--port=8081 ${project_loc}/src
6) Modify our Hello World ApplicationThe default template created uses webapp. We are going to changes that to use webapp2. webapp2 is part of the Python 2.7 runtime since App Engine SDK 1.6.0. webapp2 is a simple. It follows the simplicity of webapp, but improves it in some ways: it adds better URI routing and exception handling, a full featured response object and a more flexible dispatching mechanism.
Copy the following source into your helloworld.py
import webapp2 class MainPage(webapp2.RequestHandler): def get(self): <div> <h2>Sample Hello World Application using GAE and Python</h2><br/> <input type="text" name="yourname" size="30" maxlength="30"></input> </div> <div> <input type="submit" value="Submit My Form"> </div> </form> </body> </html> """ self.response.out.write(myPage) class Hello(webapp2.RequestHandler): def post(self): yourname = self.request.get('yourname') self.response.out.write(""" <html> <body> <div> """) self.response.out.write("<h2>Hello World - " + yourname + "</h2>") self.response.out.write(""" </div> </body> </html> """) app = webapp2.WSGIApplication([('/', MainPage), ('/hello', Hello)], debug=True)Update you application configuration file app.yaml with the following code
application: my-sample-code version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /.* script: helloworld.app libraries: - name: webapp2 version: "2.5.1"There is no need to Run anything again. Just go the browser and hit refresh and you should see the changes to your application.
7) Deploy your application to Google App EngineRight click on the helloworld.py file -> Run As –> Run Configuration. Create a new PyDev Google App Run launch configuration and name it Deploy Python Hello World. Also specify the Main Module as appcfg.py
In Arguments tab for the Program arguments specify update ${project_loc}/src. Click Run.
During the process it will ask you for your credentials to Google App Engine. Keep an eye on the console and enter your Email Address and password.
06:02 PM Host: appengine.google.com 06:02 PM Application: my-sample-code; version: 1 06:02 PM Starting update of app: my-sample-code, version: 1 06:02 PM Getting current resource limits. Email: {enter email here} Password for {email}@gmail.com: {enter password here} 06:02 PM Scanning files on local disk. 06:02 PM Cloning 2 application files. 06:02 PM Uploading 2 files and blobs. 06:02 PM Uploaded 2 files and blobs 06:02 PM Compilation starting. 06:02 PM Compilation completed. 06:02 PM Starting deployment. 06:03 PM Checking if deployment succeeded. 06:03 PM Will check again in 1 seconds. 06:03 PM Checking if deployment succeeded. 06:03 PM Will check again in 2 seconds. 06:03 PM Checking if deployment succeeded. 06:03 PM Will check again in 4 seconds. 06:03 PM Checking if deployment succeeded. 06:03 PM Deployment successful. 06:03 PM Checking if updated app version is serving. 06:03 PM Will check again in 1 seconds. 06:03 PM Checking if updated app version is serving. 06:03 PM Will check again in 2 seconds. 06:03 PM Checking if updated app version is serving. 06:03 PM Will check again in 4 seconds. 06:03 PM Checking if updated app version is serving. 06:03 PM Completed update of app: my-sample-code, version: 1Your application is now deployed to http://{your_app_Id}.appspot.com
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing. | https://www.mysamplecode.com/2012/10/google-app-engine-python-tutorial-eclipse.html | CC-MAIN-2019-39 | refinedweb | 1,048 | 60.31 |
Created on 2009-07-17.08:02:03 by kargu2, last changed 2010-09-20.19:47:11 by zyasoft.
Calling iterator.hasNext() when iterating over a HashSet results in an
IllegalAccessError when running Jython 2.2.1 on IBM JDK 6 SR5 (32 bit
and 64 bit) on Linux. A short program to trigger the bug is pasted in below.
The same program is verified to work with Jython 2.2.1 on Sun JDK
1.6.0_14 and on IBM JDK 5 SR9-SSU.
The same program is verified to work with Jython 2.5.0 on all JDK:s above.
I.e: the bug seems only to affect Jython 2.2.1 and IBM JDK 6 SR5 (32 and
64 bit) on Linux.
Stack trace:
---
Traceback (innermost last):
File "bug.py", line 8, in ?
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:77)
at java.lang.reflect.Method.invoke(Method.java:590)
java.lang.IllegalAccessException: java.lang.IllegalAccessException:
Class org.python.core.PyReflectedFunction can not access a member of
class java.util.HashMap$AbstractMapIterator with modifiers "public"
---
Program to trigger the bug:
---
from java.lang import System
print System.getProperty("java.vendor")
from java.util import HashSet
s = HashSet()
s.add("a")
itr = s.iterator()
# Next line fails
itr.hasNext()
---
Hi kargu2,
Does the same error occur on Jython 2.5.0? If it does it would be a
helpful data point (and would greatly increase the priority of this bug)
Hi,
No, it does not occur on Jython 2.5.0. I tested the same program on the
same JDK:s, and it worked.
Thanks for the update re: 2.5.0 -- I'm going to put together a 2.2.2 in
the relatively near future -- this sounds like a blocker issue for that
release. Do you happen to know anyone at IBM that is involved with
Jython? I understand that WebSphere's admin scripting language is
Jython, and I had heard it was on Jython 2.2 -- maybe they have a fix?
I've marked this issue as urgent -- though it is not a problem for 2.5.
It is urgent for the upcoming 2.2.2 release.
No, unfortunately not. I don't know anyone at IBM.
2.2.x is no longer under active development. Please switch to 2.5.x.
Please see my recent blog post, which describes dev plans: | http://bugs.jython.org/issue1404 | CC-MAIN-2014-42 | refinedweb | 398 | 71.82 |
David, Add the following to stdafx.h: #define __VCBUILD__ or define __VCBUILD__ in the preprocessor directives. -----Original Message----- From: owner-sword-devel@crosswire.org [mailto:owner-sword-devel@crosswire.org]On Behalf Of dtrotzjr@arilion.com Sent: Tuesday, April 03, 2001 12:43 PM To: sword-devel@crosswire.org Subject: [sword-devel] Conflicts with class POSITION Hello all, Lastnight I began playing with the Sword libraries and MFC. I was seeing how I can get the two to communicate intelligently. I got the Sword.dll to compile fine. I could even link into the dll using a simple console application. But when I tried to link the Sword.dll to an application that uses MFC I got an error. I don't have the error here with me, but the error was from a conflict with the class POSITION. I could overcome it by renaming the class and every reference to it as SWPOSITION. Then it would compile and I could play around with it from there. My question is: Has anyone run into this error before and is there a workaround besides renaming the class POSITION? If not would it be possible to maybe place the entire Sword Class library in it's own namespace to keep from further name conflicts? I am still very new to C++ so I don't know if this is a valid fix, but I hate to have to rename every instance of the POSITION class each time I update my source code from the cvs. Any ideas and help would be greatly appreciated. In Christ, David Trotz | http://www.crosswire.org/pipermail/sword-devel/2001-April/011628.html | CC-MAIN-2013-20 | refinedweb | 265 | 67.65 |
Introduction a point where you want to run your application in a fashion that is closer to your production environment. Docker allows you to set up your application runtime in such a way that it runs in exactly the same manner as it will in production, on the same operating system, with the same environment variables, and any other configuration and setup you require.
By the end of the article you’ll be able to:
- Understand what Docker is and how it is used,
- Build a simple Python Django application, and
- Create a simple
Dockerfileto build a container running a Django web application server.
What is Docker, Anyway?
Docker’s homepage describes Docker as follows:
“Docker is an open platform for building, shipping and running distributed applications. It gives programmers, development teams, and operations engineers the common toolbox they need to take advantage of the distributed and networked nature of modern applications.”
Put simply, Docker gives you the ability to run your applications within a controlled environment, known as a container, built according to the instructions you define. A container leverages your machines resources much like a traditional virtual machine (VM). However, containers differ greatly from traditional virtual machines in terms of system resources. Traditional virtual machines operate using Hypervisors, which manage the virtualization of the underlying hardware to the VM. This means they are large in terms of system requirements.
Containers operate on a shared Linux operating system base and add simple instructions on top to execute and run your application or process. The difference being that Docker doesn’t require the often time-consuming process of installing an entire OS to a virtual machine such as VirtualBox or VMWare. Once Docker is installed, you create a container with a few commands and then execute your applications on it via the
Dockerfile. Docker manages the majority of the operating system virtualization for you, so you can get on with writing applications and shipping them as you require in the container you have built. Furthermore, Dockerfiles can be shared for others to build containers and extend the instructions within them by basing their container image on top of an existing one. The containers are also highly portable and will run in the same manner regardless of the host OS they are executed on. Portability is a massive plus side of Docker.
Prerequisites
Before you begin this tutorial, ensure the following is installed to your system:
- Python 2.7 or 3.x,
- Docker (Mac users: it’s recommended to use docker-machine, available via Homebrew-Cask), and
- A git repository to store your project and track changes.
Setting Up a Django web application
Starting a Django application is easy, as the Django dependency provides you with a command line tool for starting a project and generating some of the files and directory structure for you. To start, create a new folder that will house the Django application and move into that directory.
$ mkdir project $ cd project
Once in this folder, you need to add the standard Python project dependencies file which is usually named
requirements.txt, and add the Django and Gunicorn dependency to it. Gunicorn is a production standard web server, which will be used later in the article. Once you have created and added the dependencies, the file should look like this:
$ cat requirements.txt Django==1.9.4 gunicorn==19.6.0
With the Django dependency added, you can then install Django using the following command:
$ pip install -r requirements.txt
Once installed, you will find that you now have access to the
django-admin command line tool, which you can use to generate the project files and directory structure needed for the simple “Hello, World!” application.
$ django-admin startproject helloworld
Let’s take a look at the project structure the tool has just created for you:
. ├── helloworld │ ├── helloworld │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ └── manage.py └── requirements.txt
You can read more about the structure of Django on the official website.
django-admin tool has created a skeleton application. You control the application for development purposes using the
manage.py file, which allows you to start the development test web server for example:
$ cd helloworld $ python manage.py runserver
The other key file of note is the
urls.py, which specifies what URL’s route to which view. Right now, you will only have the default admin URL which we won’t be using in this tutorial. Lets add a URL that will route to a view returning the classic phrase “Hello, World!”.
First, create a new file called
views.py in the same directory as
urls.py with the following content:
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world!")
Now, add the following URL
url(r'', 'helloworld.views.index') to the
urls.py, which will route the base URL of
/ to our new view. The contents of the
urls.py file should now look as follows:
from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', 'helloworld.views.index'), ]
Now, when you execute the
python manage.py runserver command and visit in your browser, you should see the newly added “Hello, World!” view.
The final part of our project setup is making use of the Gunicorn web server. This web server is robust and built to handle production levels of traffic, whereas the included development server of Django is more for testing purposes on your local machine only. Once you have dockerized the application, you will want to start up the server using Gunicorn. This is much simpler if you write a small startup script for Docker to execute. With that in mind, let’s add a
start.sh bash script to the root of the project, that will start our application using Gunicorn.
#!/bin/bash # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn helloworld.wsgi:application \ --bind 0.0.0.0:8000 \ --workers 3
The first part of the script writes “Starting Gunicorn” to the command line to show us that it is starting execution. The next part of the script actually launches Gunicorn. You use
exec here so that the execution of the command takes over the shell script, meaning that when the Gunicorn process ends so will the script, which is what we want here.
You then pass the
gunicorn command with the first argument of
helloworld.wsgi:application. This is a reference to the
wsgi file Django generated for us and is a Web Server Gateway Interface file which is the Python standard for web applications and servers. Without delving too much into WSGI, the file simply defines the
application variable, and Gunicorn knows how to interact with the object to start the web server.
You then pass two flags to the command,
bind to attach the running server to port 8000, which you will use to communicate with the running web server via HTTP. Finally, you specify
workers which are the number of threads that will handle the requests coming into your application. Gunicorn recommends this value to be set at
(2 x $num_cores) + 1. You can read more on configuration of Gunicorn in their documentation.
Finally, make the script executable, and then test if it works by changing directory into the project folder
helloworld and executing the script as shown here. If everything is working fine, you should see similar output to the one below, be able to visit in your browser, and get the “Hello, World!” response.
$ chmod +x start.sh $ cd helloworld $ ../start.sh Starting Gunicorn. [2016-06-26 19:43:28 +0100] [82248] [INFO] Starting gunicorn 19.6.0 [2016-06-26 19:43:28 +0100] [82248] [INFO] Listening at: (82248) [2016-06-26 19:43:28 +0100] [82248] [INFO] Using worker: sync [2016-06-26 19:43:28 +0100] [82251] [INFO] Booting worker with pid: 82251 [2016-06-26 19:43:28 +0100] [82252] [INFO] Booting worker with pid: 82252 [2016-06-26 19:43:29 +0100] [82253] [INFO] Booting worker with pid: 82253
Dockerizing the Application
You now have a simple web application that is ready to be deployed. So far, you have been using the built-in development web server that Django ships with the web framework it provides. It’s time to set up the project to run the application in Docker using a more robust web server that is built to handle production levels of traffic.
Installing Docker
One of the key goals of Docker is portability, and as such is able to be installed on a wide variety of operating systems.
For this tutorial, you will look at installing Docker Machine on MacOS. The simplest way to achieve this is via the Homebrew package manager. Instal Homebrew and run the following:
$ brew update && brew upgrade --all && brew cleanup && brew prune $ brew install docker-machine
With Docker Machine installed, you can use it to create some virtual machines and run Docker clients. You can run
docker-machine from your command line to see what options you have available. You’ll notice that the general idea of
docker-machine is to give you tools to create and manage Docker clients. This means you can easily spin up a virtual machine and use that to run whatever Docker containers you want or need on it.
You will now create a virtual machine based on VirtualBox that will be used to execute your
Dockerfile, which you will create shortly. The machine you create here should try to mimic the machine you intend to run your application on in production. This way, you should not see any differences or quirks in your running application neither locally nor in a deployed environment.
Create your Docker Machine using the following command:
$ docker-machine create development --driver virtualbox --virtualbox-disk-size "5000" --virtualbox-cpu-count 2 --virtualbox-memory "4096"
This will create your machine and output useful information on completion. The machine will be created with 5GB hard disk, 2 CPU’s and 4GB of RAM.
To complete the setup, you need to add some environment variables to your terminal session to allow the Docker command to connect the machine you have just created. Handily,
docker-machine provides a simple way to generate the environment variables and add them to your session:
$ docker-machine env development export DOCKER_TLS_VERIFY="1" export DOCKER_HOST="tcp://123.456.78.910:1112" export DOCKER_CERT_PATH="/Users/me/.docker/machine/machines/development" export DOCKER_MACHINE_NAME="development" # Run this command to configure your shell: # eval "$(docker-machine env development)"
Complete the setup by executing the command at the end of the output:
$(docker-machine env development)
Execute the following command to ensure everything is working as expected.
$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE
You can now dockerize your Python application and get it running using the
docker-machine.
Writing the Dockerfile
The next stage is to add a
Dockerfile to your project. This will allow Docker to build the image it will execute on the Docker Machine you just created. Writing a
Dockerfile is rather straightforward and has many elements that can be reused and/or found on the web. Docker provides a lot of the functions that you will require to build your image. If you need to do something more custom on your project, Dockerfiles are flexible enough for you to do so.
The structure of a
Dockerfile can be considered a series of instructions on how to build your container/image. For example, the vast majority of Dockerfiles will begin by referencing a base image provided by Docker. Typically, this will be a plain vanilla image of the latest Ubuntu release or other Linux OS of choice. From there, you can set up directory structures, environment variables, download dependencies, and many other standard system tasks before finally executing the process which will run your web application.
Start the
Dockerfile by creating an empty file named
Dockerfile in the root of your project. Then, add the first line to the
Dockerfile that instructs which base image to build upon. You can create your own base image and use that for your containers, which can be beneficial in a department with many teams wanting to deploy their applications in the same way.
# Dockerfile # FROM directive instructing base image to build upon FROM python:2-onbuild
It’s worth noting that we are using a base image that has been created specifically to handle Python 2.X applications and a set of instructions that will run automatically before the rest of your
Dockerfile. This base image will copy your project to
/usr/src/app, copy your requirements.txt and execute
pip install against it. With these tasks taken care of for you, your
Dockerfile can then prepare to actually run your application.
Next, you can copy the
start.sh script written earlier to a path that will be available to you in the container to be executed later in the
Dockerfile to start your server.
# COPY startup script into known file location in container COPY start.sh /start.sh
Your server will run on port 8000. Therefore, your container must be set up to allow access to this port so that you can communicate to your running server over HTTP. To do this, use the
EXPOSE directive to make the port available:
# EXPOSE port 8000 to allow communication to/from server EXPOSE 8000
The final part of your
Dockerfile is to execute the start script added earlier, which will leave your web server running on port 8000 waiting to take requests over HTTP. You can execute this script using the
CMD directive.
# CMD specifcies the command to execute to start the server running. CMD ["/start.sh"] # done!
With all this in place, your final
Dockerfile should look something like this:
# Dockerfile # FROM directive instructing base image to build upon FROM python:2-onbuild # COPY startup script into known file location in container COPY start.sh /start.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD specifcies the command to execute to start the server running. CMD ["/start.sh"] # done!
You are now ready to build the container image, and then run it to see it all working together.
Building and Running the Container
Building the container is very straight forward once you have Docker and Docker Machine on your system. The following command will look for your
Dockerfile and download all the necessary layers required to get your container image running. Afterwards, it will run the instructions in the
Dockerfile and leave you with a container that is ready to start.
To build your container, you will use the
docker build command and provide a tag or a name for the container, so you can reference it later when you want to run it. The final part of the command tells Docker which directory to build from.
$ cd
$ docker build -t davidsale/dockerizing-python-django-app . Sending build context to Docker daemon 237.6 kB Step 1 : FROM python:2-onbuild # Executing 3 build triggers... Step 1 : COPY requirements.txt /usr/src/app/ ---> Using cache Step 1 : RUN pip install --no-cache-dir -r requirements.txt ---> Using cache Step 1 : COPY . /usr/src/app ---> 68be8680cbc4 Removing intermediate container 75ed646abcb6 Step 2 : COPY start.sh /start.sh ---> 9ef8e82c8897 Removing intermediate container fa73f966fcad Step 3 : EXPOSE 8000 ---> Running in 14c752364595 ---> 967396108654 Removing intermediate container 14c752364595 Step 4 : WORKDIR helloworld ---> Running in 09aabb677b40 ---> 5d714ceea5af Removing intermediate container 09aabb677b40 Step 5 : CMD /start.sh ---> Running in 7f73e5127cbe ---> 420a16e0260f Removing intermediate container 7f73e5127cbe Successfully built 420a16e0260f
In the output, you can see Docker processing each one of your commands before outputting that the build of the container is complete. It will give you a unique ID for the container, which can also be used in commands alongside the tag.
The final step is to run the container you have just built using Docker:
$ docker run -it -p 8000:8000 davidsale/djangoapp1 Starting Gunicorn. [2016-06-26 19:24:11 +0000] [1] [INFO] Starting gunicorn 19.6.0 [2016-06-26 19:24:11 +0000] [1] [INFO] Listening at: (1) [2016-06-26 19:24:11 +0000] [1] [INFO] Using worker: sync [2016-06-26 19:24:11 +0000] [11] [INFO] Booting worker with pid: 11 [2016-06-26 19:24:11 +0000] [12] [INFO] Booting worker with pid: 12 [2016-06-26 19:24:11 +0000] [17] [INFO] Booting worker with pid: 17
The command tells Docker to run the container and forward the exposed port 8000 to port 8000 on your local machine. After you run this command, you should be able to visit in your browser to see the “Hello, World!” response. If you were running on a Linux machine, that would be the case. However, if running on MacOS, then you will need to forward the ports from VirtualBox, which is the driver we use in this tutorial so that they are accessible on your host machine.
$ VBoxManage controlvm "development" natpf1 "tcp-port8000,tcp,,8000,,8000";
This command modifies the configuration of the virtual machine created using
docker-machine earlier to forward port 8000 to your host machine. You can run this command multiple times changing the values for any other ports you require.
Once you have done this, visit in your browser. You should be able to visit your dockerized Python Django application running on a Gunicorn web server, ready to take thousands of requests a second and ready to be deployed on virtually any OS on planet using Docker.
Next Steps
After manually verifying that the application is behaving as expected in Docker, the next step is the deployment. You can use Semaphore’s Docker platform for automating this process.
Continuous Integration and Deployment for Docker projects on Semaphore
As a first step you need to create a free Semaphore account. Then, connect your Docker project repository to your new account. Semaphore will recognize that you’re using Docker, and will automatically recommend the Docker platform for it.
The last step is to specify commands to build and run your Docker images:
docker build
. docker run
Semaphore will execute these commands on every
git push.
Semaphore also makes it easy to push your images to various Docker container registries. To learn more about getting the most out of Docker on Semaphore, check out our Docker documentation pages.
Conclusion
In this tutorial, you have learned how to build a simple Python Django web application, wrap it in a production grade web server, and created a Docker container to execute your web server process.
If you enjoyed working through this article, feel free to share it and if you have any questions or comments leave them in the section below. We will do our best to answer them, or point you in the right direction.
Read next: | https://semaphoreci.com/community/tutorials/dockerizing-a-python-django-web-application | CC-MAIN-2019-47 | refinedweb | 3,139 | 53.21 |
I.
Changes:.
Here is a simple PoC exploit for the issue fixed here:
class Union1 { }class Union2 { }class arraytoctou { static volatile Union1 u1 = new Union1(); public static void main(String[] args) { final Union1[] arr1 = new Union1[1]; final Union2[] arr2 = new Union2[1]; new Thread() { public void run() { for(;;) { try { System.arraycopy(arr1, 0, arr2, 0, 1); if (arr2[0] != null) break; } catch (Exception _) { } } } }.start(); while (arr2[0] == null) { arr1[0] = null; arr1[0] = u1; } System.out.println(arr2[0]); }}
The first release candidate is available. It can be downloaded here or from NuGet.
What's New (relative to IKVM.NET 7.3):
Changes since previous development snapshot:
Binaries available here: ikvmbin-7.4.5196.0.zip
Sources: ikvmsrc-7.4.5196.0.zip, openjdk-7u40-b34-stripped.zip
Hopefully the last snapshot before the 7.4 release candidate.
Binaries available here:
ikvmbin-7.4.5178.zip
I was at FOSDEM last weekend and was reminded that I hadn't released any IKVM.NET updates in a while. So lets try to get back on the wagon.
Binaries available here: ikvmbin-7.4.5148.zip
I tweeted
a while ago about an OpenJDK vulnerability that was
reported on one of the
mailing lists.
Now that it has been fixed in 7u51, here is a simple PoC exploit:
import java.lang.invoke.*;
class test extends java.io.FileOutputStream {
static test t;
test() throws Exception {
super("");
}
protected void finalize() {
t = this;
}
public static void main(String[] args) throws Throwable {
MethodHandle mh = MethodHandles.lookup().findVirtual(test.class, "open",
MethodType.methodType(void.class, String.class, boolean.class));
System.out.println(mh);
try { new test(); } catch (Exception _) { }
System.gc();
System.runFinalization();
mh.invokeExact(t, "oops.txt", false);
}
}
Run this with a security manager enabled on a version earlier than 7u51 and it'll
create the file oops.txt, even though the code doesn't have the rights to do so. | http://weblog.ikvm.net/default.aspx?date=2014-05-20 | CC-MAIN-2018-26 | refinedweb | 317 | 60.82 |
Basics of SQL Server 2008 Locking
WEBINAR:
On-Demand
Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js
Introduction
Locking and transaction support is essential in any relational database supporting multiple users. Microsoft SQL Server has provided both of these features from the very beginning, and they are present even in the latest 2008 version. Even if you have used SQL Server before, there are slight differences in these features compared to earlier SQL Server versions. These differences might cause changed behavior in your own applications.
This article looks at the basics of locking features in SQL Server 2008, and peeks into the inner workings to learn how SQL Server implements locking. The examples are taken from SQL Server 2008, which is nowadays a common version. Note that the latest Windows Server 2008 and Windows 7 installations suggest installing SQL Server Service Pack 1 to ensure good compatibility. Some of the information presented in this article applies to earlier versions of SQL Server as well. Thus, even if you haven't yet migrated to or started using SQL Server 2008 in your development work, you can still learn how locking works in SQL Server's previous versions, especially in version 2005.
Understanding Concurrency Control Options
You are probably familiar at least with the concept of both. However, SQL Server is a complex product, and thus both transaction isolation levels and locking have dozens of different options that will affect the way your applications behave when multiple users use the same database objects simultaneously. Depending on the options selected and the order of events occurring (read, then write, or the other way around), different operations are done by the database server.
Concurrency control is usually divided into two broad categories: pessimistic and optimistic concurrency control. Shortly put, pessimistic concurrency assumes that multiple users will try to update the same rows often, and thus locking is used to control the order in which updates succeed and which will have to wait.
On the other hand, optimistic concurrency can be said to assume the opposite: updates to the same database objects (table rows in particular) are few, and thus an error message on the client is enough to handle the situation when a second user tries to update the same object.
Of course, these are only the broad lines. To understand concurrency control and locking in detail, it's best to start with a quick overview of transaction isolation levels in SQL Server 2008.
Briefly About Transaction Isolation Levels
SQL Server 2008 (Figure 1) supports five transaction isolation levels, each of which is part of the SQL standard from 1992. The main idea of different isolation levels is to control how other users (technically, other transactions) see modifications (inserts, updates and deletes) from other transactions. In addition, they specify how locks are being held, which in turn affects performance: how many users can read and write the same database objects at the same time.
Figure 1. SQL Server 2008 supports five different transaction isolation modes
The isolation levels supported by SQL Server 2008 are named READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SNAPSHOT, and SERIALIZABLE. The READ UNCOMMITTED is the least restricted level, and allows reading changes made by other transactions, even if those changes have not yet been committed. The other end of the spectrum is SNAPSHOT, which specifies that a transaction can only read committed data that existed when the transaction started. No chances will be visible during the lifetime of a transaction using the snapshot isolation.
The transaction isolation level can be set using T-SQL statements, but more commonly, it is set using the class libraries used by the application code. For instance when using the ADO.NET SqlConnection class (in the
System.Data.SqlClient namespace), you can use the
BeginTransaction method to specify which isolation level you want to use. The
IsolationLevel enumeration is used to specify the preferred option, and it defaults to
ReadCommitted. This corresponds to the database engine level
READ COMMITTED.
There are no comments yet. Be the first to comment! | https://www.codeguru.com/cpp/data/mfc_database/sqlserver/article.php/c17219/Basics-of-SQL-Server-2008-Locking.htm | CC-MAIN-2018-13 | refinedweb | 681 | 50.77 |
This page describes details of the statistics shown in the Cloud Datastore Dashboard.
Viewing the statistics
View statistics for your application's data in the Cloud Datastore Dashboard.
Go to the Cloud Datastore Dashboard page
Types of statistics
The Dashboard page displays data in various ways:
A pie chart that shows space used by each property type, such as string, double, or blob.
A pie chart showing space used by entity kind.
A table with the total space used by each property type. The "Metadata" property type represents space consumed by storing properties inside an entry that is not used by the properties directly. The "Datastore Stats" entity, if any, shows the space consumed by the statistics data itself in your database.
A table showing total size, average size, entry count, and the size of all entities, and the built-in and composite indexes.
By default, the pie charts display statistics for all entities. You can restrict the pie charts to a particular entity kind by choosing from the drop-down menu.
Storage limitations for statistics
The statistics data is stored in your application's Cloud Datastore instance. The space consumed by the statistics data increases in proportion to the number of different entity kinds and property types used by your application. If you use namespaces, each namespace contains a complete copy of the stats for that namespace. To keep the overhead of storing and updating the statistics reasonable, the database progressively drops statistics entities.
For details on statistics data and how Cloud Datastore progressively drops statistics entities, see Datastore Statistics. | https://cloud.google.com/appengine/docs/standard/python/console/datastore-statistics?hl=ru | CC-MAIN-2019-30 | refinedweb | 261 | 54.12 |
Sometimes Erlang programmers are worried “Elixir variables may be the source of hidden bugs”. This article discusses those concerns and shows how variables in Erlang can produce related “hidden bugs”, some of those eliminated by Elixir.
Before we start, a short disclaimer: Elixir does not have mutable variables, it has rebinding. Mutability is often associated with storage. In Elixir, the values being stored cannot be changed (same as in Erlang). For an example of mutable variables, we could look at F#. In F# explicitly using the
mutable keyword (e.g.
let mutable x = 5) would allow us to change a value inside an inner loop (equivalent to a list comprehension or inside
Enum.map) and observe the change after the loop is over. That is mutability, and that is not possible in Elixir or Erlang without using explicit storage like processes or ETS.
Back on track. This article will explore the potential for hidden bugs when changing code. Those bugs exist because both Erlang and Elixir variables provide implicit behaviour. Elixir rebinds implicitly, Erlang pattern matches implicitly. Such bugs may show up if developers add or remove variables without being mindful of its context.
Let’s see some examples. Imagine the following Elixir code:
foo_bar = ... # some code use_foo_bar(foo_bar)
What happens if you introduce
foo_bar before the snippet above?
foo_bar = ... # newly added line foo_bar = ... # some code use_foo_bar(foo_bar)
The code would work just as fine and the compiler would even warn if the newly added
foo_bar is unused. What would happen, however, if the new line is introduced after the
foo_bar definition?
foo_bar = ... # some code foo_bar = ... # newly added line use_foo_bar(foo_bar)
The semantics may have potentially changed if you wanted
use_foo_bar to use the first
foo_bar variable. Indeed, careless change may cause bugs.
Let’s check Erlang. Given the code:
FooBar = ... % some code use_foo_bar(FooBar)
What happens if you introduce
FooBar before its definition?
FooBar = ... % newly added line FooBar = ... % old line errors % some code use_foo_bar(FooBar)
The Erlang code crashes at runtime instead of silently continuing. Certainly an improvement, but it still means that introducing a variable in Erlang requires us to certify the variable is not matched later on, as
FooBar will no longer be assigned to but matched on.
What happens if we introduce it after its definition?
FooBar = ... % some code FooBar = ... % newly added line and it errors use_foo_bar(FooBar)
This time, the new line crashes. In other words, due to implicit matching in Erlang, we not only need to worry about all the code after introducing a variable, but we also need to be mindful of all the code before introducing it, as any previous code can cause future variables to become implicit matches.
In other words, so far Elixir requires you to be mindful of all later code after the introduction of a variable while Erlang requires you to know all previous and further code before the introduction of a variable. The one benefit of Erlang so far is that the code may crash explicitly on the match.
However, things get more complicated when considering case expressions.
Case
Let’s say you want to match on a new value inside a case. In Elixir you would write:
case some_expr() do {:ok, safe_value} -> perform_something_safe() _ -> perform_something_unsafe() end
What would happen if you accidentally introduce a
safe_value variable in Elixir before that case statement?
safe_value = ... # newly added line # some code case some_expr() do {:ok, safe_value} -> perform_something_safe() _ -> perform_something_unsafe() end
Nothing, the code works just fine due to rebinding.
Let’s see what happens in Erlang:
case some_expr() of {ok, SafeValue} -> perform_something_safe(); _ -> perform_something_unsafe() end
And what happens when you introduce a variable?
SafeValue = ... % newly added line % some code case some_expr() of {ok, SafeValue} -> perform_something_safe(); _ -> perform_something_unsafe() end
You have just silently introduced a potentially dangerous bug in your code! Again, because Erlang implicitly matches, we may now accidentaly perform an unsafe operation as the first clause no longer binds to
SafeValue but it will match against it.
Similar bug happens in Erlang when you are matching on an existing variable and you remove it. Imagine you have this working Elixir code:
safe_value = ... # some code case some_expr() do {:ok, ^safe_value} -> perform_something_safe() _ -> perform_something_unsafe() end
Because Elixir explicitly matches, if you remove the definition of
safe_value, the code won’t even compile. Let’s see the working version of the Erlang one:
SafeValue = ... % some code case some_expr() of {ok, SafeValue} -> perform_something_safe(); _ -> perform_something_unsafe() end
If you remove the
SafeValue variable, the first clause will now bind to
SafeValue instead of matching, silently changing the behaviour of the code once again! Again, another bug while the Elixir approach has shielded us on both cases.
At this point, Elixir:
- requires you to analyse all the following code when introducing a variable, failing to do so may cause bugs
- matching on a variable is always safe due to rebinding and the use of
^for explicit match
while Erlang:
- requires you to analyse all the previous and further code when introducing a variable to be sure it is a match or an assignment, failing to do so will cause runtime crashes
- requires you to analyse all the following code when introducing a variable to be sure we won’t change a later case semantics, failing to do so may cause bugs
- requires you to analyse all the following code when removing a variable to be sure we won’t change a later case semantics, failing to do so may cause bugs
Numbered variables
At the beginning, we have mentioned someone may introduce a new variable
foo_bar in the Elixir code and change the code semantics if the variable was already used later on. However, most of those cases are desired. For example, in Elixir:
foo_bar = step1() foo_bar = step2(foo_bar) foo_bar = step3(foo_bar) # some code use_foo_bar(foo_bar)
In Erlang:
FooBar0 = step1(), FooBar1 = step2(FooBar0), FooBar2 = step3(FooBar1), % some code use_foo_bar(FooBar2)
Now what happens if we want to introduce a new version of
foo_bar (
step_4) in Elixir?
foo_bar = step1() foo_bar = step2(foo_bar) foo_bar = step3(foo_bar) foo_bar = step4(foo_bar) # newly added line # some code use_foo_bar(foo_bar)
The code just works. What about Erlang?
FooBar0 = step1(), FooBar1 = step2(FooBar0), FooBar2 = step3(FooBar1), FooBar3 = step4(FooBar2), % some code use_foo_bar(FooBar2) % All FooBar2 must be changed
If the developer introduces a new variable and forgets to change
FooBar2 later on, the code semantics changed, introducing the same bug rebinding in Elixir would. This is particularly troubling if you change all but miss one variable, since the code won’t emit “unused variable” warnings. This is even more prone to errors when adding an intermediate step (say between
step2 and
step3).
Some will say that a benefit of numbered variables is that further code could use any of
FooBar2 and
FooBar3, for example:
FooBar0 = step1(), FooBar1 = step2(FooBar0), FooBar2 = step3(FooBar1), FooBar3 = step4(FooBar2), % some code use_foo_bar(FooBar2), something_else(FooBar3)
However I would consider the code above to be a poor practice because there is nothing in the name
FooBar2 that hints to why it is different than
FooBar3. In this case, the variable names would not reflect at all why part of the code would prefer to use one over the other. Your team will be much better off by giving explicit names instead of versioned ones.
Summing up
Because both Elixir and Erlang variables provide implicit behaviour, rebinding and pattern matching respectively, both require care when adding or removing variables to existing code. Therefore, if Elixir can be source of hidden bugs, we have shown Erlang is the source of similar bugs under different situations. Not only that, Erlang requires both previous and further knowledge of the context when introducing new variables while Elixir requires only further knowledge. The only way to circumvent those bugs in both languages is by either forbidding or explicitly providing both rebinding and pattern match operations, which none of the languages do.
It is possible some will react to this article by saying: “this does not happen in my code”. The truth is that it does happen, even in small functions:
-
-
-
On the other hand, it does not mean writing code in Erlang or Elixir is going to lead to more bugs in your software. After all, Erlang developers have been writing robust software for decades. Those “quirks” exist in any language and they end-up internalized by programmers as they get experienced. That’s exactly from where the “this does not happen in my code” comes from.
At the end of the day, no language will guarantee you can safely change code without caring about its context. There will always be “hidden bugs”. For example, in languages like Clojure, JavaScript and Ruby, variables and function names exist in the same namespace, so introducing variables may change the semantics of function calls. Since both Erlang and Elixir provide two namespaces, one for variables and another for functions, they are shielded from these particular “hidden bugs”.
Furthermore, type systems, compiler warnings, test suites are all techniques that help solve those problems. Languages may also provide patterns, like the Elixir pipe operator (
|>), to help to convert repetitive code into more readable and less error-prone versions.
At least, I hope this puts to rest the claim that Elixir variables are somehow unsafer than Erlang ones (or vice-versa).
Thanks to Joe Armstrong, Saša Juric, James Fish, Chris McCord, Bryan Hunter, Sean Cribbs and Anthony Ramine for reviewing this article and providing feedback. | http://blog.plataformatec.com.br/2016/01/comparing-elixir-and-erlang-variables/?utm_source=elixirdigest&utm_medium=web&utm_campaign=featured | CC-MAIN-2019-39 | refinedweb | 1,567 | 59.84 |
One of the many benefits offered by .NET Core over its predecessor (the older .NET Framework) is the way it handles configuration. I wrote about the capabilities of .NET Core configuration back when the new framework was still prerelease and using a different name (see ASP .NET 5 Application Configuration, Part 1 and Part 2), and although some APIs may have changed, most of it should still be relevant today.
It is easy to set up application settings with this recent configuration model. However, when it comes to actually deploying an application into different environments (e.g. development, staging, production, and possibly others), things become complicated. How do we maintain configurations for all these environments, and how do we save ourselves from the tedious and error-prone practice of manually tweaking individual settings on all these different servers? How do we make sure we don’t lose these settings outright if a server experiences a technical failure? These challenges have nothing to do with the configuration model itself, as they are a more general administrative burden.
One option is to use something like Octopus Deploy to store settings for different environments and transform a settings file (such as appsettings.json) at deployment time. However, not everybody has this luxury. In this article, we will see how we can manage configurations for multiple environments using features that .NET Core offers out of the box.
At the time of writing this article, .NET Core 3.1.1 is the latest version.
Stacking Configurations in .NET Core
The .NET Core configuration libraries allow you to combine application settings from different sources, even if these are of different types (e.g. JSON, XML, environment variables, etc). Imagine I have these two JSON files, named appsettings1.json and appsettings2.json:
{ "ApplicationName": "Some fancy app", "Timeout": 5000 }
{ "Timeout": 3000, "ConnectionString": "some connection string" }
In order to read these files, I’ll need to install the following package:
dotnet add package Microsoft.Extensions.Configuration.Json
We can then use the
ConfigurationBuilder to read in both files, combine them, and give us back an
IConfigurationRoot object that allows the application code to query the settings that were read:
using System; using Microsoft.Extensions.Configuration; namespace netcoreconf1 { class Program { static void Main(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile("appsettings1.json") .AddJsonFile("appsettings2.json") .Build(); Console.WriteLine("Application Name: " + config["ApplicationName"]); Console.WriteLine("Timeout: " + config["Timeout"]); Console.WriteLine("Connection String " + config["ConnectionString"]); Console.ReadLine(); } } }
After ensuring that the two JSON files are set to copy to the output directory on build, we can run the simple application to see the result:
The Application Name setting comes from the first JSON file, while the Connection String setting comes from the second. The Timeout setting, on the other hand, exists in both files, but the value was obtained from the second JSON file. In fact, the order in which configuration sources are read is important, and by design, settings read from later sources will overwrite the same settings read from earlier sources.
It follows from this that if we have some variable that defines which environment (e.g. Production) we’re in, then we can do something like this:
const string environment = "Production"; var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{environment}.json", optional: true) .Build();
In this case we have a core JSON file with the settings that tend to be common across environments, and then we have one or more JSON files specific to the environment that we’re running in, such as appsettings.Development.json or appsettings.Production.json. The settings in the environment-specific JSON file will overwrite those in the core appsettings.json file.
You will notice that we have that
optional: true parameter for the environment-specific JSON file. This means that if that file is not found, the
ConfigurationBuilder will simply ignore it instead of throwing an exception. This is the default behaviour in ASP .NET Core, which we will explore in the next section. It is debatable whether this is a good idea, because it may be perfectly reasonable to prefer the application to crash rather than run with incorrect configuration settings.
Multiple Environments in ASP .NET Core Using Visual Studio
By default, ASP .NET Core web applications use this same mechanism to combine a core appsettings.json file with an environment-specific appsettings.Environment.json file.
In the previous section we used a constant to supply the name of the current environment. Instead, ASP .NET Core uses an environment variable named
ASPNETCORE_ENVIRONMENT to determine the environment.
Let’s create an ASP .NET Core Web API using Visual Studio and run it to see this in action:
Somehow, ASP .NET Core figured out that we’re using the Development environment without us setting anything up. How does it know?
You’ll find the answer in the launchSettings.json file (under Properties in Solution Explorer), which defines the aforementioned environment variable when the application is run either directly or using IIS Express. You’ll also find that there are already separate appsettings.json and appsettings.Development.json files where you can put your settings.
If you remove this environment variable and re-run the application, you’ll find that the default environment is Production.
On the other hand, if we add a different appsettings.Staging.json, and update the environment variable to Staging, then we can run locally while pointing to the Staging environment:
Naturally, connecting locally to different environments isn’t something you should take lightly. Make sure you know what you’re doing, as you can do some real damage on production environments. On the other hand, there are times when this may be necessary, so it is a simple and powerful technique. Just be careful.
“With great power comes great responsibility.”— Uncle Ben, Spider-Man (2002)
Multiple Environments in Console Apps
While ASP .NET Core handles the configuration plumbing for us, we do not have this luxury in other types of applications. Console apps, for instance those built to run as Windows Services using Topshelf, will need to have this behaviour as part of their code.
In a new console application, we will first need to add the relevant NuGet package:
dotnet add package Microsoft.Extensions.Configuration.Json
Then we can set up a
ConfigurationBuilder to read JSON configuration files using the same stacked approach described earlier:
var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{environment}.json") .Build();
We can read the
environment from the same
ASPNETCORE_ENVIRONMENT environment variable that ASP .NET Core looks for. This way, if we have several applications on a server, they can all determine the environment from the same machine-wide setting.
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (environment != null) { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{environment}.json") .Build(); // TODO application logic goes here } else { Console.WriteLine("Fatal error: environment not found!"); Environment.Exit(-1); }
If we run the application now, we will get that fatal error. That’s because we haven’t actually set up the environment variable yet. See .NET Core Tools Telemetry for instructions on how to permanently set an environment variable on Windows or Linux. Avoid doing this via a terminal or command line window since that setting would only apply to that particular window. I’m doing this in the screenshot below only as a quick demonstration, since I don’t need to maintain this application.
Deploying an ASP .NET Core Web Application to a Windows Server
When developing applications locally, we have a lot of tools that make our lives easy thanks to whichever IDE we use (e.g. Visual Studio or Visual Studio Code). Deploying to a server is different, because we need to set everything up ourselves.
The first thing to do is install .NET Core on the machine. Download the ASP .NET Core Hosting Bundle as shown in the screenshot below. This includes the Runtime (which allows you to run an .exe built with .NET Core) and the ASP .NET Core Module v2 for IIS (which enables you to host ASP .NET Core web applications in IIS). However, it does not include the SDK, so you will not be able to use any of the command-line
dotnet tools, and even
dotnet --version will not let you know whether it is set up correctly.
Next, we can set up a couple of system environment variables:
The first is
ASPNETCORE_ENVIRONMENT which has already been explained ad nauseam earlier in this article. The second is
DOTNET_CLI_TELEMETRY_OPTOUT (see .NET Core Tools Telemetry), which can optionally be used to avoid sending usage data to Microsoft since this behaviour is turned on by default.
Another optional preparation step that applies to web applications is to add health checks. This simply means exposing an unprotected endpoint which returns something like “OK”. It is useful to check whether you can reach the web application at a basic level (while eliminating complexities such as authentication), and it can also be used by load balancers to monitor the health of applications. This can be implemented either directly in code, or using ASP .NET Core’s own health checks feature.
Finally, you really should set up logging to file, and log the environment as soon as the application starts. Since ASP .NET Core does not have a file logger out of the box, you can use third party libraries such as NLog or Serilog. Like this, if the application picks up the wrong environment, you can realise very quickly. The log files will also help you monitor the health of your application and troubleshoot issues. Use tools such as baretail to monitor logs locally on the server, or ship them to a central store where you can analyse them in more detail.
With everything prepared, we can publish our web application:
dotnet publish -c Release -r win10-x64
All that is left is to copy the files over to the server (compressing and decompressing them in the process) and run the application.
The above screenshot shows the deployed ASP .NET Core web application running, serving requests, and picking up the correct configuration. All this works despite not having the .NET Core SDK installed, because it is not required simply to run applications.
Deploying an ASP .NET Core Web Application to IIS
In order to host an ASP .NET Core web application in IIS, the instructions in the previous section apply, but there are a few more things to do.
First, if the server does not already have IIS, then it needs to be installed. This can be done by going to:
- Server Manager
- Add roles and features
- Select Web Server (IIS) as shown in the screenshot below.
- Click Add Features in the modal that comes up.
- Install
In IIS, make sure you have the AspNetCoreModuleV2 module, by clicking on the machine node in the Connections panel (left) and then double-clicking Modules. If you installed IIS after having installed the ASP .NET Core Hosting Bundle, you will need to run the latter installer again (just hit Repair).
Next, go into IIS and set up a website, with the path pointing to the directory where you put the web application’s published files:
Start your website, and then visit the test endpoint. Since you don’t have a console window when running under IIS, the log files come in really handy. We can use them to check that we are loading configuration for the right environment just as before:
It’s working great, and it seems like from .NET Core 3+, it even logs the hosting environment automatically so you don’t need to do that yourself.
Troubleshooting
When running under IIS, an ASP .NET Core application needs a web.config file just like any other. While I’ve had to add this manually in the past, it seems like they are now being created automatically when you publish. If, for any reason, you’re missing a web.config file, you can grab the example in the docs.
I ran into a problem with an IIS-hosted application under .NET Core 2.2 where the environment variable defining the hosting environment wasn’t being picked up correctly by ASP .NET Core. As a workaround, it is actually possible to set environment variables directly in web.config, and they will be passed by IIS to the hosted application.
On the other hand, when running .NET Core applications under Linux, keep in mind that files are case sensitive. Andrew Lock has written about a problem he ran into because of this.
Summary
In this article, we have seen that the old way of transforming config files is no longer necessary. By stacking configuration files, we can have a core appsettings.json file whose settings is overwritten by other environment-specific JSON files.
This setup is done automatically in ASP .NET Core applications, using the
ASPNETCORE_ENVIRONMENT environment variable to determine the current environment. In other types of apps, we can read the same environment variable manually to achieve the same effect. Under Visual Studio, this environment variable can easily be changed in launchsettings.json to work under different environments, as long as the necessary level of care is taken.
Deployment of ASP .NET Core applications requires the .NET Core Runtime to be installed on the target server. The ASP .NET Core Hosting Bundle includes this as well as support for hosting ASP .NET Core applications under IIS. The SDK is not required unless the
dotnet command-line tools need to be used on the server.
Before deploying, the server should also have the right environment variables, and the application should be fitted with mechanisms to easily check that it is working properly (such as an open endpoint and log files). | https://gigi.nullneuron.net/gigilabs/tag/appsettings/ | CC-MAIN-2021-31 | refinedweb | 2,284 | 57.67 |
When is it Constitutional to Have Bible Study and Prayer in Schools?
Freedom of Religion is Protected by the First Amendment
Bill of Rights Summary
Review of the First Ammendment
Freedom of Religion in the First Ammendment
The first ten amendments to the constitution are known as the Bill of Rights. The Bill of Rights prohibits Congress from encroaching on the basic human rights of the American people. One of the rights protected in the first amendment is freedom of religion. More specifically, the first amendment prevents congress from encroaching on the people’s freedom of religion. The clause that protects this freedom is known as the establishment clause., “Congress shall make no law respecting an establishment of religion” is known as the Establishment Clause.
Explanation of Due Proccess
Applying the First Amendment to All Levels of Government
While the establishment clause protects the American people from having their rights encroached upon by the federal government, it does not provide the same protection from state or local government. This protection is offered by the due process clause in the fourteenth amendment.
The first section of the fourteenth ammendment portion of this section that states, “No state shall make or enforce any law which shall abridge the privileges or immunities of citizens of the United States;” is known as the Due Process Clause. This clause means that unless someone is charged with, tried for and convicted of a crime that merits a punishment that infringes on one’s basic human rights, no level of government can make a law regarding the establishment of religion or prohibiting free exercise of religion.
Public Schools are Government Agencies
Public schools are funded with tax funds and are government agencies. This means that school practices and procedures are subject to the establishment and due process clauses. As a governmental agency, a school cannot make rules that establishes or prohibits religion or the free practice thereof.
As long as no public funds are used to promote religion, charter and private schools can apply religious principles and lessons to their curriculum as they want. Charter and private schools are not held to the same expectations because enrollment in them is optional.
Separation of Church and State
- U.S. Supreme Court Decisions on Separation of Church and State
A well-written, concise history of all supreme court cases regarding separation of church and state.
To What Extent Must Church and State Be Separate?
Everson v. Board of Education
The first noteworthy case was brought before the Supreme Court in 1946. In this case, Mr. Everson claimed that it was unconstitutional for a New Jersey law that allowed parents who sent their children to school on buses operated by the public transport system to include the parents who sent their children to Catholic schools. The court ruled that this did.
Can the School Sponsor Released Time Religious Studies?
McCollum v. Board of Education Dist. 71
The next case was heard in 1947. The Champaign Public School district held optional religion classes during a portion of the school day. Students could opt out if they so desired. Those that opted out spent the time studying non-religious topics.
Vashti McCollum, whose daughter attended school in the district, brought a case against the school district stating that the released time religious classes were unconstitutional because the district was involved in funding and planning the released time and its religious functions. She was concerned that not all religious groups were getting the same time as the predominate sect. She also claimed that while the district called the sessions optional, they were not optional in practice because of the ridicule and pressure the students were subjected to if they didn’t willingly attend the sessions.
The court ruled in McCollum’s favor, 8-1. It was decided that it was unconstitutional for government to encourage, promote or aid religious education.
Do Conversations of How to Pray and Bible Study Belong in the Classroom?
Engel v. Vitale
In 1962, a case was brought by New York families against their state board of regents, who required a prayer they had composed to be recited by the children daily. The families claimed the prayer violated their religious beliefs. The composed prayer reads: "Almighty God, we acknowledge our dependence upon Thee, and we beg Thy blessings upon us, our parents, our teachers and our country. Amen." The court ruled in favor of the families objecting to the composed prayer and declared that composed prayers promoted a specific religion which was unconstitutional by the establishment clause as it applied to the states through the due process clause in the 14th amendment.
Abington School District v. Schempp and Murray v. Curlett
Abington School District v. Schempp concerned mandatory bible reading in public schools in Pennsylvania. At the beginning of the day students were required to listen to or help read 10 bible verses, without comment, before beginning the studies of the day. This case was heard with Murray v. Curlett, which was brought by an atheist and challenged a Baltimore statute that required that students read a chapter from the Christian Holy Bible and/or the Lord’s Prayer, without comment, every day.
Justice Clark wrote the majority opinion and explained that while religion was of great importance in American history, the constitution forbade it to be promoted by governmental agencies. He continued to say that prayer is a form of religion and that it, as well as mandated bible reading, was thus unconstitutional
Wallace v. Jaffree
An Alabama law permitted teachers to set aside one minute at the beginning of the day for silent meditation or voluntary prayer. Ishmael Jaffree, whose children attended school in Mobile County, Alabama, claimed that this minute was an attempt to encourage prayers in school. He also claimed that teachers used this time to indoctrinate his children and to lead class-wide public prayers even after several requests for the practice to be stopped. The court agreed that prayers in schools were unconstitutional.
These three cases suggest that the Supreme Court has ruled prayer and scripture study in the public classroom unconstitutional.
The Three Pronged Measuring Stick
Lemon v. Kurtzman
In 1971, the case of Lemon v. Kurtzman was brought before the Supreme Court. The issues at hand involved whether or not “making state financial aid available to church-related educational institutions” was constitutional. The Supreme Court responded with a three part test that could be used to determine if a law violated the establishment clause or not. This test has been used to make a decision on several additional cases since 1971.
In order to be permissible under the constitution, a statute must:
- “have a secular legislative purpose”
- “have principal effects which neither advance nor inhibit religion”
- “not foster an excessive government entanglement with religion”
The third leg of the test was deemed necessary because a noticeable bit of follow up on the usage of the public funds by the Catholic school would be necessary. The court worried that this follow up may interfere with the function of the school and the role of religion in the school. As a result, the third leg of the test was adopted in order to protect the private schools and ensure they could freely teach what they wanted to.
Creationism versus Evolution is an Age Old Debate that Continues Today
Creationism and Evolution
Epperson v. Arkansas
Appellant Epperson, a teacher, brought this case to the Supreme Court for relief from Arkansas’s state “anti-evolution” statute. The clause prohibited any state funded school from teaching, or using a textbook that taught, that humans ascended or descended from a lower order of animals. The court ruled in favor of the teacher. Because the sole reason for the law was because a religious group considers the evolution theory to conflict with their religious beliefs, which included the creation story found in the Book of Genesis, the court ruled that this statute was in direct conflict of the establishment clause
Edwards v. Aquillard
In this case, which was argued in 1986, a Louisiana law that required that evolution was only taught if creationism was also taught was declared unconstitutional. The Supreme Court decided that this law failed when judged against all three prongs of the test developed in Lemon v. Kurtzman in 1971.
Displays and Decorations
Stone v. Graham
In 1980, the Supreme Court ruled that a Kentucky statute that required that the 10 commandments to be posted in all classrooms was unconstitutional because it failed the “secular purpose” clause of the test derived in Lemon v. Kurtzman. This ruling was also monumental because it was the first case that tried the constitutionality of a passive practice.
In Summary:
It is constitutional:
- for patrons of religiously affiliated schools to receive governmental money when their counterparts in public schools receive this aid, so long as they meet the appropriate criteria and the money does not promote religion in any way.
It is not constitutional:
- for school districts or other governmental groups to be involved in planning or funding released time for religious education.
- for students to be required to recite a pre-composed prayer, whether it is the Lord’s Prayer or a prayer written by a government agency, during the school day or be required to participate in a moment of silence or other practices designed to encourage prayer.
- for students to be required to read from the bible as part of a religious exercise
- for law or policies to forbid evolution to be taught or require that creationism be taught along-side evolution whenever evolution is discussed in the classroom
- for passive measures to be used in the classroom to promote religion
- for religiously themed items to be used as decoration when those decorations served no clear secular purpose
In order for a practice to be constitutional it must meet three criteria. It must:
- “have a secular legislative purpose”
- “have principal effects which neither advance nor inhibit religion”
- “not foster an excessive government entanglement with religion”
Although schools cannot promote religion by reading the bible or other religiously affiliated documents in schools, this does not mean that all reference to religion is unconstitutional. For example, it is perfectly appropriate for a religious concept to be discussed academically as it applies to a historical document as long as the purpose of the discussion is to help the students understand history and not to preach. As long as the practice in question meets the three prongs of the test provided in the case of Lemon v. Kurtzman, it is constitutional, according to the most recent rulings of the United States Supreme Court.
I can say one thing about my granddaughter's school, they still pray and pledge allegiance to the flag. The principal say if praying offends anyone, the need to attend to a different school and I agree with that.
Thanks Mr kbdressman for this useful article. The Supreme Court of the USA is always watchful and alert in protecting the constitution. Regarding religion, I would say only one thing - let religion be a private affair. In this age of enlightenment brought to us by science and technology, religion has almost been relegated to the realm of superstitions. The atheists have shown us that one can be a good person without having to believe in a faith. Let our morality come from a rational mind and not from a religious faith.
If it comes to choice and free will then being a secular society should allow choice and classes on faith or religion. Sadly those who do not belief in choice has made such ideas a very dangerous World. In any argument belief requires an individual choice that one can not force a belief on anyone to attain a true spiritual connection to God and attain any goals in heaven. Sometimes I just want to say, you our on Earth stupid You can only attain things in Heaven by avoiding everything that is Earthly.
The first line of this Hub states it all nothing more is to be said! Excellent article if only we as Americans would enforce our constitution we might truly be safe. People do not even know what safe is anymore.
Our government has funded the Islamic State and now created Isis to destabilize the west. The problem is we live in the West! Now these tyrannical powers are soon to be at your backdoor.
People are starting to wake up, however, the internet "shill's" are out in full force. I am getting slammed here and on my YouTube channel. So if your a truth fighter you can check out my content.
Up and following hopefully you follow suit. We must unite to regain the foothold on our country so we can then maintain the ground to fight them back into the sea where they came from. They never quit after the War of 1812! Good stuff keep up the age old fight!
-
Great Hub! I see it perfectly appropriate for religious STUDIES to be conducted in a public school, but I do not see a need to "burn the books" as they do pertain to history. All religions created our history as a planet, and sometimes it offends people that history went this way or that way, but if that's what historians discover, then it should be read that way. I believe in the separation of church and state, and since science has been turned into a religion, that needs to go into the religious studies group... Which COULD be elective in high school and college. I believe in science, don't get me wrong, but I believe that a "God" created science, being as it has yet to be fully discovered. It would be nice if science could be left at the periodic table and medication being labeled as "working" or "not working. Thanks for sharing. :) What we believe isn't on the line; the truth needs to be discovered, there's no doubt in that. There has to be a way to keep church and state separate while still providing the education. Thanks for sharing. :)
Yes Mam, being a Biology student, if i want to make myself believe of the Virgin Birth of Christ, then the Ancient Alien Theory is the most appropriate I guess :D. Anyways, I get your point. Thanks for the reply. :)
-
Souradipsinha... you're a biology student... and biology is concerned with human beginnings and cells and 'all that stuff' concerned with getting a new life going... well: it seems appropriate to discuss how Jesus didn't have the mixings of the same kind as us... he wasn't conceived through the procedure of having sex... he was 'put there' by an external being... Therefore, the logicalness of it... I would have loved to have heard the speech, although I may have stood in my chair and shouted at him... [smile]
Nice article. I am an Indian. Though we say proudly that we are a secular country, there are loads of hypocrisy everywhere in our Indian society. The College where I study is a State aided Christian minority college. It is one of the best in Calcutta. It hosts frequent prayer sessions and other religion related assemblies for the students (Who are Christian). The funny thing is that, most of our Christian friends find it annoying and boring to join those sessions regularly. One day, the Rector of our College (our respected former Principal) was even giving a speech to all the students of the College trying to "logically prove" the "Virgin birth of Jesus Christ". Though i respect the religious sentiments but neither is the College a place for such discussions nor is such a topic to be discussed in front of Biology Hons students. Isn't it? :)
Fantastic article. Every day I see people petitioning for religion to be taught in schools in the U.S. I'm Canadian, and you'd never see such a thing in a public school. In fact, the last politician who openly stated that the world is 6,000 years old at a political event got laughed right out of his position as party leader. Stockwell Day was his name. If Christians are so keen to force the Bible into schools, then they had better be ready to allow the Quran, the Torah and other religious texts to have equal share. It's all or nothing. Of course, Christians won't have that, because their God is the real God based on evidence such as....um....well, because they say so.
This article was most informative and well written on an important topic. As a middle school teacher, I found it useful. Thanks
I also believe there needs to be a separation because you start crossing constitutional boundaries that shouldn't have been crossed in the first place. Some of the arguments people make against this are really mind blowing and make me strongly question their intelligence.
I'm strongly in favor of keeping church and state separate. If people want their child to study religion in school then they need to send them to parochial schools or ask their church to set up after-school indoctrination sessions for their children.-... I just read this article and I was tempted to comment. Many of the commenters just started arguments with previous commenters. -- My personal opinion? Well. Most of those people do not know who you or I are. Nor do they care who we are. However, they think they want to control us, even if they don't know us. If they passed us on the street, I can guarantee there would be no "Hi, how are you!", but my assumption is that they not even glance in our direction.
it is perfectly appropriate for a religious concept to be discussed academically as it applies to a historical document as long as the purpose of the discussion is to help the students understand history and not to preach -- I agree -- the bible is a historical document. Two parts. Old Testament and New Testament. The New Testament clearly states that you must know the details of the old Testament, but must follow the NEW Testament.
19 | https://hubpages.com/politics/Should-the-Bible-Be-Used-in-Schools | CC-MAIN-2017-17 | refinedweb | 3,037 | 60.95 |
Plotting sine and cosine graph using matloplib in python
Plotting is an essential skill. Plots can reveal trends in data and outliers. Plots are a way to visually communicate results with your team and customers. In this tutorial, we are going to plot a sine and cosine. for this refer
- How to import libraries for deep learning model in python
- Importing dataset using Pandas (Python deep learning library )
Sine and Cosine Graph Using matplotlib in Python
In this tutorial, we are going to build a couple of plots which show the trig functions sine and cosine. We’ll start by importing matplotlib using the standard lines import matplotlib.pyplot as plt. This means we can use the short alias plt when we call these two libraries.
Import required libraries to draw sine and cosine graph in Python – matplotlib and numpy
import matplotlib.pyplot as plt import numpy as np
Next, we will set an x value from zero to 4π in increments of 0.1 radians to use in our plot. The x-values are stored in a numpy array. has three arguments: start, stop, step. We start at zero, stop at 4π and step by 0.1 radians. Then we define a variable
y as the sine of x using numpy sine() function.
x = np.arange(0,4*np.pi,0.1) # start,stop,step y = np.sin(x)
To build the plot, we use matplotlib’s plt.show() function. The two arguments are our numpy arrays x and y . The syntax plt.show() will show the finished plot.
plt.plot(x, y) plt.show()
Now we will build one more plot, a plot which shows the sine and cosine of x and also includes axis labels, a title, and a legend. We build the numpy arrays using the functions as before:
x = np.arange(0,4*np.pi,0.1) # start,stop,step y = np.sin(x) z = np.cos(x)
now using plt.show().
plt.plot(x,y,x,z) plt.show()
Output of sine and cosine graph program in Python:
Here are the two screenshots of the output of the program:
sine graph in matplotlib – python
cosine graph in matplotlib – Python
This is how we have built our graph, so we have learned the following.
- what is matplotlib
- importing matplotlib
- plotting sine and cosine graph
hope you got a fair idea about matplotlib and graph relation.see you in the next tutorial until then enjoy learning. | https://www.codespeedy.com/plot-sine-and-cosine-graph-using-matloplib-in-python/ | CC-MAIN-2020-34 | refinedweb | 410 | 75.61 |
Important: Please read the Qt Code of Conduct -
Make a round progress bar
Hello,
I would like to make a round progress bar close to that :
I don't know how to achieve this. Does anybody can give me clue about how to start at least ?
Thanks in advance
- sierdzio Moderators last edited by
I guess something like this could work:
Rectangle { property int value: 0 width: 300 height: width border.width: 5 radius: width * .5 clip: true Rectangle { with: parent.width height: parent.height * parent.value / 100 // percentage color: "#ff0000" } }
Untested.
@sierdzio said in Make a round progress bar:
Rectangle {
property int value: 0
width: 300
height: width
border.width: 5
radius: width * .5
clip: true
Rectangle {
with: parent.width
height: parent.height * parent.value / 100 // percentage
color: "#ff0000"
}
}
It is not working here is the result :
I tried something close to this but I have'nt been able to get the same shape as the parent rectangle.
@DavidM29 said in Make a round progress bar:
with: parent.width
That should obviously be:
width: parent.width
....
- sierdzio Moderators last edited by
OK then one more try and I'll recommend something else.
Item { id: main property int value: 0 width: 300 height: width Rectangle { width: parent.width height: parent.height * parent.value / 100 // percentage color: "#ff0000" anchors.bottom: parent.bottom } Rectangle { anchros.fill: parent border.width: 5 radius: width * .5 clip: true } }
I suppose the renctangle will still stick out, though. You could achieve your goal using QML Canvas, custom QQuickItem painting.
@sierdzio here is the result :
Never used Canvas or QuickItem painting. Can you guide me a bit through this ?
The clip effect is based on rectangle, so, you can reimplement this effect in paint render (c++) or you can use a "rectangle" (item) to shape the inner circle.
Rectangle{ property int percentage: 100 id: root width: 300 height: 300 radius: width / 2 color: "white" border.color: "#385d8a" border.width: 5 Item{ anchors.bottom: parent.bottom anchors.left: parent.left anchors.right: parent.right height: parent.height * parent.percentage / 100 clip: true Rectangle{ width: root.width - root.border.width * 2 height: root.height - root.border.width * 2 radius: width / 2 anchors.bottom: parent.bottom anchors.left: parent.left anchors.margins: root.border.width color: "red" } } Text{ anchors.centerIn: parent font.pixelSize: 20 text: root.percentage.toString() + "%" } }
Works nicely ! Thank you !
I have another question :
For an image is it possible to do the same for example, considering this as an image :
like a .svg file, would it be possible to color just the circle of the image with the same rendering ?
If you want I can make a new post for this.
@DavidM29
I believe for image you can apply a mask in the image
This post has a good solution:
Opacity Mask Documentation
I believe I did not express my self clearly.
From the the image on my previous post I would like to know how to do something like that :
The idea is to have a variable part on the image.
Maybe it should be separate in different step like that :
The background would be always present and the filling appear partially depending on the value.
- KillerSmath last edited by
@DavidM29 do you want to create an animation of loading of image starting on bottom and ending on top ?
I want to animated just a part of the image. I want to keep a constant part. Assuming this image :
I want to keep the wheel and glass but I want to animate the Orange color of the car. Loading like the circle on the previous messages.
Not sure it is very clear. I'm trying to find a real exemple somewhere.
Edit :
Like here
There is the middle of the display animated and the rest of it is fixed. I would like to anime the display from bottom to top and keeping the border fixed.
Or from the example above Fill my background image on the transparent circle with the red circle.
- KillerSmath last edited by
@DavidM29
Something like that:
Item{ width: 350 height: 150 anchors.centerIn: parent Rectangle{ id: rect color: "steelblue" width: 350 anchors.bottom: parent.bottom SequentialAnimation{ running: true loops: Animation.Infinite NumberAnimation{ target: rect properties: "height" from: 0 to: 150 duration: 5000 } NumberAnimation{ target: rect properties: "height" from: 150 to: 0 duration: 5000 } } } }
Yes exactly but with a constant border wich is like an image.
@DavidM29
Using the previous posts, you can use mask with rectangle loader.
Obs: the maximum radius = min_between(width, height) / 2
Code
import QtQuick 2.8 import QtGraphicalEffects 1.0 Rectangle{ property int imgRadius: Math.min(imgContainer.width, imgContainer.height) / 2 property int borderWidth: 3 id: imgContainer width: 190 height: 190 anchors.centerIn: parent color: "#f2f2f2" border.color: "#385d8a" border.width: borderWidth radius: imgRadius Image { id: img anchors.fill: parent source: "" layer.enabled: true layer.effect: OpacityMask { maskSource: Item { width: imgContainer.width height: imgContainer.height Rectangle{ id: rectContainer width: parent.width anchors.bottom: parent.bottom clip: true color: "transparent" Rectangle { id: rectMask anchors.bottom: parent.bottom anchors.left: parent.left anchors.right: parent.right anchors.margins: imgContainer.borderWidth height: img.height - imgContainer.borderWidth * 2 radius: Math.max(0, imgContainer.imgRadius-imgContainer.borderWidth) } SequentialAnimation{ running: img.status == Image.Ready loops: Animation.Infinite NumberAnimation{ target: rectContainer properties: "height" from: 0 to: img.height duration: 5000 } PauseAnimation{ duration: 1000 } NumberAnimation{ target: rectContainer properties: "height" from: img.height to: 0 duration: 5000 } PauseAnimation{ duration: 1000 } } } } } } }
That is close to what I want but this will work only on standard shape like rectangle or circle. If I wan't to have this effect inside an image it will not work doesn't it ? | https://forum.qt.io/topic/91649/make-a-round-progress-bar | CC-MAIN-2021-31 | refinedweb | 940 | 60.61 |
import "nsICookieService.idl";
Provides methods for setting and getting cookies in the context of a page load. See nsICookieManager for methods to manipulate the cookie database directly. This separation of interface is mainly historical.
This service broadcasts the following notifications when the cookie list is changed, or a cookie is rejected:
topic : "cookie-changed" broadcast whenever the cookie list changes in some way. see explanation of data strings below. subject: see below. data : "deleted" a cookie was deleted. the subject is an nsICookie2 representing the deleted cookie. "added" a cookie was added. the subject is an nsICookie2 representing the added cookie. "changed" a cookie was changed. the subject is an nsICookie2 representing the new cookie. (note that host, path, and name are invariant for a given cookie; other parameters may change.) "batch-deleted" a batch of cookies was deleted (for instance, as part of a purging operation). the subject is an nsIArray of nsICookie2's representing the deleted cookies. "cleared" the entire cookie list was cleared. the subject is null. "reload" the entire cookie list should be reloaded. the subject is null.
topic : "cookie-rejected" broadcast whenever a cookie was rejected from being set as a result of user prefs. subject: an nsIURI interface pointer representing the URI that attempted to set the cookie. data : none. | http://doxygen.db48x.net/comm-central/html/interfacensICookieService.html | CC-MAIN-2019-09 | refinedweb | 216 | 52.87 |
this.
This is going to sound silly, but in my current project I'm using the image manipulator to place tiles, objects etc.
For instance, to place my ground tiles I simply draw a black pixel in an image of say 32x32.
I can then have the image manipulator test for that color, and say if the color at loop x 10, loop y 32 is black create the object ground tile at x of 10*10, and y of 32*10.... In a layout that is 320 x 320. 3200 would be *100 etc.
Now that might sound limiting, but when you think about it you have 255 states for red, blue, and green, meaning you have as many options for items as you do for colors... literally millions when you take alpha into account.
With that in mind not only can you create sprites by color, you can also give those sprites attributes like angle, size, and even private variables.
All you have to do is create your own special palette, and figure what you want them to represent.
No special level editor required, just any old image editor.
Develop games in your browser. Powerful, performant & highly capable.
Interesting concept. Sounds really confusing though!
Actually I've already figured out tiles/collision tiles/triggers, and the like. I've got it set up so you can change their angles and size and everything. That was pretty easy. The problem I'm having here is with sprite objects and their private variables. I don't think your method would work for what I'm trying to do. One example is an enemy spawner; I need to be able to type the name of the enemy the spawner will create, or atleast choose it from a list. The data would have to be stored in a private variable. Another example is destructible tiles/objects. I need to tell that tile/object which particles to create when it's destroyed, what item(s) to drop, how many hits it takes to destroy, what sound to play when hit, etc.
I REALLY don't feel like basing that stuff on things like the object's angle or animation frame or something, although it is possible.
When working object oriented, you will have an easier life using one of the two object oriented tools: 's'-plugin or python
In the third post on this page, lucid gives a very fine example of how 's' could help you solve any of your issues.
When working object oriented, you will have an easier life using one of the two object oriented tools: 's'-plugin or python
In the third post on this page, lucid gives a very fine example of how 's' could help you solve any of your issues.
yeah, I agree!!!
the level editor there, if you haven't taken a look is only 4 events. add all your objects to an array, create spatial info array (automatically generates an array with your choice of any combination x,y,z,angle,width,and height of all the objects in the array)
and then save, your choice of encrypted or not
at a later time I may add the option to save pv values as well, but that's a simple matter
create an array to hold the pvs
for each object in array, add the private variable to the new array. and save after that instead
loading would just be the reverse. when you load you can tell s to automatically apply the spatial info array, and you'll have all your objects back in their original location, and in the array. and then you can just For Each Object in array, set pv to {"yourpvarray",loopindex}
in s, it's loopindex, it's just li, but if you don't know that and you plan to use 's', better start them tutorials
I've been dreading the day I'd have to learn the S plugin Oh well, better now than never.
If you feel more comfortable by reading the following, you could also consider using Python:
# creating a game object reference (that will run at start of layout)
class GameObject(object):
def __init__(self, item=None, type=None, name=None):
self.reference = {}
if item != None:
self.reference['Type'] = type
self.reference['Name'] = name
copy_from_item(item)
def copy_from_item(self, item):
self.reference['X'] = item.X
self.reference['Y'] = item.Y
self.reference['W'] = item.Width
self.reference['H'] = item.Height
self.reference['Angle'] = item.Angle
def add_pv(self, pv_title, pv_value):
self.reference[pv_title] = pv_value
#calling a game object reference (most likely a separate script somewhere in the events)
myCoolRef = GameObject(Sprite, 'Sprite', 'Bullet')
myCoolRef.add_pv('will_spawn', 'SmokeTrail')
myCoolRef.add_pv('Lifespan', int(Editbox.Text))
[/code:1d5w813b]
EDIT: But I really think, 's' would be the better choice for this particular task, simply because it was made for something like that. Saving the informations is just a matter of one order (whereas in Python you would need to create your own writing routines) and the spatial info shortcut is also neat. | https://www.construct.net/en/forum/construct-classic/help-support-using-construct-38/object-management-custom-38481 | CC-MAIN-2020-16 | refinedweb | 847 | 60.24 |
On Wed, Apr 19, 2006 at 02:25:00AM -0600, Eric W. Biederman wrote:> That patch should probably be separated, from the rest.> But it looks like a fairly sane idea. Yeah, I'll keep these together for now, but the ptrace one isconceptually different from the rest.> I think you missed a couple essential things to a time namespace.> Timers. The posix timers, in particular. The worst> of those is the monotonic timer. Oops, thanks for pointing that out.> In the case of migration the ugly case to properly handle is the> monotonic timer. That needs an offset yet it is absolutely forbidden> to provide that offset from the inside. So this is the one namespace> that I think is inappropriate to use sys_unshare to create.> We need a system call so that we can specify the minimum or the> starting monotonic time base.For migration, it looks like the container will have to specify thetime base at creation so that everything in it will have a consistentview of time if they get moved around.So, maybe it belongs in clone as a "backwards" flag similar toCLONE_NEWNS. Jeff-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2006/4/26/192 | CC-MAIN-2017-22 | refinedweb | 217 | 66.84 |
How to make a fullscreen button for Flash Catalyst?Cuwen Mar 28, 2012 7:02 AM
Hey everyone. I really hope someone can help me with this. How can I make a fullscreen button in Flash Professional that would make my Flash Catalyst project go fullscreen?
1. Re: How to make a fullscreen button for Flash Catalyst?Cuwen Mar 28, 2012 7:47 AM (in response to Cuwen)
Anyone? I mark helpful and correct answers.
2. Re: How to make a fullscreen button for Flash Catalyst?sinious Mar 28, 2012 1:56 PM (in response to Cuwen)1 person found this helpful
Never used catalyst before but I hear it's a designer tool that can handle a little code. If you want a projector to go fullscreen here would be the code to add to a buttton with the instance name of myButton to do it. I'm not sure if it's the same for you:
import flash.display.StageDisplayState;
import flash.events.MouseEvent;
myButton.addEventListener(MouseEvent.CLICK, fullScreen);
function fullScreen(event:MouseEvent):void
{
stage.displayState=StageDisplayState.FULL_SCREEN;
}
3. Re: How to make a fullscreen button for Flash Catalyst?Cuwen Apr 12, 2012 12:25 PM (in response to sinious)
Do you know if there's a way I can do this just using Flash Catalyst? I don't have Flash Builder, so I can't use it to add in the script. I'm Googling right now trying to find an answer but haven't found one, yet.
4. Re: How to make a fullscreen button for Flash Catalyst?sinious Apr 16, 2012 8:33 AM (in response to Cuwen)
I'm sorry I really don't know Flash Catalyst as much as I'd like to. Designing interfaces is left up to me, no designers at my agency use Catalyst. Though this is the Flash forum so that's as much as I can tell you. I didn't know Catalyst didn't support basic scripts (I thought I read that it did).
Ultimately, for a very cheap price you can do something like go to and buy a membership. Dirt cheap compared to what you get. They offer many courses on all this stuff and I'm sure your answer would lie in one of the (nicely broken up by subject) video training videos.
Just searching for Catalyst brings up a bunch of courses:
edit:
For instance I watched the essential CS5.5 training and I saw in 2 minutes flat that when you click on a button you should have an "Interactions" panel that lets you do things. If they didn't put fullscreen as an interaction that's another thing but I'm just pointing out it's very easy to learn how to do all sorts of things in video training. If you do not want to purchase a membership there just find a video you think would have the info in it and I'll watch it and let you know if it told me how to do it, and how to do it.
5. Re: How to make a fullscreen button for Flash Catalyst?Cuwen Apr 18, 2012 5:44 AM (in response to sinious)
Sinious, that is very kind to offer to do that. Thank you. My boss is supposed to be getting a Lynda subscription b/c I've told him how great the site is months ago and he got the ok from his bosses. He hasn't gotten around to doing it, yet, though.
And I was working with the interactions a few weeks ago, but no fullscreen button, which is kinda weird. I'll let you know if I ever find a solution in FC. Thank you so, SO much for your help!! You've been great!
6. Re: How to make a fullscreen button for Flash Catalyst?sinious Apr 18, 2012 6:18 AM (in response to Cuwen)
The subscription is worth it as a personal investment. It's like $29 a month, which is a couple packs of cigarettes or a few lattes. For what you get out of it is insanely worth it. You should consider buying it yourself! There's lots of courses on there in many different catagories from web to photography to business management to you name it. As they say, invest your time, don't spend your time.
Hope it helps! | https://forums.adobe.com/thread/981734?tstart=0 | CC-MAIN-2016-44 | refinedweb | 733 | 81.63 |
A maintenance release of RcppClassic, now at version 0.9.6, went out to CRAN today. This package provides a maintained version of the otherwise deprecated first Rcpp API; no new projects should use it.
No changes were in user-facing code. The
Makevars file was change to accomodate a request by the CRAN Maintainer to keep it free of GNU Make extensions. At the same time, we overhauled the look and feel of the (very short) vignette. Build instructions were updated both in the vignette and in the included example package. Other accumulated changes since the last release were updates to the
DESCRIPTION and
NAMESPACE file as well two namespace-related R code updates.
Courtesy of CRANberries, there is the set of changes relative... | https://www.r-bloggers.com/rcppclassic-0-9-6/ | CC-MAIN-2018-17 | refinedweb | 125 | 66.33 |
TypeScript and Babel 7
Daniel
Babel is a fantastic tool with a vibrant ecosystem that serves millions of developers by transforming the latest JavaScript features to older runtimes and browsers; but it doesn’t do type-checking, which our team believes can bring that experience to another level. While TypeScript itself can do both, we wanted to make it easier to get that experience without forcing users to switch from Babel.
That’s why over the past year we’ve collaborated with the Babel team, and today we’re happy to jointly announce that Babel 7 now ships with TypeScript support!
How do I use it?
If you’re already using Babel and you’ve never tried TypeScript, now’s your chance because it’s easier than ever. At a minimum, you’ll need to install the TypeScript plugin.
npm install --save-dev @babel/preset-typescript
Though you’ll also probably want to get the other ECMAScript features that TypeScript supports:
npm install --save-dev @babel/preset-typescript @babel/preset-env @babel/plugin-proposal-class-properties @babel/plugin-proposal-object-rest-spread
Make sure your
.babelrc has the right presets and plugins:
{ "presets": [ "@babel/env", "@babel/preset-typescript" ], "plugins": [ "@babel/proposal-class-properties", "@babel/proposal-object-rest-spread" ] }
For a simple build with
@babel/cli, all you need to do is run
babel ./src --out-dir lib --extensions ".ts,.tsx"
Your files should now be built and generated in the
lib directory.
To add type-checking with TypeScript, create a
tsconfig.json file
{ "compilerOptions": { // Target latest version of ECMAScript. "target": "esnext", // Search under node_modules for non-relative imports. "moduleResolution": "node", // Process & infer types from .js files. "allowJs": true, // Don't emit; allow Babel to transform files. "noEmit": true, // Enable strictest settings like strictNullChecks & noImplicitAny. "strict": true, // Disallow features that require cross-file information for emit. "isolatedModules": true, // Import non-ES modules as default imports. "esModuleInterop": true }, "include": [ "src" ] }
and just run
tsc
and that’s it!
tsc will type-check your
.ts and
.tsx files.
Feel free to add the
--watch flag to either tool to get immediate feedback when anything changes. You can see how to set up a more complex build on this sample repository which integrates with tools like Webpack. You can also just play around with the TypeScript preset on Babel’s online REPL.
What does this mean for me?. So even if Babel builds successfully, you might need to check in with TypeScript to catch type errors. For that reason, we feel
tsc and the tools around the compiler pipeline will still give the most integrated and consistent experience for most projects.
So if you’re already using TypeScript, maybe this doesn’t change much for you. But if you’re already using Babel, or interested in the Babel ecosystem, and you want to get the benefits of TypeScript like catching typos, error checking, and the editing experiences you might’ve seen in the likes of Visual Studio and Visual Studio Code, this is for you!
Caveats
As we mentioned above, the first thing users should be aware of is that Babel won’t perform type-checking on TypeScript code; it will only be transforming your code, and it will compile regardless of whether type errors are present. While that means Babel is free from doing things like reading
.d.ts files and ensuring your types are compatible, presumably you’ll want some tool to do that, and so you’ll still need TypeScript. This can be done as a separate
tsc --watch task in the background, or it can be part of a lint/CI step in your build. Luckily, with the right editor support, you’ll be able to spot most errors before you even save.
Second, there are certain constructs that don’t currently compile in Babel 7. Specifically,
- namespaces
- bracket style type-assertion/cast syntax regardless of when JSX is enabled (i.e. writing
<Foo>xwon’t work even in
.tsfiles if JSX support is turned on, but you can instead write
x as Foo).
- enums that span multiple declarations (i.e. enum merging)
- legacy-style import/export syntax (i.e.
import foo = require(...)and
export = foo)
These omissions are largely based technical constraints in Babel’s single-file emit architecture. We believe that most users will find this experience to be totally acceptable. To make sure that TypeScript can call out some of these omissions, you should ensure that TypeScript uses the
--isolatedModules flag.
What next?
You can read up on the details from the Babel side on their release blog post. We’re happy that we’ve had the chance to collaborate with folks on the Babel team like Henry Zhu, Andrew Levine, Logan Smyth, Daniel Tschinder, James Henry, Diogo Franco, Ivan Babak, Nicolò Ribaudo, Brian Ng, and Vladimir Kurchatkin. We even had the opportunity to speed up Babylon, Babel’s parser, and helped align with James Henry’s work on typescript-eslint-parser which now powers Prettier’s TypeScript support. If we missed you, we’re sorry but we’re grateful and we appreciate all the help people collectively put in!
Our team will be contributing to future updates in the TypeScript plugin, and we look forward to bringing a great experience to all TypeScript users. Going forward, we’d love to hear your feedback about this new TypeScript support in Babel, and how we can make it even easier to use. Give us a shout on Twitter at @typescriptlang or in the comments below.
Happy hacking!
I’m a proponent of single responsibility principle, therefore I like this possibility to separate type checking and compilation into 2 separate processes and decide on your own which tool to use for each them. Thank you a lot for that great work together with Babel!
I wonder if it is possible to do type checking of custom file formats like .vue w/o Webpack/ts-loader?
Does Typescript support file preprocessing in order to be able to digest different file formats?
Or for that case I still need to compile my project with typescript?
Thanks for the work involved in making this plugin – it makes getting involved and mixing things up with other JS tech much simpler than when I used Typescript in 2015.
What it doesn’t cover is how to do a step-wise transition. I followed another guide, which basically duplicates this info and adds some bits, but it’s more of a big-bang conversions than a progressive transition. For me, fixing 3978 typescript errors are a bit overwhelming and would stall development for a week. Just getting my 200 LOC helpers lib to compile nicely with the definitions from `react-redux` took well over an hour.
Trying to convert a single file at a time didn’t bring me much luck either: existing Mocha tests quickly crashed on being unable to find the files.
Is there a way of doing this gradually?
any minify version for browser mode only? i hate to use npm
Thank you for the article. I configured my build pretty much the same, but it doesn’t provide a correct output, for example, when a class contains an abstract readonly property. Do you know how to deal with this problem? Details: | https://devblogs.microsoft.com/typescript/typescript-and-babel-7/ | CC-MAIN-2021-25 | refinedweb | 1,210 | 63.09 |
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Breaking Apart Our Repository9:22 with James Churchill
Instead of a single repository class we can have multiple repository classes, each focused on a single entity type. Let's start by splitting out all of the repository methods that deal with comic books into its own repository class.3.3 -b breaking-apart-our-repository
Keyboard Shortcuts
CTRL+SHIFT+B- Build Solution
Additional Learning
Okay, we now have a repository, that's great, but 0:00
let's take another look at our design. 0:04
As we work on our project implementing this series and 0:07
artist controllers, we'll continue to add methods to our repository class. 0:10
Overtime, our repository can become bloated. 0:14
Also, our repository is currently concerned about persisting data for 0:18
more than one entity type, comic books and comic book artists. 0:22
We might think of our design is violating the single responsibility principle, 0:26
which states, that every class should have responsibility 0:30
over a single part of the functionality provided by your application. 0:34
Luckily for us, the solution to this problem is easy. 0:38
Instead of a single repository class, we can have multiple repository classes, 0:41
each focused on a single entity type. 0:47
Let's split out all of the repository methods that deal with comic books, 0:50
into its own repository class. 0:53
To start, let's add a class named ComicBooksRepository to the shared class 0:56
libraries date folder. 1:01
By default, classes use the internal access modifier, if one isn't specified. 1:02
That restricts access to this class to code within this project or assembly. 1:09
Adding a public access modifier, 1:14
will make this class accessible to code within the web app project. 1:15
Now, let's set up our database context instance. 1:19
At a private field of type Context named _context. 1:23
And a constructor that accepts a context instance, and 1:28
uses that the set the private field. 1:31
Remember, this is the same pattern that we used for the repository class, 1:38
which allows the controller to manage the lifetime of the context. 1:41
Now, we can select and cut the ComicBook related methods to the clipboard. 1:46
GetComicBooks, GetComicBook, AddComicBook, UpdateComicBook, 1:51
DeleteComicBook and ComicBookSeriesHasIssueNumber. 1:56
And paste those methods from the clipboard into the ComicBooksRepository class. 2:00
Let's also move over to ComicBookArtistRoleCombination method. 2:09
Looks like we've got some using directives to add. 2:27
For the namespaces, ComicBookShared.Models and 2:36
System.Data.Entity. 2:43
Now that we have a repository that's focused on comic books, 2:46
we can simplify our method names. 2:50
Consumers of this class will already know that they're working with comic books. 2:53
So we can remove any references to comic book from the method names. 2:57
For instance, we can change GetComicBooks to GetList, 3:01
And GetComicBook to simply Get. 3:10
And we can remove ComicBook from the CRUD method names. 3:13
For now, I'll leave the validation method names as they are. 3:32
Currently, we're instantiating an instance of the repository 3:36
in the BaseController class. 3:40
Doing this in the controller base class, 3:42
made the repository available to all of our controllers. 3:44
When you have a single repository class, this approach makes a lot of sense. 3:47
But when you have multiple focus repository classes, it's probably best to 3:52
allow each controller to instantiate the repositories that they need. 3:56
Given that, let's update the ComicBooksController to instantiate 4:01
an instance of our new ComicBooksRepository. 4:04
Add a private field for the repository. 4:07
And add a default constructor to instantiate an instance of the repository. 4:21
We need an instance of our database context to 4:34
pass into the ComicBooksRepository constructor. 4:37
In the BaseController class, the context is currently a private field. 4:40
We'll need to switch that over to be in a protected property, so 4:44
that it's accessible to the descendant controller classes. 4:48
And update any references to the private field to use the new property. 4:51
Back at the ComicBooksController, update the call to the ComicBooksRepository 5:02
constructor to pass in the base controller's context property. 5:06
Now we can update all of the bad repository references and method calls. 5:10
Repository.GetComicBooks becomes, 5:14
_comicBooksRepository, GetList. 5:19
Repository.GetComicBook becomes _comicBooksRepository get. 5:26
Repository.AddComicBook becomes _comicBooksRepository.Add. 5:39
Another call to Repository.GetComicBook to update. 5:45
Repository.UpdateComicBook becomes _comicBooksRepository.Update, 5:53
and another call to Repository.GetComicBook to update. 5:59
Repository.DeleteComicBook becomes _comicBooksRespository.Delete, 6:04
Repository.ComicBookSeriesHasIssueNumber becomes 6:11
_comicBookRepository.ComicBookSeriesHasIs- sueNumber. 6:16
And that fixes all of the build errors in the ComicBooksController. 6:21
Let's build the project by pressing Ctrl+Shift+B. 6:25
And the ComicBookArtistController has some build errors that we need to fix. 6:32
This controller will also need an instance on the ComicBook repository. 6:37
You might be tempted at this point to just move the ComicBooksRepository instance 6:41
into the BaseController. 6:46
But let's hold off on doing that. 6:47
I suspect that the series and 6:50
artist controllers won't need an instance of that repository. 6:51
So let's stick with our plan of letting each controller instantiate 6:55
the repositories that they need. 6:58
First, the private field. 7:01
Then, the default constructor. 7:11
And update the bad method calls 7:27
Repository.GetComicBook becomes 7:32
_comicBooksRepository.Get. 7:37
Once more, And 7:45
Repository.ComicBookHasArtistRoleCombina- tion 7:51
becomes _comicBook.Repository.ComicBookHasArtistR- 7:58
oleCombination. 8:07
And now the project is successfully building again. 8:11
In repository class, we have six methods left. 8:27
GetSeriesList, GetArtists, GetRoles, GetComicBookArtist, 8:33
AddComicBookArtist, and DeleteComicBookArtist. 8:39
Let's keep series, artist, and 8:44
role related methods in this class, at least for now. 8:46
Later on, when we have more than one method for 8:50
each of those entity types, we'll add a repository for those types. 8:52
But let's go ahead and 8:56
move the ComicBookArtist-related methods to a new repository class. 8:57
In fact, let's make that your next exercise. 9:02
Add a new repository class, move the GetComicBookArtist, 9:06
AddComicBookArtist, and DeleteComicBookArtist methods to it. 9:10
And update the ComicBookArtist controller as needed, 9:14
to get the project building again. 9:17
See you after the break. 9:20 | https://teamtreehouse.com/library/breaking-apart-our-repository?t=56 | CC-MAIN-2021-10 | refinedweb | 1,198 | 58.58 |
One of the best things about WebAssembly is the ability experiment with new capabilities and implement new ideas before the browser ships those features natively (if at all).. You can think of using WebAssembly this way as a high-performance polyfill mechanism, where you write your feature in C/C++ or Rust rather than JavaScript.
With a plethora of existing code available for porting, it's possible to do things in the browser that weren't viable until WebAssembly came along.
This article will walk through an example of how to take the existing AV1 video codec source code, build a wrapper for it, and try it out inside your browser and tips to help with building a test harness to debug the wrapper. Full source code for the example here is available at github.com/GoogleChromeLabs/wasm-av1 for reference.
TL;DR: Download one of these two 24fps test video files and try them on our built demo.
Choosing an interesting code-base
For a number of years now, we've seen that a large percentage of traffic on the web consists of video data, Cisco estimates it as much as 80% in fact! Of course, browser vendors and video sites are hugely aware of the desire to reduce the data consumed by all this video content. The key to that, of course, is better compression, and as you'd expect there is a lot of research into next-generation video compression aimed at reducing the data burden of shipping video across the internet.
As it happens, the Alliance for Open Media has been working on a next generation video compression scheme called AV1 that promises to shrink video data size considerably. In the future, we'd expect browsers to ship native support for AV1, but luckily the source code for the compressor and decompressor are open source, which makes that an ideal candidate for trying to compile it into WebAssembly so we can experiment with it in the browser.
Adapting for use in the browser
One of the first things we need to do to get this code into the browser is to get to know the existing code to understand what the API is like. When first looking at this code, two things stand out:
- The source tree is built using a tool called
cmake; and
- There are a number of examples that all assume some kind of file-based interface.
All the examples that get built by default can be run on the command line, and that is likely to be true in many other code bases available in the community. So, the interface we're going to build to make it run in the browser could be useful for many other command line tools.
Using
cmake to build the source code
Fortunately, the AV1 authors have been experimenting with
Emscripten, the SDK we're going to
use to build our WebAssembly version. In the root of the
AV1 repository, the file
CMakeLists.txt contains these build rules:
if(EMSCRIPTEN) add_preproc_definition(_POSIX_SOURCE) append_link_flag_to_target("inspect" "-s TOTAL_MEMORY=402653184") append_link_flag_to_target("inspect" "-s MODULARIZE=1") append_link_flag_to_target("inspect" "-s EXPORT_NAME=\"\'DecoderModule\'\"") append_link_flag_to_target("inspect" "--memory-init-file 0") if("${CMAKE_BUILD_TYPE}" STREQUAL "") # Default to -O3 when no build type is specified. append_compiler_flag("-O3") endif() em_link_post_js(inspect "${AOM_ROOT}/tools/inspect-post.js") endif()
The Emscripten toolchain can generate output in two formats, one is called
asm.js and the other is WebAssembly.
We'll be targeting WebAssembly as it produces smaller output and can run
faster. These existing build rules are meant to compile an
asm.js version of the library for use in an
inspector application that's leveraged to look at the content of a video
file. For our usage, we need WebAssembly output so we add these lines just
before the closing
endif() statement in the
rules above.
# Force generation of Wasm instead of asm.js append_link_flag_to_target("inspect" "-s WASM=1") append_compiler_flag("-s WASM=1")
Note: It's important to create a build directory that's separate from the source code tree, and run all the commands below inside that build directory.
Building with
cmake means first generating some
Makefiles by running
cmake itself, followed by running the command
make which will perform the compilation step.
Note, that since we are using Emscripten we need to use the
Emscripten compiler toolchain rather than the default host compiler.
That's achieved by using
Emscripten.cmake which
is part of the Emscripten SDK and
passing it's path as a parameter to
cmake itself.
The command line below is what we use to generate the Makefiles:
The parameter
path/to/aom should be set to the full path of
the location of the AV1 library source files. The
path/to/emsdk-portable/.../Emscripten.cmake parameter needs
to be set to the path for the Emscripten.cmake toolchain description file.
For convenience we use a shell script to locate that file:
#!/bin/sh EMCC_LOC=`which emcc` EMSDK_LOC=`echo $EMCC_LOC | sed 's?/emscripten/[0-9.]*/emcc??'` EMCMAKE_LOC=`find $EMSDK_LOC -name Emscripten.cmake -print` echo $EMCMAKE_LOC
If you look at the top-level
Makefile for this project, you
can see how that script is used to configure the build.
Now that all of the setup has been done, we simply call
make
which will build the entire source tree, including samples, but most
importantly generate
libaom.a which contains the
video decoder compiled and ready for us to incorporate into our project.
Designing an API to interface to the library
Once we've built our library, we need to work out how to interface with it to send compressed video data to it and then read back frames of video that we can display in the browser.
Taking a look inside the AV1 code tree, a good starting point is an example
video decoder which can be found in the file
simple_decoder.c.
That decoder reads in an IVF file
and decodes it into a series of images that represent the frames in the video.
We implement our interface in the source file
decode-av1.c.
Since our browser can't read files from the file system, we need to design some form of interface that lets us abstract away our I/O so that we can build something similar to the example decoder to get data into our AV1 library.
On the command line, file I/O is what's known as a stream interface, so we can just define our own interface that looks like stream I/O and build whatever we like in the underlying implementation.
We define our interface as this:
DATA_Source *DS_open(const char *what); size_t DS_read(DATA_Source *ds, unsigned char *buf, size_t bytes); int DS_empty(DATA_Source *ds); void DS_close(DATA_Source *ds); // Helper function for blob support void DS_set_blob(DATA_Source *ds, void *buf, size_t len);
The
open/read/empty/close functions look a lot like normal
file I/O operations which allows us to map them easily onto file I/O for a
command line application, or implement them some other way when run inside
a browser. The
DATA_Source type is opaque from
the JavaScript side, and just serves to encapsulate the interface. Note, that
building an API that closely follows file semantics makes it easy to reuse in
many other code-bases that are intended to be used from a command line
(e.g. diff, sed, etc.).
We also need to define a helper function called
DS_set_blob
that binds raw binary data to our stream I/O functions. This lets the blob be
'read' as if it's a stream (i.e. looking like a sequentially read file).
Our example implementation enables reading the passed in blob as if it was a
sequentially read data source. The reference code can be found in the file
blob-api.c,
and the entire implementation is just this:
struct DATA_Source { void *ds_Buf; size_t ds_Len; size_t ds_Pos; }; DATA_Source * DS_open(const char *what) { DATA_Source *ds; ds = malloc(sizeof *ds); if (ds != NULL) { memset(ds, 0, sizeof *ds); } return ds; } size_t DS_read(DATA_Source *ds, unsigned char *buf, size_t bytes) { if (DS_empty(ds) || buf == NULL) { return 0; } if (bytes > (ds->ds_Len - ds->ds_Pos)) { bytes = ds->ds_Len - ds->ds_Pos; } memcpy(buf, &ds->ds_Buf[ds->ds_Pos], bytes); ds->ds_Pos += bytes; return bytes; } int DS_empty(DATA_Source *ds) { return ds->ds_Pos >= ds->ds_Len; } void DS_close(DATA_Source *ds) { free(ds); } void DS_set_blob(DATA_Source *ds, void *buf, size_t len) { ds->ds_Buf = buf; ds->ds_Len = len; ds->ds_Pos = 0; }
Building a test harness to test outside the browser
One of the best practices in software engineering is to build unit tests for code in conjunction with integration tests.
When building with WebAssembly in the browser, it makes sense to build some form of unit test for the interface to the code we're working with so we can debug outside of the browser and also be able to test out the interface we've built.
In this example we've been emulating a stream based API as the interface to
the AV1 library. So, logically it makes sense to build a test harness that we
can use to build a version of our API that runs on the command line and does
actual file I/O under the hood by implementing the file I/O itself underneath
our
DATA_Source API.
The stream I/O code for our test harness is straightforward, and looks like this:
DATA_Source * DS_open(const char *what) { return (DATA_Source *)fopen(what, "rb"); } size_t DS_read(DATA_Source *ds, unsigned char *buf, size_t bytes) { return fread(buf, 1, bytes, (FILE *)ds); } int DS_empty(DATA_Source *ds) { return feof((FILE *)ds); } void DS_close(DATA_Source *ds) { fclose((FILE *)ds); }
By abstracting the stream interface we can build our WebAssembly module to
use binary data blobs when in the browser, and interface to real files when
we build the code to test from the command line. Our test harness code can be
found in the example source file
test.c.
Implementing a buffering mechanism for multiple video frames
When playing back video, it's common practice to buffer a few frames to help with smoother playback. For our purposes we'll just implement a buffer of 10 frames of video, so we'll buffer 10 frames before we start playback. Then each time a frame is displayed, we'll try to decode another frame so we keep the buffer full. This approach makes sure frames are available in advance to help stop the video stuttering.
With our simple example, the entire compressed video is available to read, so the buffering isn't really needed. However, if we're to extend the source data interface to support streaming input from a server, then we need to have the buffering mechanism in place.
The code in
decode-av1.c
for reading frames of video data from the AV1 library and storing in the buffer
as this:
void AVX_Decoder_run(AVX_Decoder *ad) { ... // Try to decode an image from the compressed stream, and buffer while (ad->ad_NumBuffered < NUM_FRAMES_BUFFERED) { ad->ad_Image = aom_codec_get_frame(&ad->ad_Codec, &ad->ad_Iterator); if (ad->ad_Image == NULL) { break; } else { buffer_frame(ad); } }
We've chosen to make the buffer contain 10 frames of video, which is just an arbitrary choice. Buffering more frames means more waiting time for the video to begin playback, whilst buffering too few frames can cause stalling during playback. In a native browser implementation, buffering of frames is far more complex than this implementation.
Getting the video frames onto the page with WebGL
The frames of video that we've buffered need to be displayed on our page. Since this is dynamic video content, we want to be able to do that as fast as possible. For that, we turn to WebGL.
WebGL lets us take an image, such as a frame of video, and use it as a texture that gets painted on to some geometry. In the WebGL world, everything consists of triangles. So, for our case we can use a convenient built in feature of WebGL, called gl.TRIANGLE_FAN.
However, there is a minor problem. WebGL textures are supposed to be RGB images, one byte per color channel. The output from our AV1 decoder is images in a so-called YUV format, where the default output has 16 bits per channel, and also each U or V value corresponds to 4 pixels in the actual output image. This all means we need to color convert the image before we can pass it to WebGL for display.
To do so, we implement a function
AVX_YUV_to_RGB() which you
can find in the source file
yuv-to-rgb.c.
That function converts the output from the AV1 decoder into something we can
pass to WebGL. Note, that when we call this function from JavaScript we need
to make sure that the memory we're writing the converted image into has been
allocated inside the WebAssembly module's memory - otherwise it can't get
access to it. The function to get an image out from the WebAssembly module and
paint it to the screen is this:
function show_frame(af) { if (rgb_image != 0) { // Convert The 16-bit YUV to 8-bit RGB let buf = Module._AVX_Video_Frame_get_buffer(af); Module._AVX_YUV_to_RGB(rgb_image, buf, WIDTH, HEIGHT); // Paint the image onto the canvas drawImageToCanvas(new Uint8Array(Module.HEAPU8.buffer, rgb_image, 3 * WIDTH * HEIGHT), WIDTH, HEIGHT); } }
The
drawImageToCanvas() function that implements the WebGL painting can be
found in the source file
draw-image.js
for reference.
Future work and takeaways
Trying our demo out on two test video files (recorded as 24 f.p.s. video) teaches us a few things:
- It's entirely feasible to build a complex code-base to run performantly in the browser using WebAssembly; and
- Something as CPU intensive as advanced video decoding is feasible via WebAssembly.
There are some limitations though: the implementation is all running on the main thread and we interleave painting and video decoding on that single thread. Offloading the decoding into a web worker could provide us with smoother playback, as the time to decode frames is highly dependent on the content of that frame and can sometimes take more time than we have budgeted.
The compilation into WebAssembly uses the AV1 configuration for a generic CPU type. If we compile natively on the command line for a generic CPU we see similar CPU load to decode the video as with the WebAssembly version, however the AV1 decoder library also includes SIMD implementations that run up to 5 times faster. The WebAssembly Community Group is currently working on extending the standard to include SIMD primitives, and when that comes along it promises to speed up decoding considerably. When that happens, it'll be entirely feasible to decode 4k HD video in real-time from a WebAssembly video decoder.
In any case, the example code is useful as a guide to help port any existing command line utility to run as a WebAssembly module and shows what's possible on the web already today.
Credits
Thanks to Jeff Posnick, Eric Bidelman and Thomas Steiner for providing valuable review and feedback.
RSS or Atom feed and get the latest updates in your favorite feed reader!Subscribe to our | https://developers.google.com/web/updates/2018/08/wasm-av1?hl=id | CC-MAIN-2021-17 | refinedweb | 2,522 | 57.1 |
finallyClause
Another aspect to exception handling is found in the
finally clause that can be associated with a
try statement. To illustrate its purpose, let’s rewrite our
PrintFile method using some more low-level primitives from the
System.IO namespace:
static void PrintFile(string path){ FileStream fs = File.OpenRead(path); StreamReader sr = new StreamReader(fs); string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); }}
This code has severe flaws in it. Even if we succeed in opening the file on the first line, we never close the
FileStream object, which causes leakage. Wait a minute, didn’t the CLR have a garbage collector to take care of this? True, but as you will see, the garbage collector ...
No credit card required | https://www.safaribooksonline.com/library/view/c-40-unleashed/9780132678926/h4_676.html | CC-MAIN-2018-17 | refinedweb | 123 | 67.35 |
Find all good indices in the given Array
Given an array A[] of integers. The task is to print all indices
of this array such that after removing the ith element from the array, the array becomes a good array.
Note:
- An array is good if there is an element in the array that equals to the sum of all other elements.
- 1-based indexing is considered for the array.
Examples:
Input : A[] = { 8, 3, 5, 2 }
Output : 1 4
Explanation: A[] = [8, 3, 5, 2]
If you remove A[1], the array will look like [3, 5, 2] and it is good, since 5 = 3+2.
If you remove A[4], the array will look like [8, 3, 5] and it is good, since 8 = 3+5.
Hence the nice indices are 1 and 4.
Input : A[] = { 2, 2, 2 }
Output : 1 2 3
Removing any element at any indices will make array good.
Approach:
- Create a hash of array A[] which store frequency of each element and a variable sum having sum of each element of A.
- Iterate the array, remove the element at index i for each
.
- After removing an element the sum of remaining array is K, where K = sum – A[i].
- We have to find an element K/2 in the remaining array to make it good. Let K = K/2 for now.
- Now the remaining array will be good if and only if below conditions holds true.
- If A[i] == K and hash(K) > 1 OR If A[i] != K and hash(K) > 0.
- Print all such indices i.
Below is the implementation of above approach:
C++
Java
Python3
# Python3 program to find all good
# indices in the given array
from collections import defaultdict
# Function to find all good indices
# in the given array
def niceIndices(A, n):
Sum = 0
# hash to store frequency
# of each element
m = defaultdict(lambda:0)
# Storing frequency of each element
# and calculating sum simultaneously
for i in range(n):
m[A[i]] += 1
Sum += A[i]
for i in range(n):
k = Sum – A[i]
if k % 2 == 0:
k = k >> 1
# check if array is good after
# removing i-th index element
if k in m:
if ((A[i] == k and m[k] > 1) or
(A[i] != k)):
# print good indices
print((i + 1), end = ” “)
# Driver Code
if __name__ == “__main__”:
A = [8, 3, 5, 2]
n = len(A)
niceIndices(A, n)
# This code is contributed by Rituraj Jain
1 4
Time Complexity: O(N*log(N))
Recommended Posts:
- Magical Indices in an array
- Find the GCD of N Fibonacci Numbers with given Indices
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K
- Find the number of good permutations
- Check if the array can be sorted using swaps between given indices only
- Find the good permutation of first N natural numbers
- Find the shortest distance between any pair of two different good nodes
- Leftmost and rightmost indices of the maximum and the minimum element of an array
- Minimum number of elements that should be removed to make the array good
- Find the largest good number in the divisors of given number N
- Maximum difference of indices (i, j) such that A[i][j] = 0 in the given matrix
- Find original array from encrypted array (An array of sums of other elements)
- Print all Good numbers in given range
- Lexicographically Smallest Permutation of length N such that for exactly K indices, a[i] > a[i] + 1
- Find an element in array such that sum of left array is equal to sum of right | https://www.geeksforgeeks.org/find-all-good-indices-in-the-given-array/ | CC-MAIN-2019-22 | refinedweb | 603 | 58.15 |
Import
Simple import statements take the following form:
from module import name version;
This declaration makes the named declaration in the specified module available. Module names are dot-separated sequences of names. All imports are absolute, not relative to the importing module's name. For example, the declaration
from a.b.c import Example 1.0;
finds a module named "a.b.c" and imports the item (pattern, for example) with the name "Example".
Multiple named declarations can be accessed in one statement by separating them with commas:
from a.b.c import Example 1.0, Another 2.3;
Imported names must not clash with other names declared or imported in the same file. To avoid clashes, declarations can be renamed on import using an
as clause:
from one import Example 1.0; from two import Example 2.3 as ExampleTwo;
When importing, it is not immediately an error to import a name that is not defined in the corresponding module, or to import from a non-existent module. It only becomes an error when the imported name is used in a context that requires it exists. In particular, when a pattern overrides another pattern (see the section on overrides), it is not an error if the overridden pattern does not exist. For all other uses of an imported name, it is an error if the import fails.
Imported names are not available for further import. So, for example, if module B imports X from module A, module C cannot import X from B - it must import it directly from A.
Version compatibility
If there is an updated version of the selected object (for example, pattern or definition), the system will check your module containing the import to ensure that the minimum requirements are still met. For example, if you import version 1.1, this will allow the imported object to be 1.1, 1.2, and so forth, but NOT allow versions 1.0, 2.0, 2.1, 3.0, and so forth. The major version must be the same and the minor version must be at least the same as the version specified. If the version is not supported, the activation fails.
Most of the time, you will not need to update the import version. It might be necessary only if either there is an incompatible change in the imported pattern (represented by a major version change), or if you modify your pattern so that is relies on additional behaviour of the updated pattern. See Pattern overview for more information about how patterns are versioned.
Recommendation
Patterns contain tags that have information about the most recent Technology Knowledge Update (TKU) that updated the pattern (for example, TKU_2010_04_01). Therefore, you can perform a search for a specific TKU version to find patterns that were last changed in a specific version of TKU. Typing that value in the search box displays a list of patterns (and the containing pattern modules).
Version numbers
All top-level declarations are specified with a version number in major.minor format. When importing declarations, the version number must be specified. It is an error if the declaration imported is not compatible with the version specified in the import statement. The versions are compatible if the major number is identical and the minor number is at least as large as the requested version. So, for example, in
from test import Example 2.3;
the "Example" declaration from the "test" module is compatible if it has version 2.3 or 2.4, but not if it has version 2.2, 1.8 or 3.0.
Circular imports
Circular imports are not permitted. It is an error for file B to import from file A when file A is still being processed. | https://docs.bmc.com/docs/discovery/101/import-535494895.html | CC-MAIN-2019-47 | refinedweb | 624 | 57.47 |
This is an interesting article about using Swift pattern matching for routing deeplink URLs.
The majority of URL routing libraries use a pattern syntax that can match each element of a URL's path in one of three ways:
- Equality: Path element must match the pattern expression.
- Value-binding: Path element can be anything at all and will be made available in a parameters dictionary.
- Wildcard: Path element can be anything at all, and will be discarded.
There are a few reasons I don't much like this approach:
- The pattern matching is abstracted away using special syntax.
- The parameter name userId is repeated and stringly typed, so it's susceptible to typos.
- parameters["userId"] should never be nil, but the compiler doesn't know that, so we must force unwrap or add a guard statement.
As it happens, Swift's built-in pattern matching can be used for each of the three pattern types.
It proceeds to walk through the design process of a few abortive approaches and ends up with the URLPatterns library here.
I prefer this approach to the approach taken by most URL routing libraries for a few reasons:
- It's simple to bypass URLs and open a deeplink directly, e.g. by calling DeepLinker.open(.Home).
- The pattern-matching code is no longer in a third-party library, which makes it easier to debug.
- The pattern-matching code leverages Swift's built-in pattern-matching, which means it can be customized and extended.
- The pattern-matching and routing processes are separated into two steps. This provides an override point if needed…
Neat! For even more niftiness, check out the Generator approach in URLs and Pattern Matching mentioned in the comments.
And while we’re discussing routing, if you want something more conventional, this looks like a good choice:
JLRoutes: "URL routing library for iOS with a simple block-based API."
- Simple API with minimal impact to existing codebases.
- Parse any number of parameters interleaved throughout the URL.
- Wildcard parameter support.
- Seamlessly parses out query string and fragment parameters and passes them along as part of the parameters dictionary.
- Route prioritization.
- Scheme namespaces to easily segment routes and block handlers for multiple schemes.
- Return NO from a handler block for JLRoutes to look for the next matching route.
- Optional verbose logging.
- Pretty-print the whole routing table.
- No dependencies other than Foundation.
Looks like a sweet drop-in to handle just about everything you'd want, that!
Related Refcard: Swift Essentials
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/a-wild-url-appeared | CC-MAIN-2016-44 | refinedweb | 427 | 57.16 |
Is this the right code.
I don't understand this code.
def product (a,b): answer = (a*b) return "The product {} and {} is {}".format(a,b,answer) a = 3 b = 4
1 Answer
Steven Parker210,423 Points
You seem to be returning a string instead of the result.
The challenge says, "
return the result.", but your code is creating a string that describes what the math does and then returns that string.
So all you really need for the return line is:
return answer
And as Antonio pointed out, creating the "a" and "b" variables is not part of the challenge.
Antonio De Rose20,878 Points
Antonio De Rose20,878 Points | https://teamtreehouse.com/community/is-this-the-right-code | CC-MAIN-2021-43 | refinedweb | 111 | 75.4 |
The packaging situation in Python is "imperfect" for a good reason - packaging is simply a very difficult problem to solve (see the amount of effort poured into Linux distribution package management for reference). One of the core issues is that project X may require version V of library L, and when you come to install project Y it may refuse to work with that version and require a newer one, with which project X can't work. So you're in an impasse.
The solution many Python programmers and projects have adopted is to use virtualenv. If you haven't heard about virtualenv, you're missing out - go read about it now.
I'm not going to write a tutorial about virtualenv or extoll its virtues here - enough bits have been spilled about this on the net already. What I plan to do is share an interesting problem I ran into and the solution I settled on.
I had to install some packages (Sphinx and related tools) on a new machine into a virtualenv. But the machine only had a basic Python installation, without setuptools or distribute, and without virtualenv. These aren't hard to install, but I wondered if there's an easy way to avoid installing anything. Turns out there is.
The idea is to create a "bootstrap" virtual environment that would have all the required tools to create additional virtual environments. It turns out to be quite easy with the following script (inspired by the answer in this SO discussion):
import sys import subprocess VENV_VERSION = '1.9.1' PYPI_VENV_BASE = '' PYTHON = 'python2' INITIAL_ENV = 'py-env0' def shellcmd(cmd, echo=True): """ Run 'cmd' in the shell and return its standard out. """ if echo: print '[cmd] {0}'.format(cmd) out = subprocess.check_output(cmd, stderr=sys.stderr, shell=True) if echo: print out return out dirname = 'virtualenv-' + VENV_VERSION tgz_file = dirname + '.tar.gz' # Fetch virtualenv from PyPI venv_url = PYPI_VENV_BASE + '/' + tgz_file shellcmd('curl -O {0}'.format(venv_url)) # Untar shellcmd('tar xzf {0}'.format(tgz_file)) # Create the initial env shellcmd('{0} {1}/virtualenv.py {2}'.format(PYTHON, dirname, INITIAL_ENV)) # Install the virtualenv package itself into the initial env shellcmd('{0}/bin/pip install {1}'.format(INITIAL_ENV, tgz_file)) # Cleanup shellcmd('rm -rf {0} {1}'.format(dirname, tgz_file))
The script downloads and unpacks a recent virtualenv (substitute your desired version in VENV_VERSION) from PyPI and uses it directly (without installing) to create a new virtual env. By default, virtualenv will install setuptools and pip into this environment. Then, the script also installs virtualenv into the same environment. This is the bootstrap part.
Voila! py-env0 (or whatever you substituted in INITIAL_ENV) is now a self-contained virtual environment with all the tools you need to create new environments and install stuff into them.
This script is for Python 2 but can be trivially adapted for Python 3. In Python 3, the situation is actually more interesting. Python 3.3 (which is really the one you ought to be using if you've switched to 3 already) comes with virtualenv in the standard library (venv package), so downloading and installing it is not required.
That said, its virtualenv will not install setuptools and pip into the environments it creates. So YMMV here: if you need setuptools and pip there, go with a variation of the script above. If not, you don't need anything special really, just use the python3.3 -m venv.
P.S. The packaging situation is getting better though. There was a lot of focus during the recent PyCon on this. One of the interesting announcements was that distribute is merging back into setuptools. | http://eli.thegreenplace.net/2013/04/20/bootstrapping-virtualenv/ | CC-MAIN-2015-06 | refinedweb | 600 | 64.71 |
PhpStorm 7.1.1 EAP 133.437
We are glad to deliver one more holiday gift for all of you, opening Early Access Program for PhpStorm 7.1.1 bug fix update just before a small New Year break. PhpStorm 7.1.1 EAP 133.437 is available for download.
This build is focused on various bug fixes and improvements from the PHP (including rename/move namespace refactorings, Smarty editor major bug fixes), web, & IntelliJ platform sides.
Download PhpStorm 7.1.1 EAP build 133.437 for your platform from project EAP page and please report any bugs and feature request to our Issue Tracker.
Patch-update between release and EAP builds is not available.
Develop with pleasure!
-JetBrains PhpStorm Team | https://blog.jetbrains.com/phpstorm/2013/12/phpstorm-7-1-1-eap-133-437/?utm_source=rss&utm_medium=rss&utm_campaign=phpstorm-7-1-1-eap-133-437 | CC-MAIN-2021-10 | refinedweb | 121 | 70.8 |
In this tutorial, we’ll look at the Python CSV Module, which is very useful for csv file processing.
Using this module, which comes bundled with Python, we can easily read and write to CSV files.
Let’s get started!
Using the Python csv module
We must import the csv module to use relevant methods.
import csv
Now, depending on what you want to do, we can read or write to csv files using appropriate objects.
Let’s look at reading csv files first.
Reading from csv files using csv.reader()
To read from a csv file, we must construct a reader object, which will then parse the file and populate our Python object.
Python’s
csv module has a method called
csv.reader() which will automatically construct the csv reader object!
We must call the
csv.reader() method on an already opened file object, using
open().
import csv reader = csv.reader(file_object)
Normally, the recommended approach is to enclose everything using a
with context manager.
You can do something similar to this:
import csv # Open the csv file object with open('sample.csv', 'r') as f: # Construct the csv reader object from the file object reader = csv.reader(f)
The reader object will be an iterable consisting of all the rows in the csv file. By default, each
row will be a Python List, so it will be very convenient for us!
So you can directly print the rows using the for loop as shown below:
for row in reader: print(row)
Alright. Now that we have a basic template code, let’s print the contents of the below file using
csv.reader().
Let’s consider
sample.csv to have the below content.
Club,Country,Rating Man Utd,England,7.05 Man City,England,8.75 Barcelona,Spain,8.72 Bayern Munich,Germany,8.75 Liverpool,England,8.81
Now, let’s run code:
import csv with open('sample.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row)
Output
['Club', 'Country', 'Rating'] ['Man Utd', 'England', '7.05'] ['Man City', 'England', '8.75'] ['Barcelona', 'Spain', '8.72'] ['Bayern Munich', 'Germany', '8.75'] ['Liverpool', 'England', '8.81']
Okay, so we do get all the rows. Here, as you can see,
csv has given us the space after the comma.
If you want to parse individual words, by separating using the whitespace character, you can simply pass it to
csv.reader(delimiter=' ') as a delimiter character.
Let’s try out the modified code now:
import csv with open('sample.csv', 'r') as f: reader = csv.reader(f, delimiter=' ') for row in reader: print(row)
Output
['Club,', 'Country,', 'Rating'] ['Man', 'Utd,', 'England,', '7.05'] ['Man', 'City,', 'England,', '8.75'] ['Barcelona,', 'Spain,', '8.72'] ['Bayern', 'Munich,', 'Germany,', '8.75'] ['Liverpool,', 'England,', '8.81']
Indeed, we’ve now split the words, so
Man Utd becomes
Man and
Utd.
Similarly, if you want to parse delimited content, simply pass that character as a delimiter to
csv.reader().
Let’s now look at writing to a csv file.
Writing to csv files using csv.writer()
Analogous to the
csv.reader() method for reading, we have the
csv.writer() method for writing to files.
This will return a
writer object which we can use to write rows to our destination file.
Let’s look at how we can use this. First, create the
writer object:
import csv with open('output.csv', 'w') as f: writer = csv.writer(f)
We can now use the
writer.writerow(row) method to write a row. Here, similar to the reader object,
row is a list.
So, we can invoke it like this:
writer.writerow(['Club', 'Country', 'Rating'])
Let’s look run the whole program now:
import csv with open('output.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['Club', 'Country', 'Rating']) clubs = [['Real Madrid', 'Spain', 9.1], ['Napoli', 'Italy', 7.5]] for club in clubs: writer.writerow(club)
Let’s now look at
output.csv.
Club,Country,Rating Real Madrid,Spain,9.1 Napoli,Italy,7.5
Indeed, we have our rows on the output file!
NOTE: Similar to
csv.reader(delimiter), we can also pass a delimiter character to write using
csv.writer(delimiter)
If you observed closely, we have manually iterated through our list of rows (list of lists) and written each row one by one.
Turns out there is another method called
writer.writerows(rows) which can directly write all our rows!
Let’s test it out.
output.csv and run the below code.
import csv with open('output.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['Club', 'Country', 'Rating']) clubs = [['Real Madrid', 'Spain', 9.1], ['Napoli', 'Italy', 7.5]] writer.writerows(clubs)
Output
Club,Country,Rating Real Madrid,Spain,9.1 Napoli,Italy,7.5
We indeed get the same output as before!
Using csv.DictReader() and csv.DictWriter() to read and write to a csv as a Dictionary
Remember that when reading using the
reader object, we got the objects row-wise, as a list?
If you want the exact
column_name: row_name mapping, we can use the
csv.DictReader class and get a Dictionary instead!
Let’s look at how we can read from a csv file into a dictionary.
import csv with open("sample.csv", 'r') as file: csv_file = csv.DictReader(file) for row in csv_file: print(dict(row))
Here,
csv.DictReader() returns an iterable of
OrderedDict() objects. We need to convert each
OrderedDict row to a
dict, using
dict(row).
Let’s look at the output:
{'Club': 'Man Utd', ' Country': ' England', ' Rating': ' 7.05'} {'Club': 'Man City', ' Country': ' England', ' Rating': ' 8.75'} {'Club': 'Barcelona', ' Country': ' Spain', ' Rating': ' 8.72'} {'Club': 'Bayern Munich', ' Country': ' Germany', ' Rating': ' 8.75'} {'Club': 'Liverpool', ' Country': ' England', ' Rating': ' 8.81'}
Indeed, we have the column name as well as the row value!
Now, for writing to a csv file from a Dictionary, you have the
csv.DictWriter() class.
This is almost the same as
csv.write(), except that you’re writing from a dictionary instead of a list.
The syntax is a bit different though. We must specify the column names in advance, as part of our
fieldnames.
We then need to write the first row (header) using
writer.writeheader().
fieldnames = ['Club', 'Country', 'Rating'] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader()
Now, we can iterate through our list of
dicts, which has the relevant information.
Let’s re-write our old
writer example using
csv.DictWriter().
import csv with open('output.csv', 'w') as f: fieldnames = ['Club', 'Country', 'Rating'] # Set the fieldnames writer = csv.DictWriter(f, fieldnames=fieldnames) # Write the header writer.writeheader() clubs = [{'Club': 'Real Madrid', 'Country': 'Spain', 'Rating': 9.1}, {'Club': 'Napoli', 'Country': 'Italy', 'Rating': 7.5}] for club in clubs: writer.writerow(club)
We’ll now get the same output as before, indicating that we’ve successfully written to the csv file using our
csv.DictWriter() object!
Conclusion
Hopefully, you’ve understood how you can use the
csv module to process csv files easily. We made it easy to read and write to/from csv files, using suitable objects.
References
- JournalDev article on reading and writing to csv files in Python | https://www.askpython.com/python-modules/python-csv-module | CC-MAIN-2022-33 | refinedweb | 1,193 | 70.9 |
It’s project kickoff time, and you’re having a conversation with your client about what form the application will take:
Client: I’m thinking mobile app. Our users will definitely be using this on the go.
Dev: Sure, we can do a native mobile-
Client: Mind you, we’ll want a desktop version too. We’ll need to use it from the office.
Dev: Okay, well, a responsive web app-
Client: One of our priorities is definitely ease of access – we’ll need the app accessible from the home screen, ’cause who has time for typing in URLs, amirite? We’ll also want it to be useable offline, whenever people want to.
Dev: Ye-yeah, no problem, we can wrap your web app in a webview, bundle it up as a native app, and-
Client: Yeah, cool. So they’ll just be able to go to the site and install the app, right?
Dev: Well, no, they’ll have to download it from the appropriate App Store.
Client: Eh, that’s a no-go – this is internal only, we can’t have it showing up in the app stores. Didn’t I make that clear from the start?
Dev: …
The term your client was looking for is Progressive Web App – an application that acts like a responsive web app when accessed from the browser on any device, but can be installed to mobile devices like a native application. The link above makes the case for PWAs, so we won’t belabour the point – if you’re still here, it’s because you’re convinced it’s time to build a PWA.
Let’s dig into the details. We’re going to assume you have, or are building, a responsive or mobile-focused web application, and want to convert it to a PWA. Keep in mind that, like wrapping a webapp in a webview, all the heavy lifting is still done by you, the developer, in CSS, HTML and JS – there’s no PWA magic to make it look ‘native’.
Well, actually, there is a little magic. We’ll get to that next time.
Part 1 will focus on implementing a PWA the standards-compliant way. In Part 2, we’ll address the ‘little bit of magic’ PWA’s can have on Android to appear more native, and PWA’s on iOS Safari, because it always has to be a special snowflake.
Let’s begin.
Service, Please
Familiar with Service Workers? If not, get ready to do some reading on them – Service Workers are the clockwork that make PWAs tick.
Mozilla’s summary of Service Workers make it clear how this is so – and also, how complex a Service Worker can be:
-.
If you’re familiar with Web Workers, you’re about half-way there – Service Workers run on their own ‘thread’ (actual implementation details are up to the browser, of course), and have no access to the DOM, like a Web Worker. They have significantly more power than a web worker, however, particularly in terms of interacting with network requests; and, as a result, have more requirements to meet.
Let’s run down the checklist, and then we’ll get into some implementation details. For a PWA’s Service Worker you will need:
- A secure context – Service Workers must be run from a TLS-secured domain (https), because they can be Men-in-the-middle on every request from the browser for a given domain. The localhost special-case domain is the only exception to this rule, for the sake of development.
- A full list of the items you need to cache (for the caching and serving from cache functionality of a Service Worker, which is a requirement to have your application considered a PWA). Wildcards can’t be used – you need to give the full (relative) path of the resource you want cached. If you’re familiar with the Application Cache API this restriction will be familiar to you. For your application to be considered a PWA, at least the start url must completely load when the user is offline.
- A means of serving the Service Worker from the root of the path that you want the Service Worker to have control over – so, if you want the Service Worker to be able to control and serve resources for your entire application, and your application is at, you will need to be able to serve the Service Worker from / (as opposed to, e.g. /static/js/workers/ – if you serve from there, the only resources the Service Worker will be able to control will be those under that path).
Additional checklist items for a PWA include:
- A responsive (or mobile-focused) design.
- Quick initial load – Google, the company behind the original PWA spec (you may have heard of them), strongly suggests that your start url load under 10 seconds on a simulated 3G network – so no loading a half-dozen affiliate advertisements.
- You will want to consider making your application a SPA – it’s generally a good fit for this use case, especially if it allows you to cache more up-front, or trim down the number of bits your application needs to transfer over the network.
Looking for a Hard Worker, Room and Board Provided
First things first, let’s set up our web server to serve that Service Worker (lot of variations on ‘serve’ in that sentence) from the root of our domain, so we can control all resources and requests therein. We’re going to assume you’re using Python and Django in the example below, but the principle will always be the same.
First, we’ll create a service worker named
CacheWorker.js in our
static directory, under a
serviceWorkers directory. Then, we can create the view to serve this worker (and any others we might want to serve with potential control over all requests):
from django.conf import settings def serve_worker(request, worker_name): """ Serve the requested service worker from the appropriate location in the static files. We need to serve the worker this way in order to allow it access to requests made against the root - whatever /sub/dir the worker ends up getting served from is the only location it will have visibility on, so serving from / is the only way to ensure the worker has visibility on all requests. Only a-zA-Z-_ characters can appear in the service worker name. :param request: :param worker_name: :return: """ worker_path = path.join(settings.STATIC_ROOT, 'serviceWorkers', "{}.js".format(worker_name)) try: with open(worker_path, 'r') as worker_file: return HttpResponse(worker_file, content_type='application/javascript') except IOError: return HttpResponseNotFound()
Next, in urls.py, we’ll add the route to this view:
urlpatterns = [ # ...other patterns... url(r'^worker-(?P[a-zA-Z\-_]+).js$', views.serve_worker, name='serve_worker'), # ...other patterns... ]
Now, assuming our domain was, a request to will return our worker script.
Putting Your Workers in their Place
Now that we’re serving our worker script from the desired location, we need to tell the browser that it should be requesting said worker script, and installing it as a Service Worker.
To this effect, we will want to use the ServiceWorkerContainer API to register our service worker. Of course, since our PWA is a progressive enhancement, we will check to ensure that the browser actually supports Service Workers before we try and install it – your application should have some fallback behaviour when it encounters a browser that doesn’t.
/** * Install service workers in those browsers which support them. */ (function(window){ var serviceWorkers = { "IMMEDIATE": [], "LOAD": ['cacheWorker'], "DELAY": [] }; /** * Attempt to register the worker, and log either the success or failure to the console. * @param {String} worker */ function registerWorker(worker){ window.navigator.serviceWorker.register('/worker-'+worker+'.js').then(function(reg){ console.log('Registration successful for worker '+worker+', with scope: ' + reg.scope); }, function(error){ console.log('Service Worker registration failed for worker: ', worker, error); }); } /** * Handle messages sent to the main thread by Service Workers. * @param event */ function handleMessage(event){ console.log("TODO: Your app should do something with the event data sent by the worker.", event.data.message, event.data.data); } // Check for ServiceWorker support. if ('serviceWorker' in window.navigator){ // Listen for messages broadcasted by any service worker window.navigator.serviceWorker.addEventListener('message', handleMessage); /* * For each service worker, consider their priority queue. * Workers in the 'IMMEDIATE' queue are registered as soon as we can - this is useful if, * for example, we need to immediately be able to intercept requests. * Workers within queue 'LOAD' are registered after document load - this is the time to start caching * resources, for example, without contending with the browser for bandwidth. * Workers in queue 'DELAY' are registered after the application lets us know explicitly that now is a * good time. How your application goes about doing this is up to you. This last category * is good for workers that are going to be carrying out long-term activities, like * long-polling a server. */ serviceWorkers.IMMEDIATE.forEach(registerWorker); window.addEventListener('load', function(){ serviceWorkers.LOAD.forEach(registerWorker); }); window.addEventListener('yourCustomDelayEvent', function(){ serviceWorkers.DELAY.forEach(registerWorker); }); } })(window);
Cache Me, I’m Falling
So, we have our server sending our cacheWorker file along properly, and we have the browser registering the service worker, and downloading and installing our script. That’s great – except, our cacheWorker script is empty, so it doesn’t do anything. Let’s fix that.
/** * Service worker intended for caching and serving files when the application is offline, * to meet the requirements for a PWA. * @author Christopher Keefer */ var cacheVersion = 1, staticCache = 'static-cache-v'+cacheVersion, cacheableResources = [ // Root - This MUST be in the cacheable resources for a PWA! '/', // Images '/static/img/yourLogo.png', //... any other static image resources your application will need ... // CSS '/static/css/yourapp.min.css', // ... any other styling your app will need, order doesn't matter .... // Fonts '/static/css/fonts/roboto/roboto-regular.woff2', // ... any other fonts ... // JS '/static/js/yourapp.min.js' // ... any other JS - as with the other entries, the order you specify here doesn't matter, // the files will be loaded in the order you indicate in your HTML document. ... ]; /** * On install of this worker, add all cacheableResources to the staticCache. * Note that workers will be (re-)installed when they have changed (byte-wise comparison) * from the last worker encountered with the registered url (see the installation of workers, above), * which can be as simple as changing the cacheVersion number to point to a new 'version' of the cache. * You will want to update that cacheVersion number each time you change any of the cached resources. * Doing so will cause the worker to re-request and re-cache the cacheableResources, which is how we * will refresh cached resources for the application. */ self.addEventListener('install', function(event){ event.waitUntil( caches.open(staticCache).then(function(cache){ return cache.addAll(cacheableResources); }).then(function(){ // Take control of the client as soon as we're installed // and the cache has been updated. return self.skipWaiting(); }) ); }); /** * On activation of this service worker, delete old caches. Note that * we return a promise that resolves when all promises returned by * the delete calls within it resolve. * Once we've deleted the old cache, we need to let the clients know that * a new service worker (with a new cache) has taken over, and they'll * need to reload in order to get the newly cached resources, via * postMessage. * @param event */ self.addEventListener('activate', function(event){ event.waitUntil( caches.keys().then(function(cacheNames){ return Promise.all( cacheNames.map(function(cacheName){ if (cacheName !== staticCache){ return caches.delete(cacheName); } }) ); }).then(function(){ return self.clients.matchAll().then(function(clients){ return Promise.all(clients.map(function(client){ return client.postMessage({message:'needs-reload'}); })); }); }) ); }); /** * Intercept network requests so that we can serve the requested resource from the * cache, if we have it, or otherwise defer to the network. */ self.addEventListener('fetch', function(event){ // Workaround for Chromium bug that makes ignoring the search // parameter very slow when matching the request against the // cached values:. // Your application may not need this - or hey, it may even be fixed by the time // you're reading this! var hasSearch = (event.request.url.indexOf('?') !== -1); event.respondWith( caches.match(event.request, { ignoreSearch: hasSearch }).then(function(response){ return response || fetch(event.request); }) ); });
So, that’s a lot to take in, but the comments above should help. Let’s break down a few of the more complex bits:
Install
So, you’ll notice that we have add an event listener for ‘install’. This is the event that gets fired when a new version of the Service Worker is installed – whether for the first time, or because the Service Worker has changed in some way. The browser does a byte-wise comparison of the downloaded script, so any change will trigger a re-install of the script.
Often, you won’t need to change anything in the script itself, but some of the cached resources have changed, and we need to tell the browser that we want to refresh the cache. In order to do this, we’ll change the
cacheVersion number, which will trigger the browser to re-install the Service Worker, triggering our install event, and allowing us to re-downloand and cache all of the updated resources.
Activate
After that, we have a listener on the ‘activate’ event. This gets triggered when our service worker takes control of the context – once it becomes ‘active’. You’ll notice in our ‘install’ event that we’re calling
self.skipWaiting();. The normal behaviour is that when a new Service Worker is installed, it doesn’t take over from the old Service Worker until the page is refreshed. This could be fine for your case, but in many cases, we’ll want to start serving the new resources right away, so we tell the browser to skip waiting for this Service Worker, and activate it immediately, allowing it to take over from the old Service Worker (if any).
In the activate event listener, we then clear out all of our old cache versions, leaving just the specified cache available. You’ll want to take a look at the Cache Interface for more details here.
Finally, once we’ve cleared out the old caches, we post a message back to main thread of any clients we have control over that they should reload, since the cache has been updated (remember the
handleMessage function in the install workers script?). What you want to do with this message will depend on your application, but it could be as simple as calling
location.reload() to get the new resources from the Service Worker.
Fetch
And here’s where the actual offline-enabling functionality happens. You’ll want to take a look at the Fetch API for more details on fetch, but the point here is that we’re intercepting all requests from the client (that’s the browser main thread for our origin), and checking the requested resource name against our cache. If we have the resource, we return it from our cache, and otherwise we pass the request through to the network.
Two things are worth noting here:
- Our fetch intercept catches all requests – not just XMLHTTPRequests, for example, but every single request the main thread makes of the network. There’s a lot that can be done with this – we’re just scratching the surface here.
- The ‘serve from cache if available, and otherwise pass to the network’ is just one potential model for how we can handle caching and serving resources with the Service Worker – see this article on Caching File with Service Worker for some alternative approaches.
Are We There Yet?
Pretty much! Assuming you can mark the other items off the checklists above, your application should now be ready to serve itself as a PWA. To confirm this, you can use the Lighthouse Extension from Google to test your site, and confirm that all is as it should be.
While this gives you a PWA suitable for, say, desktop use, there’s still a few pieces to the puzzle before we’re ready to be assigned real estate on the home screens of Android or iOS devices – we’ll be going into that next time.
Header image by kappuru, licensed under Creative Commons BY-NC-ND 2.0.
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. | https://artandlogic.com/2018/01/pwa-ya-progressive-web-apps-part-1/?shared=email&msg=fail | CC-MAIN-2021-43 | refinedweb | 2,719 | 61.06 |
- NAME
- VERSION
- SYNOPSIS
- DESCRIPTION
- CLASS METHODS
- OBJECT METHODS
- $next_future = $future->then([$on_fulfilled, $on_rejected])
- $next_future = $future->catch([$on_rejected])
- $future = $future->fulfill(@result)
- $future = $future->reject($exception, @details)
- $is_pending = $future->is_pending()
- $is_fulfilled = $future->is_fulfilled()
- $is_rejected = $future->is_rejected()
- EXAMPLE
- DIFFERENCE FROM Q
- SEE ALSO
- BUGS AND FEATURE REQUESTS
- ACKNOWLEDGEMENT
- AUTHOR
- LICENSE AND COPYRIGHT
NAME
Future::Q - a thenable Future like Q module for JavaScript
VERSION
Version 0.050
SYNOPSIS
use Future::Q; sub async_func_future { my @args = @_; my $f = Future::Q->new; other_async_func( ## This is a regular callback-style async function args => \@args, on_success => sub { $f->fulfill(@_) }, on_failure => sub { $f->reject(@_) }, ); return $f; } async_func_future()->then(sub { my @results = @_; my @processed_values = do_some_processing(@results); return @processed_values; })->then(sub { my @values = @_; ## same values as @processed_values return async_func_future(@values); })->then(sub { warn "Operation finished.\n"; })->catch(sub { ## failure handler my $error = shift; warn "Error: $error\n"; });
DESCRIPTION
Future::Q is a subclass of Future. It extends its API with
then() and
try() etc, which are almost completely compatible with Kris Kowal's Q module for Javascript.
Future::Q's API and documentation is designed to be self-contained, at least for basic usage of Futures. If a certain function you want is missing in this module, you should refer to "Missing Methods" section and/or Future. (But be prepared because Future has a lot of methods!)
Basically a Future (in a broad meaning) represents an operation (whether it's in progress or finished) and its results. For further information as to what Future is all about, see:
Terminology of Future States
Any Future::Q object is in one of the following four states.
pending - The operation represented by the Future::Q object is now in progress.
fulfilled - The operation has succeeded and the Future::Q object has its results. The results can be obtained by
get()method.
rejected - The operation has failed and the Future::Q object has the reason of the failure. The reason of the failure can be obtained by
failure()method.
cancelled - The operation has been cancelled.
The state transition is one-way; "pending" -> "fulfilled", "pending" -> "rejected" or "pending" -> "cancelled". Once the state moves to a non-pending state, its state never changes anymore.
In the terminology of Future, "done" and "failed" are used for "fulfilled" and "rejected", respectively.
You can check the state of a Future::Q with predicate methods
is_pending(),
is_fulfilled(),
is_rejected() and
is_cancelled().
then() Method
Using
then() method, you can register callback functions with a Future::Q object. The callback functions are executed when the Future::Q object is fulfilled or rejected. You can obtain and use the results of the Future::Q within the callbacks.
The return value of
then() method represents the results of the callback function (if it's executed). Since the callback function is also an operation in progress, the return value of
then() is naturally a Future::Q object. By calling
then() method on the returned Future::Q object, you can chain a series of operations that are executed sequentially.
See the specification of
then() method below for details.
Reporting Unhandled Failures
Future::Q warns you when a rejected Future::Q object is destroyed without its failure handled. This is because ignoring a rejected Future::Q is just as dangerous as ignoring a thrown exception. Any rejected Future::Q object must be handled properly.
When a rejected but unhandled Future::Q is destroyed, the reason of the failure is printed through Perl's warning facility. You can capture them by setting
$SIG{__WARN__}. The warning messages can be evaluated to strings. (They ARE strings actually, but this may change in future versions)
Future::Q thinks failures of the following futures are "handled".
Futures that
then()or
catch()method has been called on.
Futures that are returned by
$on_fulfilledor
$on_rejectedcallbacks for
then()method.
Subfutures given to
wait_all(),
wait_any(),
needs_all()and
needs_any()method.
So make sure to call
catch() method at the end of any callback chain to handle failures.
I also recommend always inspecting failed subfutures using
failed_futures() method in callbacks for dependent futures returned by
wait_all(),
wait_any(),
needs_all() and
needs_any(). This is because there may be multiple of failed subfutures. It is even possible that some subfutures fail but the dependent future succeeds.
CLASS METHODS
In addition to all class methods in Future, Future::Q has the following class methods.
$future = Future::Q->new()
Constructor. It creates a new pending Future::Q object.
$future = Future::Q->try($func, @args)
$future = Future::Q->fcall($func, @args)
Immediately executes the
$func with the arguments
@args, and returns a Future object that represents the result of
$func.
fcall() method is an alias of
try() method.
$func is a subroutine reference. It is executed with the optional arguments
@args.
The return value (
$future) is determined by the following rules:
If
$funcreturns a single Future object,
$futureis that object.
If
$functhrows an exception,
$futureis a rejected Future::Q object with that exception. The exception is never rethrown to the upper stacks.
Otherwise,
$futureis a fulfilled Future::Q object with the values returned by
$func.
If
$func is not a subroutine reference, it returns a rejected Future::Q object.
OBJECT METHODS
In addition to all object methods in Future, Future::Q has the following object methods.
$next_future = $future->then([$on_fulfilled, $on_rejected])
Registers callback functions that are executed when
$future is fulfilled or rejected, and returns a new Future::Q object that represents the result of the whole operation.
Difference from then() method of Future
Future::Q overrides the
then() method of the base Future class. Basically they behave in the same way, but in
then() method of Future::Q,
the callback funcions do not have to return a Future object. If they do not, the return values are automatically transformed into a fulfilled Future::Q object.
it will not warn you even if you call the
then()method in void context.
Detailed specification
Below is the detailed specification of
then() method.
$on_fulfilled and
$on_rejected are subroutine references. When
$future is fulfilled,
$on_fulfilled callback is executed. Its arguments are the values of the
$future, which are obtained by
$future->get method. When
$future is rejected,
$on_rejected callback is executed. Its arguments are the reason of the failure, which are obtained by
$future->failure method. Both
$on_fulfilled and
$on_rejected are optional.
$next_future is a new Future::Q object. In a nutshell, it represents the result of
$future and the subsequent execution of
$on_fulfilled or
$on_rejected callback.
In detail, the state of
$next_future is determined by the following rules.
While
$futureis pending,
$next_futureis pending.
When
$futureis cancelled, neither
$on_fulfilledor
$on_rejectedis executed, and
$next_futurebecomes cancelled.
When
$futureis fulfilled and
$on_fulfilledis
undef,
$next_futureis fulfilled with the same values as
$future.
When
$futureis rejected and
$on_rejectedis
undef,
$next_futureis rejected with the same values as
$future.
When
$futureis fulfilled and
$on_fulfilledis provided,
$on_fulfilledis executed. In this case
$next_futurerepresents the result of
$on_fulfilledcallback (see below).
When
$futureis rejected and
$on_rejectedis provided,
$on_rejectedis executed. In this case
$next_futurerepresents the result of
$on_rejectedcallback (see below).
In the above two cases where
$on_fulfilledor
$on_rejectedcallback is executed, the following rules are applied to
$next_future.
If the callback returns a single Future (call it
$returned_future),
$next_future's state is synchronized with that of
$returned_future.
If the callback throws an exception,
$next_futureis rejected with that exception. The exception is never rethrown to the upper stacks.
Otherwise,
$next_futureis fulfilled with the values returned by the callback.
Note that the whole operation can be executed immediately. For example, if
$future is already fulfilled,
$on_fulfilled callback is executed before
$next_future is returned. And if
$on_fulfilled callback does not return a pending Future,
$next_future is already in a non-pending state.
You can call
cancel() method on
$next_future. If
$future is pending, it is cancelled when
$next_future is cancelled. If either
$on_fulfilled or
$on_rejected is executed and its
$returned_future is pending, the
$returned_future is cancelled when
$next_future is cancelled.
You should not call
fulfill() or
reject() on
$next_future.
$next_future = $future->catch([$on_rejected])
Alias of
$future->then(undef, $on_rejected).
$future = $future->fulfill(@result)
Fulfills the pending
$future with the values
@result.
This method is an alias of
$future->done(@result).
$future = $future->reject($exception, @details)
Rejects the pending
$future with the
$exception and optional
@details.
$exception must be a scalar evaluated as boolean true.
This method is an alias of
fail() method (not
die() method).
$is_pending = $future->is_pending()
Returns true if the
$future is pending. It returns false otherwise.
$is_fulfilled = $future->is_fulfilled()
Returns true if the
$future is fulfilled. It returns false otherwise.
$is_rejected = $future->is_rejected()
Returns true if the
$future is rejected. It returns false otherwise.
EXAMPLE
try() and then()
use Future::Q; ## Values returned from try() callback are transformed into a ## fulfilled Future::Q Future::Q->try(sub { return (1,2,3); })->then(sub { print join(",", @_), "\n"; ## -> 1,2,3 }); ## Exception thrown from try() callback is transformed into a ## rejected Future::Q Future::Q->try(sub { die "oops!"; })->catch(sub { my $e = shift; print $e; ## -> oops! at eg/try.pl line XX. }); ## A Future returned from try() callback is returned as is. my $f = Future::Q->new; Future::Q->try(sub { return $f; })->then(sub { print "This is not executed."; }, sub { print join(",", @_), "\n"; ## -> a,b,c }); $f->reject("a", "b", "c");
DIFFERENCE FROM Q
Although Future::Q tries to emulate the behavior of Q module for JavaScript as much as possible, there is difference in some respects.
Future::Q has both roles of "promise" and "deferred" in Q. Currently there is no read-only future like "promise".
Future::Q has the fourth state "cancelled", while promise in Q does not.
In Future::Q, callbacks for
then()method can be executed immediately. This is because Future::Q does not assume any event loop mechanism.
In Future::Q, you must pass a truthy value to
reject()method. This is required by the original Future class.
Missing Methods
Some methods in Q module are missing in Future::Q. Some of them worth noting are listed below.
- promise.fail()
Future already has
fail()method for a completely different meaning. Use
catch()method instead.
- promise.progress(), deferred.notify(), promise.finally(), promise.fin()
Progress handlers and "finally" callbacks are interesting features, but they are not supported in this version of Future::Q.
- promise.done()
Future already has
done()method for a completely different meaning. There is no corresponding method in this version of Future::Q.
- promise.fcall() (object method)
Its class method form is enough to get the job done. Use
Future::Q->fcall().
- promise.all(), promise.allResolve(), promise.allSettled()
Use
Future::Q->needs_all()and
Future::Q->wait_all()methods inherited from the original Future class.
- deferred.resolve()
This is an interesting method, but it's not supported in this version of Future::Q. Call
fulfill()or
reject()explicitly instead.
- Q()
Use
Future::Q->wrap()method inherited from the original Future class.
SEE ALSO
- Future
Base class of this module. Future has a lot of methods you may find interesting.
- Future::Utils
Utility functions for Futures. Note that the error handling mechanism of Future::Q may not work well with Future::Utils functions.
- IO::Async::Future
Subclass of Future that works well with IO::Async event framework.
- Promises
Another promise/deferred/future/whatever implementation. Its API is more like jQuery's promises than Q. For the difference between jQuery.promise and Q, check out
- AnyEvent::Promises
Another port of Q (implementation of Promises/A+) in Perl. This module is more similar to Q than Future::Q. It depends on AnyEvent.
BUGS AND FEATURE REQUESTS
Please report bugs and feature requests to my Github issues
ACKNOWLEDGEMENT
Paul Evans,
<leonerd at leonerd.org.uk> - author of Future
AUTHOR
Toshio Ito,
<toshioito at cpan.org>
LICENSE AND COPYRIGHT
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See for more information. | https://metacpan.org/pod/release/TOSHIOITO/Future-Q-0.050/lib/Future/Q.pm | CC-MAIN-2015-35 | refinedweb | 1,974 | 50.12 |
This section contains information about a central concept of an EPiServer CMS project, namely that of blocks, block types and block templates.
This is how it works:
- A block type defines a set of properties.
- A block is an instance of the .NET class that defined the block type.
- At runtime a block can exist either as a property on a page or as a global block.
- When creating a global block or editing a page that contains a block the editor assigns values to the properties defined by the block type.
- When a page that contains a block is requested by a visitor, the renderer (can be a user control or a web control) associated with the block type is used to generate output.
Block type
During initialization EPiServer CMS will scan all binaries in the bin folder for .NET classes that inherits BlockData as example below. For each of the found classes a block type is created and for all public properties on the .NET class a corresponding property on the block type will be created.
[ContentType] public class PageList : BlockData { public virtual PageReference Root { get; set; } public virtual int Count { get; set; } public virtual string Heading { get; set; } }
Blocks can be reused on several pages as in the following example where PageList is a defined block.
[ContentType] public class NewsPage : PageData { public virtual PageList Archive { get; set; } } [ContentType] public class EventPage : PageData { public virtual PageList Archive { get; set; } }
Block template
A block template is used to generate output for blocks of a given type, often as an .ascx type of file or a web control. A block template can be used for more than one block type but a one-to-one connection is the most common approach. Below is an example of a template for a block.
[TemplateDescriptor(Name = "My block control", Description = "My first block control", Path = "~/templates/MyBlockControl.ascx", Default = true)] public partial class MyBlockControl : BlockControlBase<PageList> { protected TextBox HeadingControl; protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); HeadingControl.Text = CurrentBlock.Heading; } }
A central function of any block template is to access the property values of the block so that they can be integrated into the output, so how do you accomplish that? This is where the base classes and User Controls come into play. In the following you will find an example based on a web form block template.
Within the EPiServer CMS API there are some base classes that your web control can inherit from, but BlockControlBase<T> is the most common selection for usercontrols and implementing IBlockControl<T> is the common approach for web controls.
Access to the CurrentBlock property is probably the most important benefit you get from inheriting from BlockControlBase<T> (or IBlockControl<T> for web controls). You will find yourself accessing this property many times when you are writing User Controls for an EPiServer CMS project. So what is it? The type of the CurrentBlock property is an instance of your .NET class that inherits EPiServer.Core.BlockData. A BlockData object is the programmatic representation of a block in EPiServer, it contains the properties defined in your .NET class. The value of CurrentBlock is automatically set to the BlockData object that is requested by the client. This means that you don't have to find out what page you should be fetching property values from yourself, all you need to do is consume the property values from the CurrentBlock object.
Shared blocks
A block is a .NET type inheriting EPiServer.Core.BlockData. A block instance can either be part of a page instance (in case a PageType or BlockType contains a property of the block type) or it can be a shared instance. A block that is part of a page instance is stored, versioned, loaded etc, as part of the page. A shared block on the other hand is stored, versioned, loaded individually as an own entity. A shared block can be referenced from several pages or blocks.
Shared blocks structure
Shared blocks are structured with use of folders. A folder in the shared blocks structure can have other folders or Shared Blocks as children. A Shared Block can not have any children. The editorial access is set on the folders to specify which folders that should be available for the editor. There is a global folder root given by EPiServer.Core.SiteSettings.Current.GlobalBlocksRoot that is the root folder for Shared Blocks that should be available for all sites in an enterprise scenario. There might also exist a site specific folder EPiServer.Core.SiteSettings.Current.SiteBlocksRoot that contains the folder structure for shared blocks that are site specific. In a single site scenario typically the GlobalBlocksRoot and SiteBlocksRoot points to the same folder.
A Folder is an instance of EPiServer.Core.ContentFolder and is used to structure content. A content folder does not have any WebForm or MVC controller associated and hence it does not have any visual appearance on the site.
See also
- Creating page templates and block controls | https://world.episerver.com/documentation/Items/Developers-Guide/Episerver-CMS/75/Content/Block-types-and-templates/ | CC-MAIN-2018-05 | refinedweb | 836 | 55.13 |
Note from the editor: Want to give Tony's Dial-a-Carol service a try? We'll be hosting it throughout December for you to call! Just dial ?? (44)-203-905-1327 or ?? (1)-201-355-3236 and spread some Christmas cheer!
It's nearly Christmas and another year has almost gone!
I thought I would see out the year with a fun and easy piece of Python code to allow you to dial a Christmas carol to put a smile on your face - or make you cringe...
Here's the main idea:
- You dial a Nexmo Number
- You hear a selection menu
- You make your choice
- You hear a cringeworthy carol!
Awesome!
Getting Set Up<<
If you've not played with Nexmo to date I recommend our documentation as a first port of call.
I am also going to assume you know how to configure your webhooks. Also you can host your webhook server on a platform of your choice, or you can test locally using Ngrok. If you've not used Ngrok before I recommend you take a look at our Ngrok tutorial blog post and also read our documentation on it.
Configuring Your Webhooks
So, you are now ready to make sure you configure your webhooks. I will assume you are testing locally with Ngrok and you have them set along the following lines:
Webhook | URL
---- | ----
answer |
event |
NOTE: This assumes your webhook server is running on port 3000, but it can be any suitable port.
There is one other webhook of interest in this tutorial, but you don't set it in the same way you set the Answer webhook or Event webhook URLs. It's the DTMF webhook that you will see in the next section.
The Answer Webhook
When you dial into your Nexmo Number, you will hear an option menu. You can then select your carol by pressing a key on your phone keypad. This input is sent to your application via a
POST on the DTMF webhook, which has the form.
So how does Nexmo know how to call back on this URL? You have to set the DTMF webhook in your Answer webhook code.
Looking at the Answer webhook you see the following:
)
Looking at this code you can see that when your inbound call is answered, the NCCO that controls the call sends you the option menu via Nexmo's Text-To-Speech capabilities, and also sets the DTMF webhook. This is how Nexmo knows where to call back on with input from the phone keypad.
There's also a couple of parameters specified. The
timeOut parameter in this case is set to slightly longer than the default of three seconds. In this case it gives you a five second period in which to respond with a key press before the system times out on waiting for input.
maxDigits in this will make sure only one digit is accepted as input.
The other parameter worth mentioning is
bargeIn which is set to
true in this case. This allows you to interrupt the option menu for those instances when you simply can't wait to hear your favourite carol!
There is also more detailed documentation on DTMF you can read at your leisure. I just covered the basics here.
The DTMF Webhook
You just saw how the Answer webhook works. Now you'll see how the DTMF webhook works.
First here's the code:
)
You can see we are only interested in a
POST callback on this URL. Mostly this code is to make sure we handle the case where the user doesn't enter an option at all, or selects an option that's outside of the range presented in the option menu. The real action happens again in the NCCO.
In the NCCO there is a little prompt message which announces which carol is going to be played. Then the
stream action is used to play an MP3 file into the call. This feature is quite useful for things like on-hold music and so on, but we can use it in this case to get our festive fix. You only need to specify the URL and the music is, by amazing Nexmo magic, played into your call.
The Complete Code
I've covered the most important parts of the code. Here's the complete code for your convenience:
#!/usr/bin/env python3 from flask import Flask, request, jsonify from pprint import pprint app = Flask(__name__) base_url = '' # Tunes courtesy tunes = [ ["Little Town of Bethlehem", "bethlem-jazz.mp3"], ["Ding Dong Merrily", "ding-dong-merrily.mp3"], ["First Noel", "first-noel-r-and-b.mp3"], ["Jingle Bells", "jingle-bells-country.mp3"], ["Silent Night", "silent-night-piano.mp3"], ["Twelve Days of Christmas", "twelve-days-funk.mp3"] ] # Build options menu menu = "Welcome to dial a Christmas carol. You can choose from the following cheesy carols." i = 1 for t in tunes: menu = menu + " Option " + str(i) + " is " + t[0] +"." i = i + 1 menu = menu + " Please make your selection now." ) @app.route("/webhooks/event", methods=['POST']) def events(): data = request.get_json() pprint(data) return ("OK") if __name__ == '__main__': app.run(port=3000)
Once you have your application running, just dial into Nexmo using your Nexmo Number, make your selection from the options provided via your phone keypad, and listen to some festive fun.
So, I hope you have enjoyed this Christmas code.
I would like to take this opportunity to wish you all a very Merry Christmas and a Happy New Year!
Where next?
The source code is available on GitHub: * Dial a Carol source code
Here are some resources that will be useful if you want to explore things further:
* NCCO Reference - this describes the
input action in detail.
* Ngrok tutorial - a useful guide to testing your app locally.
* Webhooks - everything you ever wanted to know about Webhooks but were afraid to ask. | https://developer.vonage.com/blog/18/12/03/dial-a-christmas-carol-with-nexmo-and-python-dr | CC-MAIN-2022-40 | refinedweb | 979 | 72.36 |
Precaching in Create React App with Workbox
Caching assets with a service worker can speed up repeat visits and provide offline support. Workbox makes this easy and is included in Create React App by default.
If you don't yet understand the basic idea behind service workers and precaching, read the Precaching with Workbox guide first.
Workbox is built into
Create React App (CRA) with a default configuration that precaches all the
static assets in your application with every build.
Why is this useful?
Service workers enable you to store important resources in its cache (precaching) so that when a user loads the web page for a second time, the browser can retrieve them from the service worker instead of making requests to the network. This results in faster page loads on repeat visits as well as the ability to surface content when the user is offline.
Workbox in CRA
Workbox is a collection of tools that allow you create and maintain service
workers. In CRA, the
workbox-webpack-plugin
is already included into the production build and only needs to be enabled in
the
src/index.js file in order to register a new service worker with every
build:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
Here is an example of a React app built with CRA that has a service worker enabled through this file:
In order to see which assets are being cached:
- Mouse over the editor and press the Show button to preview the app.
- Open the DevTools by pressing
CMD + OPTION + i/
CTRL + SHIFT + i.
- Click on the Network tab.
- Reload the application.
You'll notice that instead of showing the payload size, the
Size column shows
a
(from ServiceWorker) message to indicate that these resources were retrieved
from the service worker.
Since the service worker caches all static assets, try to use the application while offline:
- In the Network tab in DevTools, enable the Offline checkbox to simulate an offline experience.
- Reload the application.
The application works in exactly the same way, even without a network connection!
Modifying caching strategies
The default precaching strategy used by Workbox in CRA is cache-first, where all static assets are fetched from the service worker cache and if that fails (if the resource is not cached for example), the network request is made. This is how content can still be served to users even when they are in a complete offline state.
Although Workbox provides support to define different strategies and approaches
to caching static and dynamic resources, the default configuration in CRA cannot
be modified or overwritten unless you eject entirely. However, there is an
open proposal
to explore adding support for an external
workbox.config.js file. This
would allow developers to override the default settings by just creating a
single
workbox.config.js file.
For more details on all the caching strategies that a service worker can use, take a look at the Offline Cookbook.
Handling a cache-first strategy
Relying on the service worker cache first and then falling back to the network is an excellent way to build sites that load faster on subsequent visits and work offline to some extent. However, there are a few things that need to be taken into consideration:
- How can caching behaviours by a service worker be tested?
- Should there be a message for users to let them know they are looking at cached content?
The CRA documentation explains these points, and more, in detail.
Conclusion
Use a service worker to precache important resources in your application to provide a faster experience for your users as well as offline support.
- If you are using CRA, enable the pre-configured service worker in
src/index.js.
- If you are not using CRA to build a React application, include one of the many libraries Workbox provides, such as
workbox-webpack-plugin, into your build process.
- Keep an eye out for when CRA will support a
workbox.config.jsoverride file in this GitHub. | https://web.dev/precache-with-workbox-react | CC-MAIN-2019-22 | refinedweb | 686 | 52.29 |
A Developer's Notebook
Two months ago, after listening to .NET Rocks! show with Daniel Simmons, I was really curious to learn more about ADO.NET Entity Framework (EF). As part of my learning I was ready to write a tutorial on how to get started with this framework. However there were no tools available at the time and with instructions on how to manually edit XML files the article turned very long, and quite frankly looked very boring. Hence I decided to postpone publishing it and wait for the tools to came out.
This week Microsoft released ADO.NET Entity Framework Beta 2. You can find the complete release notes on the ADO.NET Team Blog so I won’t repeat it here. What’s more important we finally get the first CTP of Entity Framework Tools. So now I have all the pieces to attempt to write my tutorial again.
• • •
Microsoft went a long road to get into the ORM space starting with ObjectSpaces, then WinFS and now LINQ and Entity Framework. For those interested in the full story here is nice article from one of the authors. Even though I'm by no means an ORM expert, I've worked before with number of both commercial and open source systems falling into this category.
According to ADO.NET team Entity Framework is much more then just another ORM tool. The aim here is to solve a more generic problem of mapping conceptual model to application logic which is prevalent not only in storing programming objects but also in such areas as data replication, remoting and reporting. Which EF you maintain a single conceptual model of your domain objects (called entities here) that can be later mapped and reused with other representation.
To learn new technology I usually develop a sample project so I have some well defined goal to achieve. This time again I choose to work with the PetShop 4.0 sample application. I prefer this sample for several reasons:
Besides Northwind and Adventure Works are already mapped as EF samples so it would be no fun in using them.
Working with Entity Framework involves creating three schemas for your data:
1. Conceptual Schema (CSDL) — represents the conceptual model of your data, that is entities and their relationships (in current version this maps 1:1 to the generated object model).
2. Storage Metadata Schema (SSDL) — describes the representation of your data when its stored in the database (or other storage media).
3. Mapping Specification (MSL) — as you can already guess this one describes how to map data from one of the above schemas to the another.
All three are now defined as part of single XML document that will be part of your project (edmx).
The normal workflow for Entity Framework should start with first creating the concept model of entities and then work the storage and mapping schemas from there. However in many cases you will be working with existing applications, so it would be more convenient to start from the database schema instead. This release of EF targets this "data first" scenario with the EDM Wizard built in Visual Studio.
As I said before PetShop uses four databases: product inventory, orders, and two for ASP.NET users and profiles. For now I will concentrate on the first one. So to begin with let's see how this database looks like:
As you see this database is extremely simple: each category has multiple products, that in turn hold multiple items. Each product item points to its supplier and there is additional table that holds current inventory count.
Okay, I'm ready to create the entity model. First I've created a new C# class library project, and then from the Add New Item dialog selected the ADO.NET Entity Data Model template. This starts the Entity Data Model Wizard where in first step we select either to generate model from database or to create empty one:
After selecting the first option we go to the next step when we need to specify the connection string to our database:
Note that the connection string used by the EF besides the typical settings for ADO.NET also contains paths to all three schema files.
In the last step we can select which tables, views and stored procedures should be included in the generated model (in this case I want to include all tables besides the AspNet_SqlCacheTablesForChangeNotification). We can also specify the namespace for the generated classes:
After pressing the Finish button the wizard generates the entity model (the PetShopModel.edmx file) and adds all required references to the project. In the previous version the wizard didn't worked very well and you'd had to use the command line tool called EDM Generator (edmgen.exe) to get these files. This time things changed for good so lets look at what was generated.
When we open this file from the Solution Explorer we can finally see our enities inside the EDM Designer (click on image to enlarge):
Notice that although this model looks very similar to the database model shown earlier it actually shows entities not tables. So besides the scalar properties that are mapped to the table columns we also have the navigational properties mapped to table relationships. There is also a new tab next to the Solution Explorer called Entity Model Browser that displays the structure of the model. We can see here that this model includes both the conceptual (entity) and storage schema. Finally at the bottom we see new window titled Entity Mapping Details that displays how the two schemas are mapped.
In the second part I will look at how we can modify the generated model to align it with our concept model and at the same time learn how to use this designer. Stay tuned!
Skin design by Mark Wagner, Adapted by David Vidmar | http://geekswithblogs.net/kobush/archive/2007/08/29/GettingStartedWithEntityFramework_1.aspx | CC-MAIN-2014-15 | refinedweb | 982 | 61.87 |
Was wondering if someone could offer me some advice..
I am trying to evaluate sin(x) using the recurrence relation sin(ny) = 2cos(y)sin((n-1)y)-sin((n-2)y).
The problem states that i take y = 0.01 and cos(y) = 1 - x^2/2, and obviously for a small x, sinx = x.
I have so far attempted to do this using the function below, however the results it provides are either wrong, or the program gets stuck repeatedly calling itself. I think the problem may well lie in my criteria for if x is small, but i can't figure out a another way.
So i ask: Does this seem likely? Should i start over? What stupid thing(s) am i doing?
thanks a lot
Code:
(meanwhile in main...)
result = sin_recur(n, y);
...
double sin_recur(double n, double y)
{
double x = n*y;
if( x <= 0.0001 && x >= -0.0001) //for small x, sin(x) = x
return x;
else if(x == 0.0) //sin(0) = 0
return 0;
else
return (2 - (x*x))*(sin_recur(n-1, y)) - sin_recur(n-2, y) ; //use recurrence relation
} | http://cboard.cprogramming.com/c-programming/132449-recurrence-problem-printable-thread.html | CC-MAIN-2016-18 | refinedweb | 188 | 77.84 |
Metadata lock object key. More...
Metadata lock object key.
A lock is requested or granted based on a fully qualified name and type. E.g. They key for a table consists of <0 (=table)>+<database>+<table name>. Elsewhere in the comments this triple will be referred to simply as "key" or "name".
Object namespaces.
Sic: when adding a new member to this enum make sure to update m_namespace_to_wait_state_name array in mdl.cc!
Different types of objects exist in different namespaces
Compare two MDL keys lexicographically.
Get thread state name to be used in case when we have to wait on resource identified by key.
Construct a metadata lock key from a triplet (mdl_namespace, database and name).
Construct a metadata lock key from a quadruplet (mdl_namespace, database, table and column name).
Construct a metadata lock key from a quadruplet (mdl_namespace, database, normalized object name buffer and the object name).
Routine, Event and Resource group names are case sensitive and accent sensitive. So normalized object name is used to form a MDL_key.
With the UTF8MB3 charset space reserved for the db name/object name is 64 * 3 bytes. utf8_general_ci collation is used for the Routine, Event and Resource group names. With this collation, the normalized object name uses just 2 bytes for each character (max length = 64 * 2 bytes). MDL_key has still some space to store the object names. If there is a sufficient space for the object name in the MDL_key then it is stored in the MDL_key (similar to the column names in the MDL_key). Actual object name is used by the PFS. Not listing actual object name from the PFS should be OK when there is no space to store it (instead of increasing the MDL_key size). Object name is not used in the key comparisons. So only (mdl_namespace + strlen(db) + 1 + normalized_name_len + 1) value is stored in the m_length member.
Construct a metadata lock key from namespace and partial key, which contains info about object database and name.
Check if normalized object name should be used.
Thread state names to be used in case when we have to wait on resource belonging to certain namespace. | https://dev.mysql.com/doc/dev/mysql-server/latest/structMDL__key.html | CC-MAIN-2019-43 | refinedweb | 357 | 74.19 |
On Fri, 11 Jan 2008 10:59:18 -0500Lee Schermerhorn <Lee.Schermerhorn@hp.com> wrote:> On Fri, 2008-01-11 at 10:42 -0500, Rik van Riel wrote:> > On Fri, 11 Jan 2008 15:24:34 +0900> > KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> wrote:> > > > > below patch is a bit cleanup proposal.> > > i think LRU_FILE is more clarify than "/2".> > > > > > What do you think it?> > > > Thank you for the cleanup, your version looks a lot nicer. > > I have applied your patch to my series.> > > > Rik: > > I think we also want to do something like:> > - BUILD_BUG_ON(LRU_INACTIVE_FILE != 2 || LRU_ACTIVE_FILE != 3);> + BUILD_BUG_ON(LRU_INACTIVE_FILE != 2 || LRU_ACTIVE_FILE != 3 ||> + NR_LRU_LISTS > 6);> > Then we'll be warned if future change might break our implicit> assumption that any lru_list value with '0x2' set is a file lru.Restoring the code to your original version makes things work again.OTOH, I almost wonder if we should not simply define it to return (l == LRU_INACTIVE_FILE || l == LRU_ACTIVE_FILE)and just deal with it.Your version of the code is correct and probably faster, but not aseasy to read and probably not in a hot path :)-- All rights reversed. | https://lkml.org/lkml/2008/1/11/211 | CC-MAIN-2015-11 | refinedweb | 188 | 65.83 |
May 16, 2006 01:53 AM|vcsjones|LINK
If you need to use a true array instead of using an ArrayList, you can use the static method Array.Resize<T>() to resize an array. Here is an example:
string[] strings = new string[4]; Console.WriteLine(strings.Length); //Should write 4 Array.Resize<string>(ref strings, 6); Console.WriteLine(strings.Length); //Should write 6 Console.ReadLine();
If you will notice line 3 you will see the Array.Resize method. It requires 1 type arguement and 2 parameters. You will see that the array I am working with is a string array so the type arguement is a string <string> if it was a int array, you would use <int>. The first parameter is the array you want to resize. You must pass it by reference using the ref keyword. The second arguement is the new size.
May 16, 2006 05:32 AM|vcsjones|LINK
Instead of declaring it at compile time, declare it at runtime, like this:
using System; public class Program { string[] strings; public static void Main(string[] args) { int arraySize = 4; strings = new string[arraySize]; } }
arraySize is just an example. You could pull it from a parameter, or whatever.
May 16, 2006 08:45 AM|vcsjones|LINK
You can still do that. Set arraySize to the count of items.
It seems like you may be better using a List<string> because you can convert them to a standard array by using ToArray(). List<> is completely dynamic and resizable.
Member
457 Points
May 17, 2006 03:46 AM|vcsjones|LINK
May 17, 2006 05:29 AM|vcsjones|LINK
Well, except for the obvious when you shrink an array. If you have an array that is 6 items in length and resize it to 4, you will loose the last two.
Member
352 Points
10 replies
Last post Jun 29, 2010 04:55 PM by rossman308 | http://forums.asp.net/t/990581.aspx?Creating+a+Dynamic+Array | CC-MAIN-2014-49 | refinedweb | 315 | 74.79 |
If a method arg is a closure, for crying out loud pass it a closure
March 10, 2015 7 Comments
This is a (mildly) embarrassing post, because it demonstrates how in my transition to functional programming I missed something important. I get it now, though, and I might as well help others avoid the same mistake I made.
I teach a lot of Grails training classes, and one question that always comes up is how to map to existing databases rather than generate the schema from the Grails application. Hibernate (and therefore Grails) would love to generate the database schema for you, for a variety of reasons, but mostly because going the other way isn’t unique. You have to make a lot of decisions about a domain model when you reverse-engineer an existing schema, ranging from multiplicities in relationships to how to map many-to-manys to directionality and more.
In my standard Grails course, rather than create a database we can map to, I go with an existing, freely available sample. For years I’ve chosen the Sakila sample database from MySQL.
(As an aside, it took me years to realize that the word Sakila is actually intended to be a subtle joke. It’s the letters SQL with some vowels thrown in to make it possible to pronounce the word, with the “Q” replaced by a “k”. Go figure. As it turns out, it’s also the name of their dolphin emblem, but that’s neither here nor there.)
Over the years I’ve tried to map the Sakila schema to a Grails domain model, with varying degrees of success. I think I have it all worked out now, but that’s the subject for another blog post. Here, instead, I want to talk about stored procedures.
Many of my clients want to use Grails with a database that has lots of stored procedures in it. Hibernate doesn’t like that. Hibernate wants to map all the domain classes directly to tables, without going through any possible intermediaries. While it is possible to invoke a stored procedure from Hibernate, it’s a bit awkward, mostly because Hibernate doesn’t want to do it.
(Length of Java Persistence Using Hibernate: about 850 pages. Number of pages that discuss stored procedures: about 5.)
That’s where Groovy (as opposed to Grails) comes in. The Groovy API includes the wonderful
groovy.sql.Sql class, which is a simple, but effective, façade over JDBC. That class will open and close connections, eliminate all the annoying boilerplate code associated with JDBC, and more. If I ever have to write raw SQL code, I always switch to
groovy.sql.Sql rather than use JDBC.
(That’s not quite true. The
JdbcTemplate class from Spring is nearly as helpful. If I don’t have Groovy available and I have to do JDBC, I go with that.)
Let me get specific. The Sakila database represents a video store (which shows how old that is). It has tables representing stores, and inventory, and actors, and films, and more. But it also contains a handful of stored procedures, one of which is called
film_in_stock. According to the documentation, the
film_in_stock procedure takes two input parameters (the id of the film and the id of a store) and one output parameter (the number of copies of that film currently at that store). The example they show is:
mysql> call film_in_stock(1, 1, @count); +--------------+ | inventory_id | +--------------+ | 1 | | 2 | | 3 | | 4 | +--------------+ 4 rows in set (0.06 sec) Query OK, 0 rows affected (0.06 sec) mysql> select @count; +--------+ | @count | +--------+ | 4 | +--------+ 1 row in set (0.00 sec)
There are four copies of film 1 (“Academy Dinosaur”) at store 1 (a store at “47 MySakila Drive” in Alberta). This provides me with a test case:
import spock.lang.* class StoreProcServiceIntegrationSpec extends Specification { def storedProcService // inject the service void "call film_in_stock stored procedure"() { expect: storedProcService.callFilmInStock(1, 1) == 4 } }
This assumes my call to the stored procedure happens in a class called
StoredProcService. I have to use an integration test here, because I want to use the real database, but that means I can rely on Spring dependency injection to get the service into the test.
To access the Sakila database from a Grails app, I configured my
conf/DataSource.groovy file to include the
dataSource properties:
import org.hibernate.dialect.MySQL5InnoDBDialect dataSource { pooled = true jmxExport = true driverClassName = "com.mysql.jdbc.Driver" username = "root" password = "" dialect = MySQL5InnoDBDialect } // ... environments { development { dataSource { dbCreate = "validate" url = "jdbc:mysql://localhost:3306/sakila" } } test { dataSource { dbCreate = "validate" url = "jdbc:mysql://localhost:3306/sakila" } } // ... }
(Yeah, I have super high security on this database. Don’t even think about breaking in. You’d never guess that the
root user has no password whatsoever. I mean, who would do such a ridiculous thing?)
So the default data source in my Grails app is the Sakila database, using a MySQL driver that I have listed in the
conf/BuildConfig.groovy file:
dependencies { runtime 'mysql:mysql-connector-java:5.1.29' test "org.grails:grails-datastore-test-support:1.0-grails-2.4" }
Again, nothing terribly unusual here.
The key observation is that the
dataSource reference in the config file refers to a Spring bean, which can be injected in the usual manner. So I created a Grails service called
StoredProcService and specified the
dataSource bean as a dependency.
@Transactional class StoredProcService { def dataSource // ... }
The GroovyDocs for the Groovy API show that the
groovy.sql.Sql class has a constructor that takes a data source, so I’m all set. Then, to call the stored procedure, I need to invoke the
call method from that class.
This is where life gets interesting, and ultimately tricky. The procedure I want to call has both input and output parameters, so my call has to take that into account. It turns out that the way to call a stored procedure with both inputs and outputs is to invoke:
void call(String sql, List<Object> params, Closure closure)
The SQL string uses the JDBC escape syntax for stored procedure calls. The
params list take the input parameters and placeholders for the output parameters, and the closure is then invoked with the output parameters.
Wait, what? That’s a little fast. Here’s the actual call, or at least this is the version I had before last weekend:
import groovy.sql.Sql @Transactional class StoredProcService { def dataSource int callFilmInStock(filmId, storeId) { String sqlTxt = '{call film_in_stock(?,?,?)}' // JDBC escape syntax Sql db = new Sql(dataSource) // use the injected datasource db.call(sqlTxt, [filmId, storeId, Sql.INTEGER]) { count -> // use the count here } } }
The
Sql class provides constants like “
static OutParameter INTEGER” to represent output variable in the stored procedure call. Then the last argument is a closure that has as many arguments as there are output parameters (in this case, one, which I called
count).
Now, though, I have a problem. I’d like my
callFilmInStock method to return the result of invoking the
film_in_stock stored procedure, i.e., the count of films at that store. The problem is, I can’t just say
return count inside that closure, because returning from a closure returns only from the closure, not the calling method.
I’ve blogged about that before, and even submitted a variation to Baruch Sadogursky as a Groovy Puzzler, but this is where I first encountered that problem.
My solution was always to create a local variable outside the call, assign the count to that variable, and return the variable:
int callFilmInStock(filmId, storeId) { String sqlTxt = '{call film_in_stock(?,?,?)}' // JDBC escape syntax Sql db = new Sql(dataSource) // use the injected datasource int result = 0 db.call(sqlTxt, [filmId, storeId, Sql.INTEGER]) { count -> result = count } return result }
This works, and (sigh) I’ve been teaching this approach for some time now. I’ve always been uncomfortable with it, though, and when I started digging into Java 8 lambdas I realized why. I’m using a closure here and relying on it having a side effect, which is to modify a variable defined outside the closure. In fact, in Java 8, lambdas are definitely not supposed to do that. The only variables lambdas are supposed to access from outside the lambda are those that are “effectively final”, meaning they’re never modified. Groovy closures don’t have that limitation, but I still had this nagging feeling that I was, as they say, doing it wrong.
Last weekend, the new NFJS season started for me in Minneapolis, and I got a chance to talk about this to the inimitable Venkat Subramaniam, who writes books on this stuff (among other things). After I explained the problem, he thought about it for about five whole entire minutes and said that I should be passing the method a closure, not returning an integer.
The right way to write my service function is to add a closure to the method signature and use it in the sql call:
void callFilmInStock(filmId, storeId, closure) { String sqlTxt = '{call film_in_stock(?,?,?)}' // JDBC escape syntax Sql db = new Sql(dataSource) // use the injected datasource db.call(sqlTxt, [filmId, storeId, Sql.INTEGER], closure) }
Wow, that’s so much simpler. The client now passes in a closure that uses the returned value, rather than trying to kludge returning the value itself. That means the test case becomes:
void "call film_in_stock stored procedure"() { expect: storedProcService.callFilmInStock(1, 1) { count -> assert count == 4 } }
(This uses the normal Groovy idiom where a method taking a closure as its last argument can put the closure after the parentheses.)
This test passes just as the previous one did, even though the method return type is now
void.
That’s the part I never got before. The
groovy.sql.Sql.call(String, List, Closure) method takes a closure as its last argument, which means I can supply the closure myself and the method will use it with the returned
count.
When I learned about functional programming, I got the idea of transforming collections rather than iterating over them, and using filters to select only the values I want, and reducing the results down to single values. I got that I’m supposed to favor immutability wherever possible. What I apparently hadn’t grokked was sending closures as method arguments and how that simplified everything. I’m still not sure I’m all the way there, but I’m certainly a lot closer now.
Over the weekend I tweeted that Venkat had fundamentally changed my understanding of functional programming, which is both cool and seriously annoying. Frankly, those are also words I would use to describe Venkat. If he wasn’t such a nice guy, he would be insufferable, mostly due to sheer jealousy. But we rapidly learn on the NFJS tour never to compare ourselves to Venkat in any way or you’ll just drive yourself crazy. Just don’t tell him I said that.
Now I have to go update my Grails materials…
Very cool stuff. There’s a plugin for that (TM) that will help to reduce a lot of the tedious work of mapping existing tables:, and I did use Sakila as one of the test databases when developing the plugin. Also, tangentially related – I discovered recently that they’re doing a new edition of Java Persistence with Hibernate:
I’ve recommended your db-reverse-engineer plugin many times. I’ve had difficulty applying it to Sakila, though, mostly because Sakila uses some odd datatypes. I’ll discuss that in a different blog post.
I am subscribed to the second edition of Java Persistence with Hibernate, but haven’t yet spent a lot of time with it.
Great to hear from you, btw. I’m still waiting for you to publicly announce what you’re doing these days. 🙂
Thanks Ken, glad I stumbled on this. This seems like “closure as method argument” implies “separate the logic of the computation itself from ‘what to do with the result’ and ‘how to obtain the input'” (Chiusano, Bjaranson, “Functional Programming in Scala”, pp. 12). Surprised how much I still learn every day, after all these years.
Ty — You and me both, friend. 🙂 Thanks for your comment.
So, I’ve used the former pattern for calling a stored procedure in Oracle and had the same vague unease about it. Still, when what you want is the return value of a stored proc, your original pattern seems to be the most straightforward way to get it. The new pattern definitely makes your app more functional, and in other scenarios, I could see that being a good thing. But for this case, where the result comes from a horribly stateful place (the database), doesn’t functional modeling ultimately just push the problem up to the client?
Sure, if most of your use cases _want_ to pass the result of the stored procedure through a closure, then this is great. But if all you really want is to get the count, then the client is going to be crafting a closure to modify a variable outside of the closure’s scope, just like before. And worse, you may end up doing that in every place you call the procedure, which means your app isn’t as DRY as it could be. If what you want is the count, why not construct the method to return the count, warts and all? At least then you’ve isolated the expectation of getting a count back, rather than proliferating it throughout your code.
It could very well be that I haven’t fully grokked the power of functional programming for this case. Still, I’d posit that this kind of interaction with the DB is precisely where the capacity for Groovy to switch freely between functional and OO (even imperative) styles would shine. Though that could just be me being a Gary Bernhardt sycophant (viz).
Pingback: Diario di Grails (settimana 11 del 2015) | BME
As I’ve talked to some functional people, I agree that a big part of the issue is the awkwardness of the API. The call method returns void, and that’s part of the problem. If it returned an object, or even a list, then this situation would be much easier.
As you say, the existing design favors an OO (or even imperative) approach, and trying to do it “correctly” with the functional approach may be overkill.
In the end, I’d say I agree with you. 🙂 | https://kousenit.org/2015/03/10/if-a-method-arg-is-a-closure-for-crying-out-loud-pass-it-a-closure/ | CC-MAIN-2017-34 | refinedweb | 2,406 | 62.98 |
.
How about... (Score:1)
Oopsies (Score:1)
HeilBuchanan.com! Yes! Yes! Oh, yes. (Score:1)
I wonder if you could register HeilBuchanan.com?
Better would be to do a bunch of blatantly and sincerely neo-nazi domain names, with lots of neo-nazism on 'em, and pack the meta tags with perfectly normal Bush and Buchanan crapola. (I mean, as "normal" as Buchanan gets. When he's speaking to a national audience he usually does pull up short of neo-nazism.) So anyway, suck a lot of mainstream, timid voters into a fake neo-nazi web site and have ringing endorsements of Bush and Buchanan. But make them ringingly neo-nazi endorsements. I've heard that in Louisiana, David Duke occasionally lurches up out of his slumber and endorses somebody -- who invariably falls over himself denying any association! It's wonderful. Poor Duke. (By the way, Duke is well thought of in the well-dressed middle class western suburbs of Philadelphia -- they think he got a raw deal. So much for facile assumptions (mine, for example
The right wing has gotten tremendous mileage out of painting moderate centrists as "extremist left-wing radicals". Okay, fair enough. Let's play.
Oh shut up. (Score:2)
Re:Register, Read, Vote. (Score:2)
I dont like how we arm militias of 3rd world countrys so we can help take over their gov
I dont like how we police the world.
I dont like how the politicians arent in it to better the country, but to better there own careers.
I dont like our over-agressive capitolism-But capitolism is a great thing, if done correctly and fairly.
They say if you dont like it, you can leave
Well, I don't like it-I can't change it, so im moving to canada.
Just my $0.02
PS: If you are going to whine and cry about spelling/grammar errors, save the bandwidth and forget reminding me how terrible I am.
Re:Oh that makes more sense now... (Score:2)
Settle down, no need to get frustrated.
It's a free market economy. If Bush is smart enough to buy up those names before some anti-bush person does, then more power to him.
Smart? For doing what, letting the bushsucks websites find another name, that is smart? That is a lame attempt.
Yeah, free market, I buy out your company have them fire you, buy out the every company you could work for and have them deny you a job even as janator, and then when you're wife has to leave you because you can't afford to be with her, then I will take her, or give her to a friend.
Hey!!!! Its a free market. I can buy anything with enough money, even if it is not for sale. If your wife is beautiful enough I can imagine many other rich men trying to do the same thing, we may even poll our money together just to get our turn with her.
Let someone use their geocities account to post bad things against Bush, it just won't be as easy for people to find it.
Exactly, its not how bush did it (buying up a lot of obvious bushsucks site names), its what it says in his actions.... "You can dislike me, but you wont be able to scream loud enough about it".
Sure money is power, but it isn't ethics, morals, or responsibility. Sure guns give you sense of power, but they also don't give you those things, and Colorado is a good example of abuse of that kind of power. Abuse of money is another thing, personly I think it was a dumb thing he did, not only a waste of money, but also a bad message to send out to everyone.
Either you don't live in the US (and thus don't really understand our country), or you do but really have no clue of how "free speech" and "market economy" go together.
All right lets not be lame, I'm not saying he is not free to buy them, just like I am free to shoot you there is nothing "real" holding me back, but there are and should be moral and ethical problems with this. You should know the diffrence.
If I was a Democrat, I wouldn't list that as a reference to some negative thing used against Bush.
Of course not, but there are people who would be interested, just like their are people who are interested in clintonsucks sites, and the rest of the anti sites, its just human nature to look at the bad side of something, as well as the good sides. And GB obviously know this, but he his solution is not to discuss anything its to buy everything out.
Actually your comments leave me speachless. I've never heard such a warped point of view.
OK, then try to explain why he bought them with out getting close to my "warped point of view".
Re:boycottbush.com (Score:3)
brand name" by buying up the
Register, Read, Vote. (Score:5)
Re: Who should be able to own a domain (Score:1)
I also thing companies should be able to buy as many domains as they wish - tho I'm waiting for IPv6/IPng to grow - wonder if we'll have this domain buying spree all over again...
Re:It's not over yet... (Score:1)
Oh well. Please don't encourage cracking, by the way. Cracking is bad. And it's not constructive, either. And anyone who cracks for political reasons can get in really deep doo-doo. So don't do it.
Re:quick society question... (Score:1)
I think this is the real issue anyhow, not whether he dropped 14 grand with NSI just for publicity.
boycottbush.com (Score:2)
Re:I don't get it (Score:1)
Apparently this time it was more interesting what he said than who he was.
Baahhh (Score:4)
1. You must be some kind of an official organization
2. There should be a certain number of individual computers uniquely connected to it (no virtual hosting crap)
3. ONLY ONE domain per organization
4. That name must say who you are
Domain names were never intended to be used by everly little clown that wants a web site. They were intended to identify networks and to give organizations their own namespace.
I like Bush, but this is kinda stupid. Maybe I'll vote for Alan Keyes like I did last time.
(www.)bush1999.com is not taken... (Score:1)
ttyl
Farrell
Re:quick society question... (Score:1)
Re:boycottbush.com (Score:1)
Re:Um, banner ads? (Score:1)
Re:boycottbush.com (Score:2)
Umm, no it's not. Slashdot is run by BSI, a company, not a non-profit organization. Rob has said himself that he makes money from Slashdot's banner ads. In fact, since Rob has no other job, Slashdot is his sole source of income.
dumbass.
You remind me of a middle school student. Are you 12 or 13?
Re:boycottbush.com (Score:1)
i was thinking bushbites.com
pennacook
There outta be a law... (Score:2)
If Bush buys bushsucks.com, he should be required to actually use it.
[veering OT] Stay in Sweden (Score:2)
It doesn't matter. A president's job has little to do with technical matters. If you think Gore hasn't a clue (he actually has the ability to borrow a clue; one wishes he would remind himself of that sometimes), then Bush would be an even bigger joke. Like his father (a man I really like, BTW -- except as a politician), George W just wants to be president; the only relevant details he has worked on so far is fund-raising and focus groups. Policies are not so worked-out at this time, i.e., they're for sale to the highest bidder, be it a special interest group or a corporation. He's ahead in the polls right now, but if the press scrutinizes his past business deals (e.g. Harken Energy, and the Texas Rangers baseball team), the voters will see that he made a lot of money from his surname and the fact that his dad was (at various times) the DCI (head of the CIA), vice president, and president. Of course, the voters may ignore all that and vote for the guy anyway; I'm sure he and his handlers will have worked out explanations and alibis for everything, or Double U wouldn't have run for prez. Are top politicians in Sweden this bad? Many top American politicians are; Bush is in the 90th percentile, with plenty of company.
Oh. Did I forget my RANT tags again? Moderators: I have no problem with this being reduced to a -1 score
:)
--
Re:Scientologists own the Cult Awareness Network (Score:1)
You know what the funniest thing is? Go to dict.org and lookup the word "cult". "Religion" is listed as a synonym. Yes, that includes, but is not limited to: Christianity, Islam, Buddism, Rastafarianism, among many others.
Any religiously-educated human being would know this. IIRC, the original (archaic) definition of cult was "a religion that's teaching revolves around one being" (or something close).
I'm sure it goes without saying that the original group was religious as well, I'm not going to say what religion, but it should be obvious to most. The large cult gets trounced by a smaller cult that got slammed by the large cult. Serves the large cult right.
I'm no scientologist either, but it disgusts me to find groups out there devotes their time to promoting their ideals through their own hypocracy and bashing others.
-Erik-
Re:Only an idiot believes in preaching to the choi (Score:1)
How about giving each 16,66667 % of the vote. Better than apathy and it sends a message to them.
Vote NONE OF THE ABOVE.
Law requires that if a candidate is not within a majority of 1/ of the vote, that all candidates will not be allowed to participate in a new election.
So, hence, vote NONE OF THE ABOVE if you do not like exactly what you are getting now. Keep doing it until you get someone you like... More people should do this, it's not throwing your vote away if you can get the majority to understand what it means.
And this goes for representatives and senators also. Remember that the electoral college is a good portion of the vote as well, so don't bother voting for a democrat president and a republican representative/senator, as half (i think half, someone correct me here if not) of your vote contradicts the other.
Personally I won't vote for any political seats until I move of of this shit-for-nothing country as no matter how I vote I get screwed in the ass by someone who sees their back pocket as a more important issue than the people. Even nowadays when you vote on laws the govt doesn't agree with they try to repeal them. (See oregon and medicinal marijuana, the state legislature is still trying to repeal it, even though it passed with overwhelming majority)
I'm ranting - so what.
-Erik-
domain name != URL (Score:1)
Perhaps someone is using their domain name for workstation hostnames, email, a gopher server...
Is that so bad?
--
Get your fresh, hot kernels right here [kernel.org]!
Re:just a couple things... (Score:1)
How could this possibly be a restriction of free speech? The domain names were open for anybody to take, the Bush guys just got to them first. You are still free to put up a site that makes fun of Bush, details why he's a bad choice, or even documents why you think he's the leader of a vampire cult. You just have to think of a name that hasn't been registered yet.
Re:Domain name registration. (Score:1)
just joking . .
.
Beer recipe: free! #Source
Cold pints: $2 #Product
Re:Baahhh (Score:1)
So what if you can't register the domain name you want because someone's holding it? They're not limiting you, they're just limiting your execution. If what you say is really important, people will find your information.
Does it hurt him at all? (Score:1)
This is not an attack on free speech in any way. People can still say whatever they want about him.
You're blowing this out of proportion... (Score:1)
When someone compares the buying of domain names to various illegal and/or reprehensible acts, are they being brilliant?
Its just like saying "you can say anything you want, but you can't say it out loud".
Oh, please. You make it sound like he's banned anti-Bush Websites. He hasn't. Yeah, now the sites are going to be something like bushsucks.somewhere.com, or maybe something a bit more obscure like. Big deal.
By the way, I suggest you read the Gnome vs. KDE flamewars sometime. Why? Take a look at all the posts. Every time the word "sucks" or "blows" or anything is used in a post, you'll notice that the person doesn't have anything worthwhile or serious to say. Those who are really trying to make a point never use language like that (I dare you to find me a serious post on the issue that has the word "sucks" anywhere in it except to quote someone else). My point: yeah, the little oh-boy-lets-badmouth-a-candidate kiddies are going to be deterred by this. But not the professionals, and not the people who actually have something to say. Bush hasn't stopped the pros. He didn't mean to do that either.
Re:You're blowing this out of proportion... (Score:1)
You honestly think that's his message? Look, here's the thing:
The written word is a remarkable thing. It can convey messages, calm the hysterical, heal the depressed, and so forth. It can also be a terrible weapon. Look back over the history of presidential races: especially in recent years, every candidate who runs is dragged through the dirt. Every little aspect of their lives, sometimes going as far back as childhood mistakes, is dredged up in ways which would land the dredger in jail in any other circumstance.
No you think Bush wants that? No; he'd have to be out of his mind to want that. I doubt you'd want it either; no one does.
Also, note the names he eliminated. "bushsucks.org" or "bushblows.org," but not things like "boycottbush.net." My point: he took the names which were explicitly defamatory, as opposed to ones which suggested actions or at least sounded professional (honestly, do you think his opponents' campaigns will use "bushsucks.com"? No; it'll be the upstarts, the people with little vendettas and axes to grind). He's trying to save some shred of his dignity; he'll lose the rest during the race, as will all the other candidates. Can you blame him for that?
That important? (Score:1)
It won't accomplish anything (Score:1)
He can't have tagged all of them... (Score:1)
Re:Baahhh (Score:1)
Wow, did I read that right? I hope you don't take too much offense, but I must strongly disagree with your implied point. Of all the rights in the Bill of Rights, free speech is, IMO, by far the most important (especially for those of us who spend a lot of time communicating over the internet). It certainly isn't 'mere rhetoric'.
Read through some of the other posts on this topic and notice how some other democratic countries (Canada and Sweden are mentioned) limit the way you can register domains. Not only does this serve to limit one's speech, in some cases, someone comes up with a workaround of some sort (the Polynesian
I'm no big, flag-waving, patriot-zealot, but I'm glad I'm in the US where I can register as many domains as I want for any reason (or no reason!). Do you really want the government or a corporation deciding how you can express yourself on the internet?
Cheers,
Matthew
Re:quick society question... (Score:1)
Dibs on networksolutions.sucks
Re:Here are 3 they missed... (Score:3)
His brother Jeb, OTOH, kept trying to jam the ethernet cable into the phone jack.... Don't ask Jeb Bush to help with anything technical.
just a couple things... (Score:1)
First, I doubt that I will vote for someone who is squatting on over 200 domain names.
Second, Isnt this in some way a restriction of free speech?
Re:boycottbush.com (Score:1)
Re:boycottbush.com (Score:1)
at the time of this writing I'm 14(I was 13 like 2 months ago), I'll be a highschool junior for 99-00...
Though I don't see how age comes into the matter, age really is so fickle...
I've been using linux since I was 12, and it was NOT redhat, I did my time reading HOWTOs and man pages, I got X working my first time from a CONF file I wrote completely from scratch, which is alot more then I can say about some "adults" that I know.
There's been kids much younger then I that have gotten doctorates, and written books. Hell, wasn't Alexander the Great like 9 when he started?
Re:How about... (Score:1)
Cheers,
Perrin.
Re:I don't get it (Score:1)
Cheers,
Perrin.
Re:He didn't get the cannibals choice... (Score:1)
Cheers,
Perrin.
Re:How about... (Score:1)
Cheers,
Perrin.
Re:quick society question... (Score:1)
Cheers,
Perrin.
Re:Oh that makes more sense now... (Score:1)
Cheers,
Perrin.
Re:quick society question... (Score:2)
Cheers,
Perrin.
Re:Well... (Score:3)
Cheers,
Perrin.
Re:Baahhh (Score:3)
Cheers,
Perrin.
Re:Um, banner ads? (Score:1)
-mike kania
Exactly: Utterly pointless (Score:1)
As for wanting the publicity, boff... I'm not sure I agree that "any press is good press". Are people really going to be more likely to vote for him, having read this?
Incidentally, I have nothing against the man myself. I don't live in the US and have no idea of his policies, anyways. Just pointing out that this was a dumb idea.
Steve 'Nephtes' Freeland | Okay, so maybe I'm a tiny itty
I don't get it (Score:4)
I Think This is Cool (Score:2)
Re:just a couple things... (Score:1)
Second, no.
Hmm.,. dunno what that would do.. (Score:1)
Given that I usually get my url's from references from people I know, from a search engine, or from postings on newsgroups/slashdot, I don't see how this would stop any anti-Bush sentiment from showing up on the Internet.
Looks like it's time to start looking for an original domain name that attacks Bush.
Ben
Re:boycottbush.com (Score:1)
200*70 = 14000
when i grow up i want to own a monopoly
Re:Here are 3 they missed... (Score:2)
If your state doesn't have a motor voter law, look up your town's electorial commission in the phone book, phone them for instructions on registering and just do it.
I live in Cambridge, MA, and there are voter registration tables at street fairs and a lot of other public events. It's not exactly a normal town, since there's more registered Libertarians than Republicans in it, but even less activist towns have to let you register if you can prove:
1. citizenship
2. residence in the town
3. that you have no felony convictions
Re:quick society question... (Score:1)
Re:Baahhh (Score:1)
off-topic: is keyes running again? i didn't get to vote in the last election, but he would definately be my choice for president. he's a good, honest man with whom i tend to agree on almost every issue.
Re: (Score:1)
whois microsfot.com
[rs.internic.net]
Registrant:
JS technologies SA (MICROSFOT2-DOM)
Rue du Centre 72
St-Sulpice, 1025
CH
Domain Name: MICROSFOT.COM
hrm (Score:1)
I am sure the 200 names Bush registered only represent a very small fraction of the possibilities.
Forcing your opponents to be more creative is not always the best way to go.
Re:HeilBuchanan.com! Yes! Yes! Oh, yes. (Score:1)
Did any of you ever hear of irony? (Score:1)
Re:I don't get it (Score:1)
And as for good publicity vs. bad publicity, there's not much difference. Publicity is the point. Forget who said it, but "say whatever you like about me, just so long as you spell my name right."
Re:HeilBuchanan.com! Yes! Yes! Oh, yes. (Score:1)
And wasn't what's his name, "This space for Rent" Byrd in the Clan back when?
Re:.sucks.com and .rules.com domains (Score:1)
--
.sucks.com and .rules.com domains (Score:3)
The domains sucks.com [sucks.com] and rules.com [rules.com] are not being used for this sort of purpose. sucks.com exhibits a "coming soon" sign, and rules.com seems to have been snaffled by a speculator/hosting company.
If I owned these domains I would be selling subdomains, and making lotsa dosh! I shudder to think of the money geeks would pay to get domains like microsoft.sucks.com, or linux.rules.com. People would probably play ~internic rates for subdomains there, IMHO....
Besides, it be much more fun to tease those who only sorta get the tech, but exploiting holes in their knowledge....
Re:boycottbush.com (Score:1)
Lay off.
:) It's not like it really affects anyone.
Scientologists own the Cult Awareness Network (Score:3)
That was about three years ago.
Poor flame artists (Score:2)
Erm, my heart bleeds for all the poor flame artists who will find it marginally harder to throw personal insults at someone because they disagree with his politics. Um, not.
I'd have to say that buying domains instead of sending threatening letters is a definite improvement.
Project Vote Smart! (Score:3)
This non-partisan site has lots of detailed info on all the candidates and so forth, including issues responses and recent voting history. That is, if they've been a Congressman, it lists how they voted on various bills.. very good solid data. (Could use more info on those bills, though.)
Anyway, this is the quickest way to check out tons of solid facts about various candidates. (Score:4)
Apple owns 100's of domain names to point to thier website, Nike owns around 500 I belive, and I'm sure there are alot of others who own that amount of domain names.
And I'll be damned, look where takes me too.....
suckclinton.org fund? (Score:1)
:-)
He didn't get the cannibals choice... (Score:1)
little companies become big companies (Score:1)
Re:Is it _really_ clever... (Score:1)
Re:Is it _really_ clever... (Score:1)
First of all, the main reason for buying the domain name is to keep it out of the hands of the opposition.
But second, it's fairly clever to have someone looking for one thing find exactly the opposite message -- like sometimes happens with various brand names, as we've seen on
To be really fiendishly clever, they could direct people coming to those negative URLs to specific targeted pitches designed for people who already dislike the candidate (or other product). Focus groups could tell them what stuff works best for these people, and it's probably not the same rah-rah stuff that would be at the main home page.
Re: (Score:1)
way to go!
*ROTFL*
Is it _really_ clever... (Score:2)
Bush just demonstrated his low ethical standards (Score:1)
Not that I'm defending Gore-the-Internet-Inventor, but...
I think it's revealing that Bush was willing to do something so petty just to attempt to keep people from speaking against him. It's analogous to a rogue moderator marking down messages that disagree with his opinion. Regardless of Bush's stand on "important" issues, there's no way I could vote for him after reading this, simply because it shows that he's basically a dishonorable person. He just proved himself to be just another Clinton.
no one missed anything... (Score:1)
And he can't get bush.com, some other guy named Bush registered it in 1995 (smart guy, that one. Got his own name first!)
Apache/Php (Score:1)
Here are 3 they missed... (Score:1)
blowmegeorge.net
blowmegeorge.org
Of course, I'm stuck in Sweden at the moment, so I don't have a clue about the potential candidates. I know that Gore doesn't have a clue, but what about George, how does he stand up when it comes to technical matters?
---
Re: (Score:2)
Nowhere...
whois microsfot.org
[rs.internic.net]
No match for "MICROSFOT.ORG".
You agree that you will not reproduce, sell, transfer, or
modify any of the data presented in response to your search request, or
use of any such data for commercial purpose, without the prior
express written permission of Network Solutions.
Now microsfot.com on the other hand points to linux.org...
--- is free, go buy it (Score:2)
-----BEGIN ANNOYING SIG BLOCK-----
Evan
Re:Hmm.,. dunno what that would do.. (Score:2)
Jaq
This is a problem with name registration, not Bush (Score:2)
I would suggest a good rule for domain name registration authorities is that a company can have its domain name renewal denied if it hasn't made use of the name. If all a name does is point to a "Coming soon" or "Buy this domain" page for a year, then we should return it to the pile and let someone else have a go at it. Ditto when someone has a bunch of domain names point to the same page.
Bush isn't doing anything wrong, but he's still being a jerk by buying something just to keep someone else from having it. We should work for rules that stop this sort of land-grab behavior.
If he can't put up content on every domain name, and not just link them all to one page, then let him, but if he's just pissing all over stuff to keep other people away... Well, we don't need that bullshit on the net as well as in the physical world.
It's a brave new world (Score:2)
I can imagine George and his advisors sitting around some large expensive table discussing if they want to buy. I'll bet they were laughing as hard as I was.
It says something about the power; or maybe the perceived power of the internet. It's really amazing how far it has come in the span of a few years. I was thinking back to 94 when I got my first account on Prodigy. You had to pay extra to go on the "Web" at that time and the speed coming through prodigy was horrible, but I'll bet I didn't sleep for a week.
Now the internet seems so commonplace, having an email adr. is the norm not the execption, and major political powers are giving some serious thought on how to harness the power.
This should be interesting.
Re:Baahhh (Score:2)
So, I should have to agree to someone else's definition of organized?
2. There should be a certain number of individual computers uniquely connected to it (no virtual hosting crap)
Hmm, how many addresses can you map to ONE name? And wouldn't that be fun if you had to have NSI manage your subdomains.
3. ONLY ONE domain per organization
Lessee, there's my right foot, my left one... Is my head the same organization as my book collection? How many names do you go by personally? There's usually your first name, your last name, a nick name, insults, email aliases, handles...
4. That name must say who you are
And who you are must say what you do, what you sell, your interests, your history, your address, your income, your SSN, your license plate.
Domain names were never intended to be used by everly little clown that wants a web site.
They were meant to be used by suits to communicate to other suits, or by scientists to communicate with their peers. Clowns need web sites to look at, too.
They were intended to identify networks and to give organizations their own namespace.
I believe they were intended to identify addresses belonging to interfaces belonging to computers belonging to networks belonging to organizations. Well then, there are mail handlers too.
I like bush
hee hee
I like Bush more and more (Score:2)
While Gore claims to be the high-tech candidate, I think Bush is the man for the geek community. Why? His actions show that instead of jumping on buzzwords and trying to jump in front of the crowd so that he can call himself a leader, Bush is actually willing to do his homework and study the nature of our world before he opens his mouth.
Note please do not construe this post as flaim bait. This forum isn't about who supports welfare, abortion, bombing soveriegn countries, etc. It's about technology and which candidate can best drive it forward. Please, please, please, limit responses to this. exists (Score:2)
quick society question... (Score:3)
Why do people in general have to create sucks.com sites? Yeah, you may not like the person, but you can still let the person campaign/sell/express their opinion. Going out and just saying they suck is just childish. If you want to vent your frustrations with someone, you can find a far more adult way to do it somewhere else.
(And I'm not associated with *any* political party...I don't agree with any of them)
Anyone capable of getting themselves made presiden (Score:2)
Douglas Adams, The Hitchikers Guide To The Galaxy
read some history dorkwad and go back to coding (Score:2)
capitalism is still a theory
Feudalism never ended. People just feel rich because of suits.
communism is extreme socialism for control of power. Some cultures' medium of value(currency) is power.
protectionism is extreme capitalism for control of
money. Some cultures' medium of value is money.
so far no culture has held value as a medium of value.
stop trying to legislate or institutionalize good will. nothing lasts past a few generations after its inception. every generation is as far from the last generation as the next will be from it because nothing changes just the percentage of different qualities of character. stop being so ridiculously enthusiastic, it's sickening.
Read Forever Flowing, A Captive Mind, watch "Brazil" a few times.
"but we can still do much better..." go back to coding.
Re:Register, Read, Vote. (Score:2)
Re:Baahhh (Score:2)
And all those old programs were never intended to be used after 2000, or they would have been Y2K compliant.
So what?
We need more Slashdot categories (Score:5)
These stories weren't very interesting to begin with and now they're just plain annoying. I don't care.
I care about Linux news, but not what people have to say about piddly bi-weekly kernel improvements.
Thank you, and good night.
Re:Baahhh (Score:4)
Worst part is that it's some American lawyer who manages it, not the polynesians, who gets all the money...
Re:Hmm.,. dunno what that would do.. (Score:2)
anyhow, if your refering to the guy who the story says wants 300,000 (?? didn't go back and reread figure could be wrong..) then I appologize and ignore me..
Domain name registration. (Score:2)
rules on who gets what type of domain name,
and how many you can have. An organization
can only have ONE domain name, and it either
has to relate to their company name, or
a registered trademark. So now, for example,
you can have either coke.ca or coca-cola.ca,
but not both. You wouldn't believe the hoops
I had to jump through to get pollock.ca!
Jason | https://beta.slashdot.org/story/99/05/16/0726220/george-w-bush-buys-anti-bush-names?sdsrc=prev | CC-MAIN-2016-44 | refinedweb | 5,429 | 73.88 |
// this is a template for making NUnit tests. Text enclosed // in square brackets (and the brackets themselves) should be // replaced by appropiate code. // // [File Name].cs - NUnit Test Cases for [explain here] // // [Author Name] ([Author email Address]) // // (C) [Copyright holder] // // these are the standard namespaces you will need. You may // need to add more depending on your tests. using NUnit.Framework; using System; // all test namespaces start with "MonoTests." Append the // Namespace that contains the class you are testing, e.g. // MonoTests.System.Collections namespace MonoTests.[Namespace] { // the class name should end with "Test" and start with the name // of the class you are testing, e.g. CollectionBaseTest public class [Class to be tested]Test : TestCase { // there should be two constructors for your class. The first // one (without parameters) should set the name to something // unique. // Of course the name of the method is the same as the name of // the class public [Constructor]() : base ("[Namespace.Class]") {} public [Constructor](string name) : base(name) {} // this method is run before each Test* method is called. You // can put variable initialization, etc. here that is common to // each test. // Just leave the method empty if you don't need to use it. protected override void SetUp() {} // this method is run after each Test* method is called. You // can put clean-up code, etc. here. Whatever needs to be done // after each test. Just leave the method empty if you don't need // to use it. protected override void TearDown() {} // this property is required. You need change the parameter for // typeof() below to be your class. public static ITest Suite { get { return new TestSuite(typeof([Classname here])); } } // this is just one of probably many test methods in your test // class. each test method must start with "Test". All methods // in your class which start with "Test" will be automagically // called by the NUnit framework. public void Test[Something] { // inside here you will exercise your class and then // call Assert() } } | http://www.mono-project.com/TemplateTest.cs | CC-MAIN-2013-20 | refinedweb | 325 | 75.91 |
ADO.NET & Foreign Text
I'm a bit of a newbie to internationalization of apps, so bear with me. An Sql Server 2000 table for our website has a "text" field (not "ntext"), where our users insert content in various languages (Korean and Chinese are popular). In regular old ASP/ADO, I'd select and write the data, and it would render just fine in a web browser.
Now as I convert our website to ASP.NET/ADO.NET, selecting the same field returns garbage to the web browser. I'd like to know a way around this; a way to exhibit the same behavior as in regular ASP.
I imagine this is due to the fact that .NET is in Unicode, and the "text" field is not. Changing the field to "ntext" might help, but unfortunately, this is currently not an option. Any suggestions?
Monsur
Wednesday, December 11, 2002
How are you rendering it?... Databinding? Response.Write()?
Duncan Smart
Wednesday, December 11, 2002
rendering using Response.Write
Monsur
Thursday, December 12, 2002
Actually, thinking about it that shouldn't make a difference.
Maybe the browser is mangling it becasue of incorrect codepage recognition...
Look into the CodePage attribute of the <%@ Page %> directive:
There's a table of code pages here:
You can also set it programmatically with Response.CodePage.
Duncan Smart
Thursday, December 12, 2002
Thanks Duncan for the CodePage tip. Unfortunately, that didn't work.
It seems like the data is becoming "mangled" by ToString. I actually did get an example to work, but I had to use an SqlDataReader, use GetBytes to read in all the bytes, and then write them out to a BinaryWriter. This is way too tedious to do in production. Plus although this works great with an SqlDataReader, what would be the analogous method for a DataSet? This is sounding like an ADO.NET issue; any ideas would be appreciated.
Thanks!
Monsur
Sunday, December 15, 2002
Other things I would try:
<%@ Page ResponseEncoding="..." %>
which could be: "utf-8" (the default I think... but not sure), "unicode", various others. (Weird thing is I would have expected "utf-8" to cope with it.)
It can also be cone at a web.config level:
<system.web>
<globalization
fileEncoding="utf-8" />
...
As to the ToString() method messing it up... try writing a simple Windows app and seeing if it has the same problem. If not then it's down to ASP.NET or the browser...
Duncan Smart
Monday, December 16, 2002
Actually, that was my next step. I used two methods of writing to a file:
1) BinaryWriter in conjunction with SqlDataReader's GetBytes
2) StreamWriter in conjunction with SqlDataReader's GetString
Sure enough, case 1 writes the correct output, while case 2 does not.
I also tried using the OleDb classes instead of SqlClient, with the same results.
I'm suspecting ADO.NET is trying to read the UTF-8 encoded field as Unicode, which causes the mangling. GetBytes accesses the bytes before they get mangled. But GetBytes really isn't the ideal solution to roll into production. I haven't found any documentation covering ADO.NET and encodings.
Monsur
Tuesday, December 17, 2002
With GetBytes() all you need to do is something like:
using System.Text;
...
x = Encoding.Unicode.GetString( reader.GetBytes() );
(OK, not ideal when the DataReader *should* be interpreting the string correctly)
Does DataBinding give you the same problem? i.e.
<p>... <%# reader["blah"] %> ...</p>
...
Page.DataBind();
How about SqlDataReader.GetSqlString()?
Have you tried installing .NET Framewrk SP2?
This might will be worth posting to: as there you're likely to get an MS insider chasing it up.
Duncan Smart
Wednesday, December 18, 2002
First off, I must really thank you. It's been very kind of you to stick with me on this issue. You really live up to your name, Duncan Smart :)
Service Pack 2 is installed on our system. Databinding as well as GetSqlString() gives the same results.
However, the GetString() method DOES work. But it runs into the same issues I had above when using a BinaryWriter above. The SqlDataReader's GetBytes signature is
public long GetBytes(
int i,
long dataIndex,
byte[] buffer,
int bufferIndex,
int length
);
So in order to grab the proper string, I need to iterate over GetBytes, using GetString at each iteration to generate the output string. It is a solution, but a very unwieldy one for production.
And I have no guarantee that all the data access in my system will use SqlDataReaders. Some areas use DataSets, for which I don't see an analogous GetBytes method.
So as you can see, I'm at an impasse. I saw this question posted to a group a few months back, but it didn't have any responses. I have tried a few other groups (including MS' Newsgroup), with the same results. But now that I have a better understanding of the issue, I will try develop.com. Thanks!
Monsur
Wednesday, December 18, 2002
Recent Topics
Fog Creek Home | https://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=898&ixReplies=8 | CC-MAIN-2018-26 | refinedweb | 833 | 67.25 |
11.01.2012 20:23, Trond Myklebust пишет:> On Tue, 2012-01-10 at 16:58 +0400, Stanislav Kinsbursky wrote:>> 06.01.2012 00:58, Trond Myklebust пишет:>>> The second problem that was highlighted was the fact that as they stand>>> today, these patchsets do not allow for bisection. When we hit the Oops,>>> I had Bryan try to bisect where the problem arose. He ended up pointing>>> at the patch "SUNRPC: handle RPC client pipefs dentries by network>>> namespace aware routine", which is indeed the cause, but which is one of>>> the _dependencies_ for all the PipeFS notifier patches that fix the>>> problem.>>>>>>> I'm confused here. Does this means, that I have to fix patch "SUNRPC: handle RPC>> client pipefs dentries by network namespace aware routine" to make it able to>> bisect?>> What I mean is that currently, I have various ways to Oops the kernel> when I apply "SUNRPC: handle RPC client pipefs dentries by network> namespace aware routine" before all these other followup patches are> applied.>> One way to could fix this, might be to add dummy versions of> rpc_pipefs_notifier_register()/unregister() so that "NFS: idmap PipeFS> notifier introduced" and the other such patches can be applied without> compilation errors or Oopses before the "handle RPC client pipefs> dentries..." patch is applied. The latter could then enable the real> rpc_pipefs_notifier_register()/....>> The point is to not have these patches add _known_ bugs to the kernel at> any point, so that someone who is trying to track down an unknown bug> via "git bisect" doesn't have to also cope with these avoidable> issues...>Ok, thanks for explanation.BTW, it looks like that in last 2 days I've sent all updates to the issues you pointed out. If not, please, ping me once more.-- Best regards,Stanislav Kinsbursky--To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2012/1/11/251 | CC-MAIN-2015-27 | refinedweb | 328 | 68.91 |
US4558413A - Software version management system - Google PatentsSoftware version management system Download PDF
Info
- Publication number
- US4558413AUS4558413A US06553724 US55372483A US4558413A US 4558413 A US4558413 A US 4558413A US 06553724 US06553724 US 06553724 US 55372483 A US55372483 A US 55372483A US 4558413 A US4558413 A US 4558413A
- Authority
- US
- Grant status
- Grant
- Patent type
-
- Prior art keywords
- file
- object
- system
- version
- to software version management system and method for handling and maintaining software, e.g. software updating uniformily across the system, particularly in a large software development environment having a group of users or programmers. The system is also referred to as the "System Modeller".
Programs consisting of a large number of modules need to be managed. When the number of modules making up a software environment and system exceeds some small, manageable set, a programmer cannot be sure that every new version of each module in his program will be handled correctly. After each version is created, it must be compiled and loaded. In a distributed computing environment, files containing the source text of a module can be stored in many places in a distributed system. The programmer may have to save it somewhere so others may use it. Without some automatic tool to help, the programmer cannot be sure that versions of software being transferred to another user or programmer are the versions intended to be used.
A programmer unfamiliar with the composition of the program is more likely to make mistakes when a simple change is made. Giving this new programmer a list of the files involved is not sufficient, since he needs to know where they are stored and which versions are needed. A tool to verify a list of files, locations and correct versions would help to allow the program to be built correctly and accurately. A program can be so large that simply verifying a description is not sufficient, since the description of the program is so large that it is impractical to maintain it by hand.
The confusion of a single programmer becomes much worse, and the cost of mistakes much higher, when many programmers collaborate on a software project. In multi-person projects, changes to one part of a software system can have far-reaching effects. There is often confusion about the number of modules affected and how to rebuild affected pieces. For example, user-visible changes to heavily-used parts of an operating system are made very seldom and only at great cost, since other programs that depend on the old version of the operating system have to be changed to use the newer version. To change these programs, the "correct" versions of each have to be found, each has to be modified, tested, and the new versions installed with the new operating system. Changes of this type often have to be made quickly because the new system may be useless until all components have been converted. Members or users of large software projects are unlikely to make such changes without some automatic support.
The software management problems faced by a programmer when he is developing software are made worse by the size of the software, the number of references to modules that must agree in version, and the need for explicit file movement between computers. For example, a programming environment and system used at the Palo Alto Research Center of Xerox Corporation at Palo Alto, Calif., called "Cedar" now has approximately 447,000 lines of Cedar code, and approximately 2000 source and 2000 object files. Almost all binary or object files refer to other binary or object files by explicit version stamp. A program will not run until all references to an binary or object file refer to the same version of that file. Cedar is too large to store all Cedar software on the file system of each programmer's machine, so each Cedar programmer has to explicitly retrieve the versions he needs to run his system from remote storage facilities or file servers.
Thus, the problem falls in the realm of "Programming-the-Large" wherein the unit of discourses the software module, instead of "Programming-in-the-Small", where units include scalor variables, statements, expressions and the like. See the Article of Frank DeRemer and H. Kron, "Programming-in-the-Large versus Programming in the small", IEEE Transactions on Software Engineering, Vol. 2(2), pp. 80-86, June 1976.
To provide solutions solving these problems overviewed above, consider the following:
1. Languages are provided in which the user can describe his system.
2. Tools are provided for the individual programmer that automate management of versions of his programs. These tools are used to acquire the desired versions of files, automatically recompile and load aprogram, save new versions of software for others to use, and provide useful information for other program analysis tools such as cross-reference programs.
3. In a large programming project, software is grouped together as a release when the versions are all compatible and the programs in the release run correctly. The languages and tools for the individual programmer are extended to include information about cross-package dependencies. The release process is designed so production of release does not lower the productivity of programmers while the release is occurring.
To accomplish the foregoing, one must identify the kinds of information that must be maintained to describe the software systems being developed. The information needed can be broken down into three categories:
1. File Information: For each version of a system, the versions of each file in the system must be specified. There must be a way of locating a copy of each version in a distributed environment. Because the software is always changing, the file information must be changeable to reflect new versions as they are created.
2. Compilation Information: All files needed to compile the system must be identified. It must be possible to compute which files need to be translated or compiled or loaded and which are already in machine runnable format. This is called "Dependency Analysis." The compilation information must also include other parameters of compilation such as compiler switches or flags that affect the operation of the compiler when it is run.
3. Interface Information: In languages that require explicit delineation of interconnections between modules (e.g. Mesa, Ada), there must be means to express these interconnections.
There has been little research in version control and automatic software management. Of that, almost none has built on other research in the field. Despite good reasons for it, e.g. the many differences between program environments, and the fact that programming environments ususally emphasize one or two programming languages, so the management systems available are often closely related to those programming languages, this fact reinforces the singularity of this research. The following is brief review of previous work in this area.
(1) Make Program
The Make program, discussed in the Article of Stuart J. Feldman, "Make-A Program for Maintaining Computer Programs", Software Practice & Experience, Vol. 9 (4), April, 1979, uses a system description called the Makefile, which lists an acyclic dependency graph explicitly given by the programmer. For each node in the dependency graph, the Makefile contains a Make Rule, which is to be executed to produce a new version of the parent node if any of the son nodes change.
For example the dependency graph illustrated in FIG. 1 shows that x1.o depends on x1.c, and the file a.out depends on x1.o and x2.o. The Makefile that represents this graph is shown in Table I below.
TABLE I______________________________________a.out: x1.o x1.o x2.o______________________________________ cc x1.o x2.ox1.0: x1.c cc -c x1.cx2.o: x2.c cc -c x2.c______________________________________
In Table I, the expression, "cc-c x1.c" is the command to execute and produce a new version of x1.o when x1.c is changed. Make decides to execute the make rule i.e., compile x1.c, if the file modification time of x1.c is newer than that of x1.o.
The description mechanism shown in Table I is intuitively easy to use and explain. The simple notion of dependency, e.g., a file x1.o, that depends on x1.c must be recompiled if x1.c is newer, works correctly vitually all the time. The Makefile can also be used as a place to keep useful commands the programmer might want to execute, e.g.,
print:
pr x1.c x2.c
defines a name "print" that depends on no other files (names). The command "make print" will print the source files x1.c and x2.c. There is usually only one Makefile per directory, and, by convention, the software in that directory is described by the Makefile. This makes it easy to examine unfamiliar directories simply by reading the Makefile.
Make is an extremely fast and versatile tool that has become very popular among UNIX users. Unfortunately, Make uses modification times from the file system to tell which files need to be re-made. These times are easily changed by accident and are a very crude way of establishing consistency. Often the programmer omits some of the dependencies in the dependency graph, sometimes by choice. Thus, even if Make employed a better algorithm to determine the consistency of a system, the Makefile could still omit many important files of a system.
(2) Source Code Control System (SCCS)
The Source Code Control System (SCCS) manages versions of C source programs enforcing a check-in and check-out regimen, controlling access to versions of programs being changed. For a description of such systems, see the Articles of Alan L. Glasser, "The Evolution of a Source Code Control System", Proc. Software Quality & Assurance Workshop, Software Engineering Notes, Vol. 3(5), pp. 122-125, November 1978; Evan L. Ivie, "The Programmer's Workbench-A Machine for Software Development", Communications of the ACM, Vol. 20(10) pp. 746-753, October, 1977; and Marc J. Rochkind "The Source Code Control System", IEEE Transactions on Software Engineering, Vol. 1(4), pp. 25-34, April 1981.
A programmer who wants to change a file under SCCS control does so by (1) gaining exclusive access to the file by issuing a "get" command, (2) making his changes, and (3) saving his changed version as part of the SCCS-controlled file by issuing a "delta" command. His changes are called a "delta" and are identified by a release and level number, e.g., "2.3". Subsequent users of this file can obtain a version with or without the changes made as part of "delta 2.3". While the programmer has "checked-out" the file, no other programmers may store new deltas. Other programmers may obtain copies of the file for reading, however. SCCS requires that there be only one modification of a file at a time. There is much evidence this is a useful restriction in multi-person projects. See Glasser, Supra. SCCS stores all versions of a file in a special file that has a name prefixed by "s.". This "s." file represents these deltas as insertions, modifications, and deletions of lines in the file. Their representation allows the "get" command to be very fast.
(3) Software Manufacturing Facility (SMF)
Make and SCCS were unified in special tools for a development project at Bell Labs called the Software Manufacturing Facility (SMF) and discussed in the Article of Eugene Cristofer, F. A. Wendt and B. C. Wonsiewicz, "Source Control & Tools=Stable Systems", Proceedings of the Fourth Computer Software & Applications Conference, pp. 527-532, Oct. 29-31, 1980. The SMF uses Make and SCCS augmented by special files called slists, which list desired versions of files by their SCCS version number.
A slist may refer to other slists as well as files. In the SMF, a system consists of a master slist and references to a set of slists that describe subsystems. Each subsystem may in turn describe other subsystems or files that are part of the system. The SMF introduces the notion of a consistent software system: only one version of a file can be present in all slists that are part of the system. Part of the process of building a system is checking the consistency.
SMF also requires that each slist refer to at least one Makefile. Building a system involves (1) obtaining the SCCS versions of each file, as described in each slists, (2) performing the consistency check, (3) running the Make program on the version of the Makefile listed in the slist, and (4) moving files from this slist to an appropriate directory. FIG. 2 shows an example of a hierarchy of slists, where ab.sl is the master slist.
SMF includes a database of standard versions for common files such as the system library. Use of SMF solves the problem created when more than one programmer is making changes to the software of a system and no one knows exactly which files are included in the currently executing systems.
(4) PIE Project
The PIE project is an extension to Smalltalk developed at the Palo Alto Research Center of Xerox Corporation and set forth in the Articles of Ira P. Goldstein and Daniel G. Bobrow, "A Layered Approach to Software Design", Xerox PARC Technical Report CSL-80-5, December 1980; Ira P. Goldstein and Daniel G. Bobrow, "Descriptions for a Programming Environment", Proceedings of the First Annual Conference of the National Association of Artificial Intelligence, Stanford, Calif., August 1980; Ira P. Goldstein and Daniel G. Bobrow, "Representing Design Alternatives", Proceedings of the Artificial Intelligence and Simulation of Behavior Conference, Amsterdam, July 1980; and the book "Smalltalk-80, The Language and It Implemention" by Adele Goldberg and David Robson and published by Addison-Wesley, 1983. PIE implements a network database of Smalltalk objects, i.e., data and procedures and more powerful display and usage primitives. PIE allows users to categorize different versions of a Smalltalk object into layers, which are typically numbered starting at zero. A list of these layers, most-preferred layer first, is called a context. A context is a search path of layers, applied dynamically whenever an object in the network database is referenced. Among objects of the same name, the one with the layer number that occurs first in the context is picked for execution. Whenever the user wants to switch versions, he or she arranges his context so the desired layer occurs before any other layers that might apply to his object. The user's context is used whenever any object is referenced.
The distinction of PIE's solution to the version control problem is the ease with which it handles the display of and control over versions. PIE inserts objects or procedures into a network that corresponds to a traditional hierarchy plus the threads of layers through the network. The links of the network can be traversed in any order. As a result, sophisticated analysis tools can examine the logically-related procedures that are grouped together in what is called a Smalltalk "class". More often, a PIE browser is used to move through the network. The browser displays the "categories", comprising a grouping of classes, in one corner of a display window. Selection of a category displays a list of classes associated with that category, and so on until a list of procedures is displayed. By changing the value of a field labeled "Contexts:" the user can see a complete picture of the system as viewed from each context. This interactive browsing features makes comparison of different versions of software very convenient.
(5) Gandalf Project
A project, termed the Gandalf project at Carnegie Mellon University, and discussed in the Article of A. Nico Habermann et al., "The Second Compendium of Gandalf Documention", CMU Department of Computer Science, May 1980, is implementing parts of an integrated software development environment for the GC language, an extension of the C language. Included are a syntax-directed editor, a configuration database, and a language for describing what is called system compositions. See the Articles of A. Nico Haberman and Dewayne E. Perry "System Compositions and Version Control for Ada", CMU Computer Science Department, May 1980 and A. Nico Haberman "Tools for Software System Construction", Proceedings of the Software Tools Workshop, Boulder, Colo., May 1979. Various Ph.D these have explored this language for system composition. See the Ph.D Thesis of Lee W. Cooprider "The Representation of Families of Software Systems", CMU Computer Science Department, CMU-CS-79-116, Apr. 14, 1979 and Walter F. Tichy, "Software Development Control Based on System Structure Description", CMU Computer Science Department, CMU-CS-80-120, January 1980.
Recent work on a System Version Control Environment (SVCE) combines Gandalf's system composition language with version control over multiple versions of the same component, as explained in the Article of Gail E. kaiser and A. Nico Habermann, "An Environment for System Version Control", in "The Second Compendium of Gandalf Documentation", CMU Department of Computer Science, Feb. 4, 1982. Parallel versions, which are different implementations of the same specification, can be specified using the name of the specific version. There may be serial versions of each component which are organized in a time-dependent manner. One of the serial versions, called a revision, may be referenced using an explicit time stamp. One of these revisions is designated as the "standard" version that is used when no version is specified.
Descriptions in the System Version Control Language (SVCL) specify which module versions and revisions to use and is illustrated, in part, in FIG. 3. A collection of logically-related software modules is described by a box that names the versions and revisions of modules available. Boxes can include other boxes or modules. A module lists each parallel version and revision available. Other boxes or modules may refer to each version using postfix qualifiers on module names. For example, "M" denotes the standard version of the module whose name is "M," and "M.V1" denote parallel version V1. Each serial revision can be specified with an "@," e.g., "M.V1@2" for revision 2.
Each of these expressions, called pathnames, identifies a specific parallel version and revision. Pathnames behave like those in the UNIX system: a path name that begins, for example, /A/B/C refers to box C contained in box B contained in A. Pathnames without a leading "/" are relative to the current module. Implementations can be used to specify the modules of a system, and compositions can be used to group implementations together and to specify which module to use when several modules provide the same facilities. These ways of specifying and grouping versions and revisions alloy virtually any level of binding: the user may choose standard versions or, if it is important, the user can be very specific about versions desired. The resulting system can be modified by use of components that specialize versions for any particular application as illustrated in FIG. 3.
SVCE also contains facilities for "System Generation". The Gandalf environment provides a command to make a new instantiation, or executable system, for an implementation or composition. This command compiles, links, and loads the constituent modules. The Gandalf editor is used to edit modules and edit SVCL implementations directly, and the command to build a new instantiation is given while using the Gandalf editor. Since the editor has built-in templates for valid SVCL constructs, entering new implementations and compositions is very easy.
SVCE combines system descriptions with version control, coordinated with a database of programs. Of the existing systems, this system comes closest to fulfillng the three previously mentioned requirements: Their file information is in the database, their recompilation information is represented as lines in the database between programs and their interface information is represented by system compositions.
(6) Intermetrics Approach
A system used to maintain a program of over one million lines of Pascal code is described in an Article of Arra Avakian et al, "The Design of an Integrated Support Software System", Proceedings of the SIGPLAN '82 Syposium on Compiler Construction, pp. 308-317, June 23-25, 1982. The program is composed of 1500 separately-compiled components developed by over 200 technical people on an IBM 370 system. Separately-compiled Pascal modules communicate through a database, called a compool, of common symbols and their absolute addresses. Because of its large size (90 megabytes, 42,000 names), a compool is stored as a base tree of objects plus some incremental revisions. A simple consistency check can be applied by a link editor to determine that two modules were compiled with mutually-inconsistent compools, since references to code are stamped with the time after which the object file had to be recompiled.
Management of a project this size poses huge problems. Many of their problems were caused by the lack of facilities for separate compilation in standard Pascal, such as interface-implementation distinctions. The compool includes all symbols or procedures and variables that are referenced by modules other than the module in which they are declared. This giant interface between modules severely restricts changes that affect more than one separately-compiled module. Such a solution is only suitable in projects that are tightly managed. Their use of differential-updates to the compool and creation times to check consistency makes independent changes by programmers on different machines possible, since conflicts will ultimately be discovered by the link editor.
(7) Mesa, C/Mesa and Cedar
Reference is now made to the Cedar/Mesa Environment developed at Palo Alto Research Center of Xerox Corporation. The software version management system or system modeller of the instant invention is implemented on this enviroment. However, it should be clear to those skilled in the art of organizing software in a distributed environment that the system modeller may be implemented in other programming systems involving a distributed environment and is not dependent in principle on the Cedar/Mesa environment. In other words, the system modeller may handle descriptions of software systems written in other programming languages. However, since the system modeller has been implemented in the Cedar/Mesa environment, sufficient description of this environment is necessary to be familiar with its characteristics and thus better understand the implementation of the instant invention. This description appears briefly here and more specifcally later on.
The Mesa Language is a derivative of Pascal and the Mesa language and programming is generally disclosed and discussed in the published report of James G. Mitchell et al, "Mesa Language Manual, Version 5.0", Xerox PARC Technical Report CSL-79-3, April 1979. Mesa programs can be one of two kinds: interfaces or definitions and implementations. The code of a program is in the implementation, and the interface describes the procedures and types, as in Pascal, that are available to client programs. These clients reference the procedures in the implementation file by naming the interface and the procedure name, exactly like record or structure qualification, e.g., RunTime.GetMemory[] refers to the procedure GetMemory in the interface RunTime. The Mesa compiler checks the types of both the parameters and results of procedure calls so that the procedures in the interfaces are as strongly type-checked as local, private procedures appearing in a single module.
The interconnections are implemented using records of pointers to procedure bodies, called interface records. Each client is passed a pointer to an interface record and accesses the procedures in it by dereferencing once to get the procedure descriptors, which are an encoded representation sufficient to call the procedure bodies.
A connection must be made between implementations (or exporters) and clients (or importers) of interfaces. In Mesa this is done by writing programs in C/Mesa, a configuration language that was designed to allow users to express the interconnection between modules, specifying which interfaces are exported to which importers. With sufficient analysis, C/Mesa can provide much of the information needed to recompile the system. However, C/Mesa gives no help with version control since no version information can appear in C/Mesa configurations.
Using this configuration language, users may express complex interconnections, which may possibly involve interfaces that have been renamed to achieve information hiding and flexibility of implementation. In practice, very few configuration descriptions are anything more than a list of implementation and client modules, whose interconnections are resolved using defaulting rules.
A program called the Mesa Binder takes object files and configuration descriptions and produces a single object file suitable for execution. See the Article of Hugh C. Lauer and Edwin H. Satterthwaite, "The Impact of Mesa on System Design", Proceedings of the 4th International Conference on Software Engineering, pp. 174-182, 1979. Since specific versions of files cannot be listed in C/Mesa descriptions, the Binder tries to match the implementations listed in the description with flies of similar names on the invoker's disk. Each object file is given a 48-bit unique version stamp, and the imported interfaces of each module must agree in version stamp. If there is a version conflict, e.g., different versions of an interface, the Binder gives an error message and stops binding. Most users have elaborate command files to retrieve what they believe are suitable versions of files to their local disk.
A Librarian, discussed in the Article of Thomas R. Horsley and William C. Lynch, "Pilot: A Software Engineering Case Study", Proceedings of the 4th International Conference on Software Engineering, pp. 94-99, 1979, is available to help control changes to software in multi-person projects. Files in a system under its control can be checked out by a programmer. While a file is checked out by one programmer, no one else is allowed to check it out until it has been checked in. While it is checked out, others may read it, but no one else may change it.
In one very large Mesa-language project, which is exemplified in the Article of Eric Harslem and Leroy E. Nelson, "A Retrospective on the Development of Star" Proceedings of the 6th International Conference on Software Engineering, September 1982, programmers submit modules to an integration service that recompiles all modules in a system quite frequently. A newly-compiled system is stored on a file system and testing begins. A team of programmers, whose only duty is to perform integrations of other programmer's software, fix incompatibilities between modules when possible. The major disadvantage of this approach is the amount of time between a change made by the programmer and when the change is tested.
The central concern with this environment is that even experienced programmers have a problem managing versions of Mesa or Cedar modules. The lack of a uniform file system, lack of tools to move version-consistent sets of modules between machines, and lack of complete descriptions of their systems contribute to the problem.
The first solution developed for version mangement of files is based on description files, also designated as DF files. The DF system automates version control for the user or programmer. This version management is described in more detail later on because experience with it is what led to the creation of the version management system of the instant invention. Also, the version management of the instant invention includes some functionality of the DF system integrated into an automatic program development system. DF files have information about software versions of files and their locations. DF files that describe packages of software are input to a release process. The release process checks the submitted DF files to see if the programs they describe are made from compatible versions of software, and, if so, copies the files to a safe location. A Release Tool performs these checks and copies the files. If errors in DF files are found and fixed employing an interactive algorithm. Use of the Release Tool allows one making a release, called a Release Master, to release software with which he may in part or even to a large extent, not be familiar with.
According to this invention, the system modeller provides for automatically collecting and recompiling updated versions of component software objects comprising a software program for operation on a plurality of personal computers coupled together in a distributed software environment via a local area network. As used herein, the term "objects" generally has reference to source modules or files, object modules or files and system models. The component software objects are stored in various different local and remote storage means throught the environment. The component software objects are periodically updated, via a system editor, by various users at their personal computers and then stored in designated storage means.
The system modeller employes system modeller when any one of the objects is being edited by a user and the system modeller is responsive to such notification to track the edited objects and alter their respective models to the current version thereof. The system modeller upon command is adapted to retieve and recompile source files corresponding to altered models and load the binary files of the altered component software objects and their dependent objects into the user's computer.
The system modeller also includes accelerator means to cache the object pointers in the object models that never change to thereby avoid further retrieving of the objects to parse and to discern the object pointers. The accelerator means for the models includes (1) an object type table for caching the unique name of the object and its object type to enhance the analysis of a model by the modeller, (2) a projection table for caching the unique name of the source object, names of object parameters, compiler switches and compiler version to enhance the translation of objects into derived objects, and (3) a version map for caching the object pathname.
The system modeller is an ideal support system in a distributed software environment for noting and monitoring new and edited versions of objects or modules, i.e., source or binary or model files, and automatically managing the compilation, loading saving of such modules as they are produced. Further, the system modeller provides a means for organizing and controlling software and its revision to provide automatic support for several different kinds of program development cycles in a programming system. The modeller handles the daily evolution of a single module or a small group of modules modified by a single person, the assembly of numerous modules into a large system with complex interconnections, and the formal release of a programming system. The modeller can also efficiently locate a large number of modules in a big distributed file system, and move them from one machine to another to meet operational requirements or improve performance.
More particularly, the system modeller automatically manages the compilation, loading and saving of new modules as they are produced. The system modeller is connected to the system editor and is notified of new and edited versions of files as they are created by the system editor, and automatically recompiles and loads new versions of software. The system user decribes his software in a system model that list the versions of files used, the information needed to compile the system, and the interconnections between the various modules. The modeller allows the user or programmer to maintain three kinds of information stored in system models. The models, which are similar to a blueprint or schematic, describe particular versions of a system. A model combines in one place (1) information about the versions of files needed and hints about their locations, (2) additional information needed to compile the system, and (3) information about interconnections between modules, such as which procedures are used and where they are defined. To provide fast response, the modeller behaves like an incremental compiler so that only those software modules that have experienced a change are analyzed and recompiled.
System models are written in a SML language, which allows complete descriptions of all interconnections between software modules in the environment. Since these interconnections can be very complicated, the language includes defaulting rules that simplify system models in common situations.
The programmer uses the system modeller to manipulate systems described by the system models. The system modeller (1) manipulates the versions of files listed in models (2) tracks changes made by the programmer to files listed in the models, (3) automatically recompiles and loads the system, and (4) provides complete support for the release process. The modeller recompiles new versions of modules and any modules that depend on them.
The advantages of the system modeller is (1) the use of a powerful module interconnection language that expresses interconnections, (2) the provision of a user interface that allows interactive use of the modeller while maintaining an accurate description of the system, and (3) the data structures and algorithms developed to maintain caches that enable fast analysis of modules by the modeller. These advantages are further expandable as follows.
First, the system modeller is easy to use, perform functions quickly and is to run while the programmer is developing his software and automatically update system descriptions whenever possible. It is important that a software version management system be used while the programmer is developing software so he can get the most benefit from them. When components are changed, the descriptions are adjusted to refer to the changed components. Manual updates of descriptions by the programmer would slow his software development and proper voluntary use of the system seems unlikely. The system modeller functioning as an incremental compiler, i.e. only those pieces of the system that are actually change are recompiled, loaded and saved.
Second, the exemplified computing environment upon which the described system modeller is utilized is a distributed personal computer environment with the computers connected over an Ethernet local area network (LAN). This environment introduces two types of delays in access to versions of software stored in files: (1) if the file is on a remote machine, it has to be found, and (2) once found, it has to be retrieved. Since retrieval time is determined by the speed of file transfer across the network, the task of retrieving files is circumvented when the information desired about a file can be computed once and stored in a database. For example, the size of data needed to compute recompilation information about a module is small compared to the size of the module's object file. Recompilation information can be saved in a database stored in a file on the local disk for fast access. In cases where the file must be retrieved determining which machine and directory has a copy of the version desired can be very time consuming. The file servers can deliver information about versions of files in a remote file server directory at a rate of up to six versions per second. Since directories can have many hundreds of versions of files, it is not practical to enumerate the contents of a file server while looking for a particular version of a file. The solution presented here depends on the construction of databases for each software package or system that contains information about file locations.
Third, since many software modules, e.g., Cedar software modules, have a complicated interconnection structure, the system modeller includes a description language that can express the interconnection structure between the modules. These interconnection structures are maintained automatically for the programmer. When new interconnections between modules are added by the programmer, the modeller updates the model to add the interconnection when possible. This means the user has to maintain these interconnections very seldom. The modeller checks interconnections listed in models for accuracy by checking the parameterization of modules.
Further advantages, objects and attainments together with a fuller understanding of the invention will become apparent and appreciated by referring to the following description and claims taken in conjunction with the accompanying drawings.
FIG. 1 is an illustration of a dependency graph for a prior art software management system.
FIG. 2 is an illustration for a hierarchy of another prior art software management system.
FIG. 3 is an illustration of the description specifiers of a still another prior art software management system.
FIG. 4 is an illustration of a Cedar system client and implementor module dependency.
FIG. 5 is an illustration of a Cedar system source and object file dependency.
FIG. 6 is an illustration of a dependency graph for a Cedar System.
FIG. 7 is an example of a typical distributed computer evironment.
FIG. 8 is a flow diagram of the steps for making a release in a distributed computer environment.
FIG. 9 is a dependency graph for DF files in the boot file.
FIG. 10 is a dependency graph illustrative of a detail in the boot file.
FIG. 11 is a dependency graph for interfaces.
FIG. 12 is a dependency graph for files outside the boot file.
FIGS. 13a and 13b illustrate interconnections between implementation and interface modules.
FIG. 14 illustrates two different versions of a client module.
FIGS. 15a and 15b illustrate a client module to IMPORT different versions of the module that EXPORTs.
FIG. 16 illustrates a client module with different types of objects.
FIG. 17 is an example of a model.
FIG. 18 are examples of object type and projection tables.
FIG. 19 is an example of a version map.
FIG. 20 is an illustration the user's screen for system modeller in the Cedar system.
FIG. 21 is a flow diagram illustrating the steps the user takes in employing the system modeller.
FIG. 22 is a modeller implementation flow diagram illustrating "StartModel" analysis.
FIG. 23 is a modeller implementation flow diagram illustrating computation analysis.
FIG. 24 is a modeller implementation flow diagram illustrating loader analysis.
FIG. 25 illustrates the Move Phase two of the release utilitity.
FIG. 26 illustrates the Build Phase three of the release utility.
FIG. 27 is an example of a version map after release.
One kind of management system of versions of software for a programmer in a distribution environment is a version control system of modest goals utilizing DF files. Each programmer lists files that are part of his system in a description file which is called a DF file.
Each entry in a DF file consists of a file name, its location, and the version desired. The programmer can use tools to retrieve files listed in a DF file and to save new versions of files in the location specified in the DF file. Because recompiling the files in his system can involve use of other systems, DF files can refer also to other DF files. The programmer can verify that, for each file in the DF file, the files it depends on are also listed in the DF file.
DF files are input to a release process that verifies that the cross-package references in DF files are valid. The dependencies of each file on other files are checked to make sure all files needed are also part of the release. The release process copies all files to a place where they cannot be erroneously destroyed or modified.
The information about file location and file versions in DF files is used by programs running in the distributed programming environment. Each programmer has a personal computer on which he develops software. Each personal computer has its own disk and file system. Machines are connected to other machines using an Ethernet local area network. Files can be transferred by explicit request from the file system on one machine or computer to another machine or computer. Often transfers occur between a personal machine and a file storage means, e.g., a file server, which is a machine dedicated to servicing file requests, i.e., storing and permitting the retrieval of stored files.
The major research contributions of the DF system are (1) a language that, for each package or system described, differentiates between (a) files that are part of the package or system and (b) files needed from other packages or systems, and (2) a release process that does not place too high a burden on programmers and can bring together packages being released. A release is complete if and only if every object file needed to compile every source file is among the files being released. A release is consistent if, and only if, only one version of each package is being released and every other package depends on the version being released. The release process is controlled by a person acting as a Release Master, who spends a few days per monthly release running programs that verify that the release is consistent and complete. Errors in DF files, such as references to non-existent files or references to the wrong versions of files, are detected by a program called the Release Tool. After errors are detected, the Release Master contacts the implementor and has him fix the appropriate DF file.
Releases can be frequent since performing each release imposes a low cost on the Release Master and on the programmers. The Release Master does not need to know details about the packages being released, which is important when the software of the system becomes too large to be understood by any one programmer. The implementor of each package can continue to make changes to his package until the release occurs, secure in the knowledge that his package will be verified before the release completes. Many programmers make such changes at the last minute before the release. The release process supports a high degree of parallel activity by programmers engaged in software development of a large dsitributed programing environment.
The DF system does not offer all that is needed to automate software development. DF files have only that information needed to control versions of files. No support for automatic recompilation of changed software modules is provided in the DF system. The only tool provided is a consistency checker that verifies that an existing system does not need to be recompiled.
In order to better understand the software version control system of the instant invention, a general understanding of the programming environment in which it is implemented is desirable. The programming environment is called Cedar. First, some general characteristics of Cedar.
The Cedar system changes frequently, both to introduce new function and also to fix bugs. Radical changes are possible and may involve recompilation of the entire system. System requirements are:
1. The system must manage these frequent changes and must give guarantees about the location and consistency of each set of files.
2. Each consistent set of Cedar software is called a "Cedar Release", which is a set of software modules carefully packaged into a system that can be loaded and run on the programmer's personal machine. These releases must be carefully stored in one place, documented and easily accessible.
3. Cedar releases should be accomplished, e.g., as often as once a week, since frequent releases make available in a systematic way new features and bug fixes. The number of users or programmers is small enough that releases do not need to be bug-free since users are generally tolerant of bugs in new components or packages in the system. When bugs do occur, it must be clear who is responsible for the software in which the bug occurs.
4. The system must minimize inconvenience to implementors and cannot require much effort from the person in charge of constructing the release. The scheme must not require a separate person whose sole job is control and maintenance of the system.
5. The system must be added on top of existing program development facilities, since it is not possible to change key properties of such a large distributed programing environment.
A limited understanding of the dependency relationships in the Cedar software systems is necessary, i.e., an overview of Cedar modules and dependencies.
The view taken in the Cedar system is that the software of a system is completely described by a single unit of text. An appropriate analogy is the sort of card deck that was used in the 1950s to boot, load and run a bare computer. Note that everything is said explicitly in such a system description. There is no operator intervention, such as to supply compiler switches or loader options, after the "go" button is initiated. In such a description there is no issue of "compilation order", and "version control" is handled by distributing copies of the deck with a version number written on the top of each copy.
The text of such a system naturally will have integral structure appropriate to the machine on which it runs as well as to the software system itelf. The present system is composed of modules that are stored as text in files termed modules or objects. This representation provides modularity in a physical representation, i.e., a file can name other files instead of literally including their text. In Cedar, these objects are Cedar modules or system models. This representation is convenient for users to manipulate, it allows sharing of identical objects or modules, and facilitates the separate compilation of objects or modules. But it is important to appreciate that there is nothing essential in such a representation. In principle, a system can always be expressed as a single text unit.
Unless care is taken, however, the integrity of the system will be lost, since the contents of the named files may change. To prevent this, files are abstracted into named objects, which are simply pieces of text. The file names must be unique and objects must be immutable. By this it is meant that each object has a unique name, never used for any other object. The name is stored as part of the object, so there is no doubt about whether a particular collection of bits is the object with a given name. A name is made unique by appending a unique identifier to a human-sensible string.
The contents of an object or module never change once the object is created. The object may be erased, in which case the contents are no longer accessible. If the file system does not guarantee immutability, it can be ensured by using a suitable checksum as the unique identifier of the object.
These rules ensure that a name can be used instead of the text of a module without any loss of integrity, in the sense that either the entire text of a system will be correctly assembled, or the lack of some module will be detected.
In Cedar, a Cedar module A depends on another Cedar module B when a change to B may require a change to A. If module A depends on module B, and B changes, then a system that contains the changed version of B and an unchanged version of A could be inconsistent. Depending on the severity of the change to B, the resulting system may not work at all, or may work while being tested but fail after being distributed to users. Cedar requires inter-module version checking between A and B that is very similar to Pascal type-checking for variables and procedures. As in Pascal, Cedar's module version checking is designed to detect inconsistency as soon as possible at compile time so that the resulting system is more likely to run successfully after development is completed.
Each Cedar module is represented as a source file whose names, for example, ends in "Mesa". The Cedar compiler produces an object file whose name, for example, ends in "Bcd". Each object file can be uniquely-identified by a 48-bit version stamp so no two object files have the same version stamp. Cedar modules depend on other modules by listing in each object file the names and 48-bit version stamps of object files they depend on. A collection of modules that depend on each other are required to agree exactly in 48-bit version stamps. For example, module A depends on version 35268AADB3E4 (hexadecimal) of module B, but B has been changed and is now version 31258FAFBFE4, then the system is inconsistent.
The version stamp of a compiled module is a function of the source file and the version stamps of the object files on which it depends on. If module A depends on module B which in turn depends on module C, and C is changed and compiled, then when B and A are compiled their version stamps will change because of the change to C.
There are three kinds of software modules in Cedar. They are called interface, implementation, and configuration. There are two programs that produce object files. They are the Cedar Complier and the Cedar Binder.
Executing code for a Cedar system is contained in an implementation module. Each implementation module can contain procedures, global variables, and local variables that are scoped using Pascal scoping rules. To call a procedure defined in another implementation module, the caller or client module must IMPORT a interface module that defines the procedure's type i.e. the type of the procedure's argument and result values. This interface module must be EXPORTED by the implementation module that defines it. This module is called the implementor.
Both the client and implementor modules depend on the interface module. This dependency is illustrated in FIG. 3. If the interface is recompiled, both client and implementor must be recompiled. The client and implementor modules do not depend on each other, so if either is compiled the other does not need to be. Thus, Cedar uses the interface-implementor module distinction to provide type safety with minimal recompilation cost.
A compiler-produced object file depends on (1) the source module that was compiled and (2) the object files of any interfaces that this module IMPORTs or EXPORTs. This dependency is illustrated in FIG. 5. These interface modules are compiled separately from the implementations they described, and interface object files contain explicit dependency information. In this respect, Cedar differs from most other languages with interface or header files.
Another level of dependency is introduced by configuration modules, which contain implementation modules or other configuration modules. The programmer describes a set of modules to be packaged together as a system by writing a description of those modules and the interconnections among them in a language called C/Mesa. A C/Mesa description is called a configuration module. The source file for a configuration is input to the Cedar Binder which then produces an object file that contains all the implementation module object files. The Binder ensures the object file is composed of a logically-related set of modules whose IMPORTs and EXPORTs all agree in version. Large system of modules are often made from a set of configurations called sub-configurations. A configuration object file depends on (1) its source file and (2) the sub-configurations and implementation object files that are used to bind the configuration. These object files can be run by loading them with the Cedar Loader which will resolve any IMPORTs not bound by the Binder.
In general, a Cedar system has a dependency graph like that illustrated in FIG. 6.
Each Cedar programmer has its own personal computer, which is connected to other computers by an Ethernet local area network (LAN). Most files comprising a system are stored on central file servers dedicated to serving file requests and are copied from the central file server(s) to the personal machine by an explicit command, which is similar to the Arpanet "ftp" command. FIG. 7 illustrates a typical environment. In such an environment, a plurality of workstations comprising a personal computer or machine 10 with keyboard, display and local memory are connected to an Ethernet LAN via cable 12. Also connected to cable 12 is file server 14 comprising a server computer 16 and storage disk units 18 capable of storing large amounts of files under designated path or directory names. Cable 12 is also connected to a gateway computer 20 which provides access and communication to other LANs.
The user of a machine 10 must first install a boot file that is given control after the machine is powered on. Cedar users install the Cedar boot file that contains the operating system and possibly pre-loaded programs.
Since the Binder and Loader ensure that the version stamps of Cedar modules all agree, all Cedar modules could be bound together and distributed to all users for use as the Cedar boot file. However, users who wanted to make changes would have to re-bind and load the system every time they changed a module to test their changes. The resulting boot file would be very large and difficult to transfer and store on the disks of the personal machines. To avoid these problems, Cedar users install this boot file on their machine, which contains a basic system to load and execute Cedar programs, a file system, and a pre-loaded editor and then retrieve copies of programs they want to run that are not already in the boot file. These programs are thus loaded as they are needed.
Changes to these programs are possible as long as the versions of interfaces pre-loaded in the Cedar boot file agree with the versions IMPORTed by the program being loaded. Since the boot file EXPORTs are more than 100 interfaces, the programmer can quickly become confused by version error messages for each of the interfaces he uses. This problem could be solved simply by disallowing changes to the Cedar interfaces except, say, once annually. However, it is desirable to be able to adjust interfaces frequently to reflect new features and refinements as they are understood.
Control of software in module interconnection languages is analogous to control over types in conventional programming languages, such as Pascal. Still opposed by some, strong type-checking in a language can be viewed as a conservative approach to programming, where extra rules, in the form of type equivalence, are imposed on the program. Proponents claim these rules lead to the discovery of many programming errors while the program is being compiled, rather than after it has started execution.
Like strong type-checking of variables, type-checking in a language like Cedar with the explicit notion of an interface module can be performed at the module level so that incompatibilities between modules can be resolved when they are being collected together rather than when they are executing. As in the strong type-checking case, proponents claim this promotes the discovery of errors sooner in the development of programs.
Incompatible versions of modules, like incompatible types in a programming languages, may be corrected by the programmers involved. Many times, complex and subtle interdependencies exist between modules, especially when more than a few programmers are involved and the lines of communication between them are frayed or partially broken. In the Cedar Xerox environment, where each module is a separate file and development occurs on different personal computers or machines, module-level type-checking is more important than type-checking of variables in conventional programming languages. This is because maintaining inter-module type consistency is by definition spread over different files, possibly on different computers by more than one programmer/user, while maintaining type-consistency of variables is usually localized in one file by one programmer/user on one computer.
Users in Cedar are required to group logically-related files, such as the source and object files for a program they are developing, into a package. Each software package is described by a DF file that is a simple text file with little inherent structure that is editable by the programmer/user. The DF file lists all the files grouped together by the implementor as a package. For each file, the DF file gives a pathname or location where the file can be found and information about which version is needed.
In Cedar, files are stored on remote file servers with names like "Ivy" or "Indigo" and have path or directory names, e.g., "Levin>BTrees>". A file like "BTreeDefs.Mesa" would be referenced as "[Ivy]<Levin>BTrees>BTreeDefs.Mesa". In addition, when created, each file is assigned a creation time. Therefore "BTreeDefs.Mesa Of May 13, 1982 2:30 PM" on "[Ivy]<Levin>BTrees>" defines a particular version.
A DF file is a list of such files. For syntactic grouping, we allow the user to list files grouped under common directories. The implementor of a B-tree package, for example, might write in his DF file, called BTrees.DF:
______________________________________Directory [Ivy]<Levin>BTrees>______________________________________BTreeDefs.Mesa 2-Oct-81 15:43:09______________________________________
to refer to the file [Ivy]<Levin>BTrees>BTreeDefs.Mesa created at 2-Oct-81 15:43:09.
If, for example, the BTree package included an object file for BTreeDefs.Mesa, and an implementation of a B-tree package, it could be described in BTrees.DF as:
______________________________________Directory ______________________________________
Two different DF files could refer to different versions of the same file by using references to files with different create dates.
There are cases where the programmer wants the newest version of a file. If the notation, ">", appears in place of a create time notation, the DF file refers to the newest version of a file on the directory listed in the DF file. For example,
______________________________________Directory [Ivy]<Pilot>Defs>______________________________________Space.Bed >______________________________________
refers to the newest version of Space.Bcd on the directory [Ivy]<Pilot>Defs>. This is used mostly when the file is maintained by someone other than the programmer and is content to accept the latest version of the file.
Users are encouraged to think of the local disk on their personal computer as a cache of files whose "true" locations are the remote servers. A program called BringOver assures the versions listed in a DF file are on the local computer disk.
Since DF files are editable, the programmer who edits, for example, BTreeDefs.Mesa could, when ready to place a new copy on the server,Ivy, store it manually and edite the DF file to insert the new create time for the new version.
For large numbers of files, this would always be error prone, so a StoreBack program provides automatic backup of changed versions (1) by storing files that are listed in the DF file but whose create date differs from the one listed in the DF on the assumption that the file has been edited, and (2) by updating the DF file to list the new create dates. The DF file is to be saved on the file server, so we allow for a DF self-reference that indicates where the DF file is stored. For example, in BTrees.DF:
______________________________________Directory [Ivy]<Levin>BTrees>______________________________________BTrees.DF 20-Oct-81 9:35:09BTreeDefs.Mesa 2-Oct-81 15:43:09BTreeDefs.Bed 2-Oct-81 16:00:28BTreeImpl.Mesa 2-Oct-81 15:28:54BTreeImpl.Bed 2-Oct-81 16:44:31______________________________________
the first file listed is a self-reference. The StoreBack program arranges that the new version of BTrees.DF will have the current time as its create date.
The Cedar system itself is a set of implementaton modules that export common system interfaces to the file system, memory allocator, and graphics packages. Assume the B-tree package uses an interface from the allocator. The user makes this dependency explicit in their DF file. The BTree package will then IMPORT the interface "Space", which is stored in object form in the file "Space.Bcd".
The BTree DF package will reflect this dependency by "importing" Space.Bcd from a DF file "PilotInterfaces.DF" that lists all such interfaces. BTrees.DF will have an entry:
______________________________________Imports [Indigo]<Cedar>Top> 2-Oct-81 15:43:09PilotInterfaces.DF OfUsing[Space.Bed]______________________________________
The "Imports" in a DF file is analogous to the IMPORTS in a Cedar program. As in Cedar modules, BTrees.DF depends on Pilot.DF. Should "Space.Bcd" and its containing DF file "Pilot.DF" change, then BTrees.DF may have to also change.
The programmer/user may want to list special programs, such as a compiler-compiler or other preprocessors, that are needed to make changes to his system. This is accomplished using the same technique of IMPORTing the program's DF file.
For the individual programmer, there are two direct benefits from making dependency information explicit in his DF file. First, the BringOver program will ensure that the correct version of any imported DF files are on the local disk, so programmers can move from one personal computer to another and guarantee they will have the correct version of any interfaces they reference. Second, listing dependency information in the DF file puts in one place information that is otherwise scattered across modules in the system.
How does the programmer/user know which files to list in his DF file? For large systems, under constant development, the list of files is long and changes frequently. The programmer can run a program VerifyDF that analyzes the files listed in the DF file and warns about files that are omitted. VerifyDF analyzes the dependency graph, an example of which is illustrated in FIG. 6, and analyzes the versions of (1) the source file that was compiled to produce the object file and (2) all object files that this object file depends on. VerifyDF analyzes the modules listed in the DF file and constructs a dependency graph. VerifyDF stops its analysis when it reaches a module defined in another package that is referenced by IMPORTs in the DF. Any modules defined in other packages are checked for versionstamp equality, but no modules that they depend upon are analyzed, and their sources do not need to be listed in the package's DF file.
VerifyDF understands the file format of object files and uses the format to discover the dependency graph, but otherwise it is quite general. For example, it does not differentiate between interface and implementation files. VerifyDF could be modified to understand object files produced by other language compilers as long as they record all dependencies in the object file with a unique version stamp. For each new such language, VerifyDF needs (1) a procedure that returns the object version stamp, source file name and source create time, and (2) a procedure that returns a list of object file names and object version stamps that a particular object file depends on.
If the programmer lists all such package and files he depends on, then some other programmer on another machine will be able to retrieve, using BringOver command, all the files he needs to make a change to the program and then run StoreBack to store new versions and produce a new DF file.
Using these tools, that is BringOver, StoreBack, VerifyDF, the programmer/user can be sure he has a DF file that lists all the files that are needed to compile the package (completeness) and that the object files were produced from the source files listed in the DF file, and there are no version stamp discrepancies (consistency). The programmer can be sure the files are stored on central file servers and can turn responsibility for a package over to another programmer by simply giving the name of the DF file.
DF files can be used to describe releases of software. Releases are made by following a set of Release Procedures, which are essentially managerial functions by a Release Master and requirements placed on implementors/users. A crucial element of these Release Procedures is a program called the Release Tool, which is used to verify that the release is consistent and complete, and is used to move the files being released to a common directory on a designated file server.
If the packages a programmer depends on change very seldom, then use of the tools outlined above is sufficient to manage versions of software. However, packages that almost everyone depends on may be changed. A release must consist of packages that, for example, all use the same versions of interfaces supplied by others. If version mismatches are present, modules that IMPORT and EXPORT different versions of the same interface will not be connected properly by the loader. In addition to the need for consistency and completeness across an entire release, the component files of a particular release must be carefully saved somewhere where they are readily available and will not be changed or deleted by mistake, until an entire release is no longer needed.
The administration of Cedar releases are organized around an implementor/user who is appointed Release Master. In addition to running the programs that produce a release, he is expected to have a general understanding of the system, to make decisions about when to try to make a release, and to compose a message describing the major changes to components of the release.
Once he decides to begin the release process after conferring with other implementors and users, the Release Master sends a "call for submissions" message through an electronic mail system of the distributed system to a distribution list of programmers/users who have been or are planning to contribute packages to the release. Over a period of a few days, implementors/users are expected to wait until new versions of any packages they depend on are announced, produce a new version on some file server and directory of their choosing, and then announce the availability of their own packages.
One message is sent per package, containing, for example, "New Version of Pkg can be found on [Ivy]<Schmidt>Pkg.DF, that fixes the bug . . . ". Programmers who depend on Pkg.DF are expected to edit their DF files by changing them to refer to the new version. Since often it is the newest version, clients of Pkg.DF usually replace an explicit date by the notation, ">". They might refer to Pkg.DF by inserting:
______________________________________Imports [Ivy]<Schmidt>Pkg.DF Of>Using[File1.Bed. File2.Bed]______________________________________
in their DF file.
If the package is not changed, a message to that effect will be sent. These submissions do not appear in lock step since changes by one implementor may affect packages that are "above" them in the dependency graph.
This pre-release integration period is a parallel exploration of the dependency graph of Cedar software by its implementor/users. If an implementor is unsure whether he will have to make changes as a result of lower level bug fixes, for instance, he is expected to contact the implementor of the lower package and coordinate with him. Circular DF-dependencies may occur, where two or more packages use interfaces exported by each other. In circular cases, the DF files in the cycle have to be announced at the same time or one of the DF files has to be split into two parts: a bottom half that the other DF file depends on and a top half that depends on the other DF file.
The Release Master simply monitors this integration process and when the final packages are ready, begins the release. FIG. 7 illustrates the steps being taken to accomplish a release.
Once all packages that will be submitted to the release are ready, the Release Master prepares a top-level DF file that lists all the DF files that are part of the release. Packages that are not changed relative to a previous release are also listed in this DF file. DF files are described using a construct similar to "Imports" discussed earlier. The contents of each DF file are referenced by an Include statement, e.g.,
Include [Ivy]<Levin>BTrees>BTrees.DF Of>
refers to the newest version of the BTree package stored on Levin's working directory <Levin>BTrees>. Include is treated as macro-substitution, where the entire contents of BTrees.DF are analyzed by the Release Tool as if they were listed directly in the top-level DF.
The Release Master uses the top-level DF as input to phase one of the Release Tool. Phase one reads all the included DF files of the release and performs a system-wide consistency check. A warning message is given if there are files that are part of the release with the same name and different creation times (e.g., BTreeDefs.Mesa of 20-May-82 15:58:23 and also another version of 17-Apr-82 12:68:33). Such conflicts may indicate that two programmers are using different versions of the same interface in a way that would not otherwise be detected until both programs were loaded on the same computer. These warnings may be ignored in cases where the Release Master is convinced that no harm will come from the mismatch. For example, there may be more than one version of "Queue.Mesa" in a release since more than one package has a queue implementation, but each version is carefully separated and the versions do not conflict.
Phase one also checks for common blunders, such as a DF file that does not refer to newest versions of DF files it depends on, or a DF file that refers to system or program files that do not exist where the DF file indicates they can be found. The Release Master makes a list, package by package, of such blunders and calls each user and notifies them they must fix their DF files.
Phase one is usually repeated once or twice until all such problems are fixed and any other warnings are judged benign. Phase two guarantees system wide completeness of a release by running VerifyDF will warn of files that should have been listed in the DF file but were omitted. Implementor/users are expected to run VerifyDF themselves, but during every release, ot is easy for at least one to forget. Any omissions must be fixed by the implementor/user.
Once phases one and two are completed successfully, the Release Master is fairly certain there are no outstanding version of system composition problems, and he can proceed to phase three.
To have control over the deletion of old releases, phase three moves all files that are part of a release to a directory that is mutable only by the Release Master. Moving files that are part of the release also helps users by centralizing the files in one phase. The DF files produced by users, however, refer to the files on their working directories. We therefore require that every file mentioned in the DF files that are being released have an additional phrase "ReleaseAsreleasePlace". The BTrees.DF example would look like:
______________________________________Directory [Ivy]<Levin>BTrees>______________________________________Release As [Indigo]<Cedar>Top>BTrees.DF 20-Oct-81 9:35:09ReleaseAs [Indigo]<Cedar>BTrees>BTreeDefs.Mesa 2-Oct-81 15:43:09BTreeDefs.Bed 2-Oct-81 16:00:28BTreeImpl.Mesa 2-Oct-81 15:28:54BTreeImpl.Bed 2-Oct-81 16:44:31______________________________________
which indicates a working directory as before and a place to put the stable, released versions. By convention, all such files must be released onto subdirectories of [Indigo]<Cedar>. To make searching for released DF files on the <Cedar> directory easier, each DF file's self-reference must release the DF file to the special subdirectory <Cedar>Top>. When the third phase is run, each file is copied to the release directory, e.g., B-tree files are copied to <Cedar>BTrees> and new DF files are written that describe these files in their release positions, e.g.,
______________________________________Directory [Indigo]<Cedar>Top>Came From [Ivy]<Levin>BTrees>BTrees.DF 9-Nov-81 10:32:45Directory [Indigo]<Cedar>BTrees>Came From ______________________________________
The additional phrase "CameFrom" is inserted as a comment saying where the file(s) were copied from.
The other major function of phase three is to convert references using the "newest version" notation, ">", to be explicit dates, since "newest version" will change for every release. Phase three arranges that a reference like:
______________________________________Imports[Ivy]<Levin>BTrees>BTrees.DF Of>Using[BtreeDefs.Bed]______________________________________
becomes
______________________________________Imports [Indigo]<Cedar>BTrees>Btrees.DF Of dateCame from [Ivy]<Levin>BTrees>Using [BTreeDefs.Bed]______________________________________
where date is approximately the time that phase three is run.
The notion of a "Cedar Release" has many advantages. In addition to a strong guarantee that the software will work as documented, it has an important psychological benefit to users as a firewall against disasters, since programmers are free to make major changes that may not work at all, and are secure in the knowledge that last release is still available to fall back upon. Since users can convert back and forth between releases, users have more control over which versions they use. There is nothing wrong with more than one such release being in use at one time by different programmer/users, since each programmer has his own personal computer. Users are also allowed to convert to new releases at their own pace.
This approach to performing releases fulfills initial requirements:
(1). All files in the release have been moved to the release directory. These files are mutually consistent versions of software. All DF files refer to files known to be on the release directory.
(2). As described earlier, we cannot make a configuration module that contains all the modules in a release. Cedar releases are composed of (a) a boot file and (b) programs that are mutually consistent and can be run on a personal machine with the boot file being released. Phase two runs VerifyDF on all the components to guarantee that the versions of source and object files listed in the DF file are the ones actually used to build the component and guarantees that all files needed to build the component are listed in the DF file, so no files that conflict in version can be omitted.
(3). The release process is automatic enough that frequent releases are possible. Bugs in frequent releases are easily reported since the concept of ownership is very strongly enforced by our approach. The programmer who provides new versions of software is the recipient of bug reports of his software.
(4). The Release Master is required to (a) decide when to make a release, (b) send a call-for-submissions message, (c) make a to-level DF file and run the Release Tool, and (d) send a message announcing the release's completion. Because releases are expected, over time, to include more and more system programs, it is important that the Release Master not need to compile packages other than any packages he may be contributing to the release. Indeed, no single person has ever known how to compile the entire system by himself.
Since the implementors use DF files for maintaining their own software as well as for submitting components to the release, there is little additional burden on the implementors when doing a release. If the burden were too high, the implementors would delay releases and overall progress would be slowed as the feedback from users to implementors suffered.
(5). A general database system to describe the dependency hierarchy of packages when we are producing systems is not needed. A message system is used, rather than a database of information that the programmers can query, to notify implementors that packages they may depend on are ready.
Many aspects of bootstrapping Cedar are simplified when interfaces to the lowest and most heavily used parts of the boot file are not changed. Some major releases use the same versions of interfaces to the system object allocator and fundamental string manipulation primitives. Most major releases use the same versions of interfaces to the underlying Pilot system such as the file system and process machinery. The implementations of these stable parts of the system may be changed in ways that do not require interface changes.
In the Cedar environment, two previous releases have included changes to the interfaces of the operating system, called Pilot and discussed in the Article of Redell et al. "Pilot: An Operating System for a Personal Computer", Proceedings of the Seventh Symposium on Operating System Principles, December 1979, and thereby forced changes in the style of integration for those releases. Since the released loader cannot load modules that refer to the new versions of operating system interfaces, the software of Cedar environment that is preloaded in the boot file must all be recompiled before any changes can be tested. Highest priority is given to producing a boot file in which these changes can be tested.
If the DF files describing the Cedar system were layered in hierarchical order, with the operating system at the bottom, this boot file could be built by producing new versions of the software in each DF file in DF-dependency order. FIG. 9 shows the dependency graph for DF files in the boot file, where an arrow from one DF file, e.g., Rigging.DF, to another, e.g., CedarReals.DF, indicates Rigging.DF IMPORTS some file(s) from CedarReals.DF. In this dependency graph, "tail" DF files depend on "head" DF files. Double headed arrows indicate mutual dependency. Basic Heads.DF means that this DF file includes other files, BasicHeadsDorado.DF, BasicHeadsDO.DF and BasicHeadCommon.DF, Communication.DF includes CommunicationPublic.DF, CommunicationFriends.DF and RS232Interfaces.DF. CompatabilityPackage.DF includes MesaBAsics.DF.
Note that Rigging.DF also depends on CompatibilityPackage.DF, but the dependency by CedarReals.DF on CompatibilityPackage.DF ensures a new version of Rigging.DF will be made after both lower DF files. The PilotInterfaces.DF file is at the bottom and must be changed before any other DF files.
This dependency graph is not acrylic, however. The most extreme cycle is in the box with six DF files in it, which is expanded in FIG. 10. Each DF file is in a cycle with at least one other DF file, so each DF file depends on the other, and possibly indirectly, and no DF file can be announced "first". There is an ordering in which these component can be built: If the interfaces listed in each of the DF files are compiled and DF files containing those interfaces are stored on <PreCedar>, each programmer can then compile the implementation modules in this component and then store the remaining files on <PreCedar>.
An example for the dependency graph for interfaces is shown in FIG. 11. This graph indicates that the interfaces of CIFS, VersionMap, Runtime, WorldVM, ListsAndAtoms, and IO can be compiled in that order. This interface dependency graph had cycles in it in the Cedar release that have since been eliminated. Appendix A contains examaples of some of these DF files before and after the release.
Recompilation of all the interfaces in the boot file requires that at least nine programmer/users participate. Since the boot file cannot be produced until all interfaces and implementation modules in the DF files of FIG. 9 are compiled, interface changes are encouraged to be made as soon as possible after a successful release and only once per release. Once the users have made their interface changes and a boot file using the new interfaces is built, the normal period of testing can occur and new changes to implementation modules can be made relatively painlessly.
Components being released that are outside the boot file have a much simpler dependency structure, shown in FIG. 12. The majority of these components are application programs that use Cedar system facilities already loaded in the boot file.
The information in the DF files of a release help to permit study and planning for the development of the Cedar system. The ability to scan, or query, the interconnection information gives a complete view of the use of software by other programs in the system. For example, one can mechanically scan the DF files of an entire release and build a dependency graph describing the interfaces used in Cedar and which implementors depend on these interfaces. Since VerifyDF ensures all interfaces needed by a component are described in its DF file, an accurate database of information can be assured. This information can be used to evaluate the magnitude of changes and anticipate which components can be affected. One can also determine which interfaces are no longer used, and plan to eliminate the implementation of those interfaces, which happens often in a large programming environment while it is under active development.
The Cedar release/DF approach assumes only one person is changing a DF file at a time. How would we cope with more than one modifier of a package? If the package is easily divided, as with the Cedar system window manager and editor, two or more DF files can be included by an "umbrella" DF file that is released. One of the implementors must "own" the umbrella DF file and must make sure that the versions included are consistent by running VerifyDF check on the umbrella file. If the package is not easily divided, then either a check in/check out facility must be used on the DF and its contents to guarantee only one person is making changes at a time, or a merge facility would be needed to incorporate mutually exclusive changes. Should more than one programmer change the same module, this merge facility would have to ask for advice on which of the new versions, if any, to include on the DF file. 2. Module Interconnection Language--SML
SML is a polymorphic and applicative language that is used to describe packages of Cedar modules. The programmer/user writes SML programs, which are called system models, to specify the modules in the system the user is responsible for and the interconnections between them. These system models are analyzed by a system modeller of the instant invention that automates the compile-edit-debug cycle by tracking changes to modules and performs the compilation and loading of systems.
The specification of module interconnection facilities of the Cedar system requires use of polymorphism, where the specification can compute a value that is later used as the type for another value. This kind of polymorphism is explained in detail later. The desire to have a crisp specification of the language and its use of polymorphism led to base SML on the Cedar Kernal language, which is used to describe the semantics of Cedar developed programs.
The semantics of the SML language have to be unambiguous so every syntactically-valid system model has clear meaning. The Cedar Kernal language has a small set of principles and is easily implemented. The clear semantics of Kermel language descriptions give a concise specification of the SML language and give good support to the needs of the module interconnection specification. SML could have been designed without reference to the Kernal language. However, without the Kernel language as a base, there would be less confidence that all language forms had clear meaning.
SML is an applicative language, since it has no assignment statement. Names or identifiers in SML are given values once, when the names are declared and the value of a name may not be changed later unless the name is declared in some inner scope. SML is easier to implement because it is applicative and function invocation has no side effects.
The fundamental concepts of SML are now presented, followed by a description of SML's treatment of files. The Cedar Kernal language, which serves as a basis for SML, is described, followed by a section on the syntax and semantics of SML expressions.
The Cedar System is based on the Mesa language see Mitchell et al., supra and Lauer et al., supra. The system contains features for automatic storage management (garbage collection) and allows binding of types at runtime, i.e. pointers to objects whose types are known only at runtime. The system derives from the Mesa language a rich module interconnection structure that provides information hiding and strong type checking at the module level, rather than at the procedure level. In order to better understand SML, it is important to know about the existing module interconnection facilities used in the Cedar system.
As previously indicated in part, a Cedar system consists of a set of modules, each of which is stored in a separate file. A module can be one of two types: an implementation (PROGRAM) module, or an interface (DEFINITIONS) module. Interface modules contain constants found in other Pascal-like languages: procedure declarations, type declarations, and other variables. A module that wishes to call a procedure declared in another module must do so by IMPORTing an interface module that declares this procedure. This interface module must be EXPORTED by a PROGRAM module. For example, a procedure "USortList" declared in a module "SortImpl" would also be declared in an interface Sort, and SortImpl would EXPORT Sort. A PROGRAM that wants to call the procedure USortList does so by IMPORTing Sort. We call the importer of Sort the "client" module and say SortImpl (the exporter) "implements" Sort. Of course, SortImpl may IMPORT interfaces to use that are defined elsewhere.
These interconnections are shown in FIG. 13, which shows filenames for each module in the upper left corner. The interface Sort defines an object composed of a pair of x,y coordinates. The EXPORTer, SortImpl.Mesa, declares a procedure that takes a list of these objects and sorts them, eliminating duplicates. LIST in the Cedar system is a built-in type with a structure similar to a Lisp list. ClientImpl.Mesa defines a procedure that calls USortList to sort a list of such objects. Details about "CompareProc" have been omitted for simplicity.
Most collections of modules in the system use the same version of interfaces, e.g., there is usually only one version of the interface for the BTree package in a given system. Situations arise when more than one version is used in a system. For example, there could be two versions of an interface to a list manipulation system, each one manipulating a different type of object.
FIG. 14 shows, on the left, the module from FIG. 13 and, on the right, another similar module that defines an "Object" to be a string instead of coordinates. A module that refers to the Sort interface would have to be compiled with one of the two versions of the Sort interface, since the compiler checks types of the objects being assembled for the sort. This is referred to as interface type parameterization since the types of items from the interface used by a client (ClientImpl.Mesa) are determined by the specific version of the interface (SortCoord.Mesa or SortNames.Mesa).
A different kind of parameterization may occur when two different implementations for the same interface are used. For example, a package that uses the left version of the Sort interface in FIG. 14 above might use two different versions of the module that EXPORTs Sort, one of which uses the QuickSort algorithm and the other uses the HeapSort algorithm to perform the sort. Such a package includes both implementors of Sort and must specify which sort routine the clients (IMPORTers) use when they call Sort.USortList[]. In the Cedar system, it is possible for a client module to IMPORT both versions, as shown in FIG. 15.
In FIG. 15, SortQuickImpl and SortHeapImpl both EXPORT different procedures for the Sort interface. One procedure, SortQuickImpl, uses QuickSort to sort the list. The other uses HeapSort to sort the list. The importer, ClientImpl, IMPORTS each version under a different name. SortQuickInst and SortHeapInst are called interface records, since they are represented as records containing pointers to procedures. The client procedure "TestThem" calls each in turn by specifying the name of the interface and the name of the procedure, e.g., SortQuickInst.USortList[].
How are the two interface records that are EXPORTED by SortQuickImpl and SortHeapImpl connected to the two interface records (SortQuickInst and SortHeapIInst) required by ClientImpl? A program called the Mesa Binder makes these connections by reading a specification written in a subset of Mesa called C/Mesa. C/Mesa source files, called CONFIGURATIONs, name the implementation modules involved and specify the interconnections. Below is shown the configuration that makes this connection:
______________________________________ClientConfig: CONFIGURATION = { SQ1: Sort ← SortQuickImpl[]; SHI: Sort ← SortHeapImpl[]; ClientImpl[SortQuickInst: SQ1, SortHeapInst: SHI]; }.______________________________________
Two variables are declared (SQI and SHI) that correspond to the interface records EXPORTED by the two modules. The client module is named, followed by the two interfaces given in keywork parameter notation.
This is called interface record parameterization, since the behavior of the client module is a function of which interfaces SortQuickInst and SortHeapInst refer to when they are called in ClientImpl.
C/Mesa, as currently defined, cannot express interface type parameterization at all. The semantics of some C/Mesa specifications are ambiguous. Because of this, the use of SML was choosen to replace the use of C/Mesa.
SML programs give the programmer/user the ability to express both kinds of parameterization. It is possible to think of SML as an extension of C/Mesa, although their underlying principles are quite different. Before explaining SML, reference is first made to an example of modules that use both interface type and interface record parameterization and show how this can be expressed in SML.
The essential features of SML are illustrated by the following simple model and are discussed later on relative to SML's treatment of files. A description of the SML language is also given later.
Consider two versions of the Sort interface from FIG. 14 and two EXPORTERs of Sort from FIG. 15. Since the EXPORTERs do not depend on the kind of object (coordinates or names), the EXPORTERs can each be constructed with a different type of object. Assume the client module wants to call USortList with all four combinations of object type and sort algorithm: (coordinates+quicksort, coordinates+heapsort, names+quicksort, names+heapsort). FIG. 16 shows a version of ClientImpl module that uses all four combinations of object type.
In SML, a model to express this is shown in Table II below.
TABLE II______________________________________ClientModel˜[______________________________________interface typesSortCoord: INTERFACE˜@SortCoord.Mesa[];SortNames: INTERFACE˜@SortNames.Mesa[];interface recordsSQCI: SortCoord˜@SortQuickImpl.Mesa[SortCoord];SQNI: SortNames˜@SortQuickImpl.Mesa[SortNames];SHCI: SortCoord˜@SortHeapImpl.Mesa[SortCoord];give all to clientClient: CONTROL˜@Clientlmpl.Mesa[SortCoord.SortNames.SQCI,SQNI,SHCI,SHNI]______________________________________
SML allows names to given types and bound to values. After the header, two names "SortCoord" and "SortNames" are given values that stand for the two versions of the Sort interface. Each has the same type, since both are versions of the Sort interface. Their type is "INTERFACE Sort", where "INTERFACE" is a reserved word in SML and "Sort" is the interface name. The next four lines bind four names to interface records that correspond to the different sort implementations. "SQCI" is a name of type "SortCoord" and has as value the interface record with a procedure that uses QuickSort on objects with coordinates. Similarly, "SQNI" has as value an interface record with a procedure for QuickSort on objects with strings, etc. Note that each of the four implementations is parameterized by the correct interface, indicating which type to use when the module is compiled.
The last line specifies a name "Client" of reserved type "CONTROL" and gives it as value the source file for ClientImpl, parameterized by all the previously defined names. The first two, SortCoord and SortNames, are values to use for the names "SortCoord: INTERFACE Sort" and "SortNames: INTERFACE Sort" in the DIRECTORY clause of ClientImpl. The last four, in order, give interface records for each of the four imports.
There are a number of nearly-equal names in the example. If all related names were uniform, e.g., SortQuickCoordImpl instead of SQHI and SortQuickCoordInst, and SortHeapCoordImpl instead of SQHI and SortHeapCoordInst, then the parameter lists in the example could be omitted.
The kinds of values in SML follow naturally from the objects being represented: the value of "@ SortCoord.Mesa[]" is the object file for the interface module SortCoord.Mesa when it is compiled. The value of "@ SortQuickImpl.Mesa[]" is an interface record produced when the object file for SortQuickImpl.Mesa is loaded. Note there are two versions of the object file for SortQuickImpl.Mesa: one has been compiled with SortCoord as the interface it EXPORTs, and the other has been compiled with SortNames as the interface it EXPORTs.
It is helpful to differentiate the two types of parameterization by the difference in uses: Interface type parameterization is applied when a module is compiled and the types of the various objects and procedures are checked for equality. Interface record parameterization is applied when a module is loaded and the imports of other modules are resolved. The interface records by which a module is parameterized are used to satisfy these inter-module references.
The SML language is built around four concepts:
1. Application: The basic method of computing.
2. Values: Everything is a value, including types (polymorphism) and functions.
3. Binding: Correspondence between names and values is made by binding.
4. Groups: Objects can be grouped together.
The basic method of computation in the SML language is by applying a function to argument values. A function is a mapping from argument values to result values.
A function is implemented either by a primitive supplied by the language (whose inner workings are not open to inspection) or by a closure, which is the value of a λ-expression whose body, in turn, consists of applications of functions to arguments. In SML, λ-expressions have the form
λ[free-variable-list]→[returns-list]IN[body-expression]
For example, a λ-expression could look like
λ[x: STRING, y: STRING]→[a: STRING]IN[exp]
where "x" and "y" are the free variables in the λ-expression, "a" is the name of the value returned when this λ-expression is invoked, and exp is any SML expression that computes a value for name "a". "IN" is like "." in standard λ-notation. It is helpful to think of a closure as a program fragment that includes all values necessary for execution except the λ's parameters, hence the term closure. Every λ-expression must return values, since the language has no side effects. Application is denoted in programs by expressions of the form ƒ[arg, arg, . . . ].
A SML program manipulates values. Anything that can be denoted by a name or expression in the program is a value. Thus strings, functions, interfaces, and types are all values. In the SML language, all values are treated uniformly, in the sense that any can be passed as an argument, bound to a name, or returned as a result.
These operations must work on all values so that application can be used as the basis for computation and λ-expressions as the basis for program structure. In addition, each particular kind or type of value has its own primitive functions. Some of these (like equality) are defined for most types. Others (like subscripting) exist only for specific types (like groups). None of these operations, however, is fundamental to the language.
There is a basic mechanism for making a composite value out of several simpler ones. Such a composite value is called a group, and the simpler ones are its components or elements. Thus [3, x+1, "Hello"] denotes a group, with components 3, x+1, and "Hello". The main use of groups is for passing arguments to functions without naming them. These are sometimes called positional arguments. Groups are similar to other language's "structures" or "records": ordered and typed sequences of values.
A binding is an ordered set of [name, type, value] triples, often denoted by a constructor like the following: [x: STRING˜"s", y: STRING˜"t"], or simply [x˜"s", y˜"t"]. Individual components can be selected from a binding using the "." operation, similar to Pascal record selection: binding.element yields the value of the component named "element" in binding.
A scope is a region of the program in which the value bound to a name does not change. For each scope there is a binding that determines these values. A new scope is introduced by a [. . . ] constructor for a declaration or binding, or a LET statement illustrated below.
A declaration is an ordered set of [name, type] pairs, often denoted [x: STRING, y: STRING]. A declaration can be instantiated (e.g. on block entry) to produce a binding in which each name is bound to a name of the proper type. If d is a declaration, a binding b has type d if it has the same names, and for each name n the value b.n. has the type d.n.
In addition to the scopes defined by nested bindings, a binding can be added to the scope using a LET statement,
LET binding IN expr
that makes the names in binding accessible in expr without qualification.
Every name has a type, either because the name is in a binding or the name is in a declaration. Names are given values using bindings. If a name is given an explicit type in the binding, the resulting value must have that type. For example,
n: t˜v
the type of "v" must be "t". Similarly, if "p" is a λ-expression with "a" as a free variable of type "STRING", then
p[b]
type-checks if "b" has type "STRING".
There are no restrictions on use of type as values in SML. For example,
______________________________________ [nl: t ˜ v1, n2: n1 ˜ v2]______________________________________
declares a name "n1" with a type t and a value v1, and then declares a name "n2" with type "n1" and value "v2". Although each such value can in turn be used as the type of another name, the modeller implementation does not attach semantics to all such combinations.
Strings are useful in a module interconnection language for compiler options and as components of file names. SML contains facilities to declare strings. For example, the binding
______________________________________ [x: STRING ˜ "lit", y; STRING ˜ x]______________________________________
gives x and y the string literal value "lit".
SML describes software by specifying a file containing data. This file is named in SML by a filename proceded by an @. SML defines @ as source-file inclusion: The semantics of an @-expression are idential to those of an SML program that replaced the @ expression by its contents. For example, if the file inner.sm contained
"lit"
which is a valid SML expression, the binding
______________________________________ [x: STRING ˜ @inner.sm, y: STRING ˜ @inner.sm] and [x: STRING ˜ "lit", y: STRING ˜ "lit"]______________________________________
The @-expression is used in SML to refer to source modules. Although we cannot substitute the @-expression by the contents of the source file since it is written in C/Cedar, we treat the Cedar source file as a value in the language with a type. This type is almost always a procedure type. The values in SML that describe module interconnection are all obtained by invoking one of the procedure values defined by an @-expression.
When compiling a system module, all interfaces it depends on must be compiled first and the compiler must be given unambiguous references to those files. In order to load a module, all imports must be satisfied by filling in indirect pointers used by the microcode with references to procedure descriptors EXPORTed by other modules. Both kinds of information are described in SML by requiring that the user declare objects corresponding to an interface file (for compilation) or an interface record with procedure descriptors (for loading), and then parameterize module objects in SML as appropriate.
Consider an interface that depends on no other interfaces, i.e., it can be compiled without reference to any files. SML treats the file containing the interface as a function whose closure is stored in the file. The procedure type of this interface is for a procedure that takes no parameters and returns one result, e.g.,
[]→[INTERFACE Sort]
where "Sort" is the name of the interface, as in FIG. 13. The application of this λ-expression (with no arguments) will result in an object of type "INTERFACE Mod".
Id: INTERFACE Sort˜@ Sort.Mesa[]
declares a variable "Id" that can be used for subsequent dependencies in other files. An interface "BTree" defined in the file "BTree.Mesa" that depends on an interface named "Sort" would have a procedure type like:
[INTERFACE Sort]→[INTERFACE BTree]
The parameters and results are normally given the same name as the interface type they are declared with, so the procedure type would be:
[Sort: INTERFACE Sort]→[BTree: INTERFACE BTree]
In order to express this in his model, the user would apply the file object to an argument list:
Sort: INTERFACE Sort˜@ Sort.Mesa[];
BTree: INTERFACE BTree˜@ BTree.Mesa[Sort];
These interfaces can be used to reflect other compilation dependencies.
An interface that is EXPORTed is represented as an interface record that contains procedure descriptors, etc. These procedures are declared both in the interface being EXPORTed and in the exporting PROGRAM module. One can think of the interface record as an instance of a record declared by the interface module. Consider the implementation module SortImpl.Mesa in FIG. 13. SortImpl EXPORTs an interface record for the Sort interface and calls no procedures in other SortImpl EXPORTs an interface record for the Sort interface and calls no procedures in other modules (i.e., has no IMPORTs). This file would have as procedure type:
[Sort: INTERFACE Sort]→[SortInst: Sort]
and would be used as follows:
Sort: INTERFACE Sort˜@ Sort.Mesa[];
SortInst: Sort˜@ SortImpl.Mesa[Sort];
which declares an identifier "SortInst" of the type "Sort", whose value is the interface record exported by SortImpl.Mesa. If SortImpl.Mesa imported an interface reocrd for "BTree," then the procedure type would be:
[Sort: INTERACE Sort, BTree: INTERFACE BTree. BTreeInst: BTree]→[SortInst: Sort]
and the exported record would be computed by:
SortInst: Sort˜@ SortImpl.Mesa[Sort, BTree, BTreeInst]:
where [Sort, BTree, BTreeInstr] is a group that is matched to parameters of the procedure by position. Keyword matching of actuals to formals can be accomplished through a binding described later.
LET statements are useful for including definitions from other SML files. A set of standard Cedar interfaces could be defined in the file CedarDefs.Model:
______________________________________Rope: INTERFACE Rope ˜ @Rope.Mesa,IO: INTERFACE IO ˜ @IO.Mesa,Space: INTERFACE Space ˜ @Space.Mesa]______________________________________
Then a LET statement like:
LET @ Cedar Defs.Model IN [expression]
is equal to:
______________________________________LET [Rope: INTERFACE Rope ˜ @Rope.Mesa,IO: INTERFACE IO ˜ @IO.MesaSpace: INTERFACE Space ˜ @Space.Mesa]IN [expression]______________________________________
and makes the identifiers "Rope", "IO", and "Scope" available within [expression].
SML syntax is described by the BNF grammar below. Whenever "x, . . . " appears, it refers to 0 or more occurrences of x separated by commas. "|" separates different productions for the same non-terminal. Words in which all letters are capitalized are reserved keywords. Words that are all lower case are non-terminals, except for
id, which stands for an identifier,
string, which stands for a string literal in quotes, and
filename, which stands for a string of characters that are legal in a file name, not surrounded by quotes.
Subscripts are used to identify specific non-terminals, so they can be referenced without ambiguity in the accompanying explanation.
______________________________________ exp :: = 1 [decl.sub.1 ] → [decl.sub.2 ] IN exp.sub.1 |let [binding] IN exp.sub.1 |exp.sub.1 → exp.sub.2 |exp.sub.1 [exp.sub.2 ] |exp.sub.1 . id |[exp, . . . ] |[decl] |[binding] |id |string |INTERFACE id |STRING |@filename decl :: = id: exp, . . . binding :: = bindelem, . . . bindelem :: = [decl] ˜ exp.sub.1 |id: exp.sub.1 ˜ exp.sub.2 |id ˜ exp.sub.1______________________________________
A model is evaluated by running a Lisp-style evaluator on it. This evaluator analyzes each construct and reduces it to a minimal form, where all applications of closures to known values have been replaced by the result of the applications using β-reduction. The evaluator saves partial values to make subsequent compilation and loading easier. The evaluator returns a single value, which is the value of the model, usually a binding.
The semantics for the productions are:
exp::=λ[decl.sub.1 ]→[decl.sub.2 ]IN exp.sub.1
The expression is a value consisting of the parameters and returned names, and the closure consisting of the expression exp1 and the bindings that are accessible statically from exp. The type is "decl1 →decl2 ". The value of this expression is similar to a procedure variable in conventional languages, which can be given to other procedures that call it within their own contexts. The closure is included with the value of this expression so that, when the λ-expression is invoked, the body (exp1) will be evaluated in the corect environment or context.
exp::=LET [binding]IN exp.sub.1
The current environment of exp1 is modified by adding the names in the binding to the scope of exp1. The type and value of this expression are the type and value of exp1.
exp::=exp.sub.1 →exp.sub.2
The value of exp is a function type that takes values of type exp1 and returns values of type exp2.
exp::=exp.sub.1 [exp.sub.2 ]
The value of exp1, which must be a closure, is applied to the argument list exp2 as follows. A binding is made for the values of the free variables in the λ-expression. If exp2 is a group, then the components of the group are matched by type to the formals of the λ-expression. The group's components must have unique types for this option. If exp2 is a binding then the parameters are given values using the normal binding rules to bind f˜exp2 where exp2 is a binding and f is the decl of the λ-expression.
There are two cases to consider:
1. The λ-expression has a closure composed of SML expressions. This is treated like a nested function. The evaluation is done by substitution or β-reduction: All occurrences of the parameters are replaced by their values. The resulting closure is then evaluated to produce a result binding. The λ-expression returns clause is used to form a binding on only those values listed in the λ-expression returns list, and that binding is the value of the function call.
2. If the function being applied is a Cedar source or object file, the evaluator constructs interface types of interface records that correspond to the interface module or to the implementation module's exported interfaces, as appropriate. After the function is evaluated, the evaluator constructs a binding between the returned types in its procedure type and the values of the function call.
exp::=[exp, . . . ]
The exp1 is evaluated and must be a binding. The component with name "id" is extracted and its value returned. This is ordinary Pascal record element selection.
exp::=[exp, . . . ]
A group of the values of the component exp's is made and returned as a value.
exp::=[decl]
decl::=id:exp, . . .
Adds names "id" to the current scope with type equal to value of exp. A list of decls is a fundamental object.
______________________________________ exp :: = [binding] binding :: = bindelem, . . . bindelem :: = [decl] ˜ exp.sub.1 |id: exp.sub.1 ˜ exp.sub.2 |id ˜ exp.sub.1______________________________________
A bindelem binds the names in decl to the value of expl. If an id is given instead of a decl, the type of id is inferred from that of exp1. The binding between the names in decl and the values in exp1 follows the same rules as those for binding arguments to parameters of functions.
exp::=id
id stands for an identifier in some binding (i.e., in an enclosing scope). The value or id is its current binding.
exp::=string
A string literal like "abc" is a fundamental value in the language.
exp::=INTERFACE id
This fundamental type can be used as the type of any module with module name id. Note id is used as a literal, not an identifier, and its current binding is irrelevant. The value of this expression is the atom that represents "INTERFACE id".
exp::=STRING
A fundamental type in the language. The value of "STRING" is the atom that represents string types.
exp::=@ filename
This expression denotes an object whose value is stored in file filename. If the file is another model, then the string @ filename can be replaced by the content of the file. If it is another file, such as a source or object file, it stands for a fundamental object for which the evauator must be able to compute a procedure type.
Function calls in SML are made by applying a closure to (1) a group or (2) a binding. If the argument is a group, the parameters of the closure are matched to the components by type, which must be unique. If the argument is a binding, the parameters of the closure are matched by name with the free variables. For example, if p is bound to:
p˜λ[x: STRING, y: INTERFACE Y]→[Z: INTERFACE Z]IN[ . . . ]
then p takes two parameter, which may be specified as a group:
______________________________________defs: INTEFACE Y ˜ @Defs.Mesa[],z: INTERFACE Z ˜ p["lit", Defs]]______________________________________
where the arguments are matched by type to the parameters of the closure. The order of "lit" and Defs in the example above does not matter. Also the order of x and y in the call of p in the example does not matter. The function may also be called with a binding as follows:
______________________________________defs: INTERFACE Y ˜ @Defs,Mesa[],z: INTERFACE Z ˜ p[x ˜ "lit", y ˜ Defs]]______________________________________
which corresponds to keyword notation in other programming languages.
Since the parameter lists for Cedar modules are quite long, the SML language includes defaulting rules that allow the programmer to omit many parameters. When a parameter list, either a group or a binding, has too few elements, the given parameters are matched to the formal parameters and any formals not matched are given default values. The value for each defaulted formal parameter is the value of a variable defined in some scope enclosing the call with the ame name and type as the formal. Therefore, the binding for Z in:
______________________________________ [ x: STRING ˜ "lit", y: INTERFACE Y ˜ @Defs.Mesa[], z: INTERFACE Z ˜ p[] ]______________________________________
is equivalent to "p[x. y]" by the equal-name defaulting rule.
SML also allows projections of closures into new closures with parameter. For example,
______________________________________Y: INTERFACE Y ˜ @Defs.Mea[],pl:[Y: INTERFACE Y] ← [Z: INTERFACE Z] ˜ p["lit"],Z: INTERFACE Z ˜ pl[Y]]______________________________________
sets Z to the same value as before but does it in one extra step by creating a procedure value with one fewer free variable, and then applied the procedure value to a value for the remaining free variable. The defaulting rules allow parameter to be omitted when mixed with projections:
______________________________________X: STRING ˜ "lit",Y: INTERFACE Y ˜ @Defs.Mesa[],pl: [Y: INTERFACE Y] → [Z: INTERFACE Z] ˜ p[],Z: INTERFACE Z ˜ pl[]]______________________________________
Enough parameters are defaulted to produce a value with the same type as the target type of the binding (the type on the left side of the notation, "˜"). When the type on the left side is omitted, the semantics of SML guarantee that all parameters are defaulted in order to produce result values rather than a projection. Thus
Z˜p1[]
in the preceding examples declares a value Z of type INTERFACE Z and not a projection whose value is a λ-expression. These rules are stated more concisely below.
If the number of components is less than those required to evaluate the function body, a coercion is applied to produce either (1) the complete argument list, so the function body may be evaluated, or (2) a projection of the original λ-expression into a new λ-expression with fewer free variables. If the type of the result of "exp1 [exp2 ]" is supplied, one of (1) or (2) will be performed. When the target type is not given, e.g.,
x˜proc[Y]
case (1) is assumed and all parameters of "proc" are assumed defaulted. For example, the expression:
proc: [Y: STRING, Z: STRING]→[r: R],
x: T˜proc[Y]
binds the result of applying proc to Y to x of type T. If T is a simple type (e.g., "STRING"), then the proc[Y] expression is coerced into proc[YU, Z], where Z is the name of the omitted formal in the λ-expression and R must equal T. If Z is undefined (has no binding) an error has occurred and the result of the expression is undefined. If T is a function type (e.g., [Z: STRING]→[r: R]), then a new closure is replaced by tghe value of Y. This closure may be subsequently applied to a value of Z and the result value can be computed. The type of Z must agree with the parameters of the target function type.
The SML evaluator is embedded in a program management system that separates the functions of file retrieval, compilation, and loading of modules. Each of these functions is implemented by analyzing the partial values of the evaluated SML expression. For example, the application of a file to arguments is analyzed to see whether compilation or loading is required. For each of these phases, the evaluator could be invoked on the initial SML expression, but this would be inefficient. Since the SML language has no iteration constructs and no recursively-defined functions, the evaluator can substitute indirect references to SML expressions through @-expressions by the file's contents and can expand each function by its defining expression with formals replaced by actuals.
This process of substitution must be applied recursively, as the expansion of a λ-expression may involve expansion of inner λ-expressions. The evaluator does this expansion by copying the body of the λ-expression, and then evaluating it using the scope in which the λ-expression was defined after adding the actual parameters as a binding for the function to the scope.
The scope is maintained as a tree of bindings in which each level corresponds to a level of binding, a binding added by a LET statement, or a binding for parameters to a λ-expression.
Bindings are represented as lists of triples of name, type, value. A closure is represented as a quadruple comprising "list of formals, list of returns, body of function, scope printer", where the scope pointer is used to establish the naming environment for variables inside the body that are not formal parameter. The @-expression is represented by an object that contains a pointer to the disk file named. A variable declared as INTERFACE mod (i.e., an interface type variable), is represented as a "module name, pointer to module file" pair, and a variable given as type and interface type variable, i.e., an interface record variable, is repreented as a "pointer to procedure descriptors, pointer to loaded module".
The substitution property of Russell, discussed in the Article of A. Demers et al., "Data Types, Parameters & Type Checking", Proceedings of the Seventh Symposium on Principles of Programming Languages, Las Vegas, Nev., pp. 12-23, 1980, guarantees that variable-free expressions can be replaced by their values without altering the semantics of Russell programs. Since SML programs have no variables and allow no recursion, the substitution property holds for SML programs as well. This implies that the type-equivalence algorithm for SML programs always terminates, since the value of each type can always be determined statically.
The following are two further examples of models described in SML.
The B-tree package consists of an implementation module in the file "BTreeImpl.Mesa" and an interface "BTree.Mesa" that BTreeImpl EXPORTS. There is no client of BTree, so this model returns a value for the interface type and record for BTree. Some other model contains a reference to this model and a client for that interface. The BTree interface uses some constants found in "Ascii.Mesa", which contains names for the ASCII chaacter set. The BTreeImpl module depends on the BTree interface since it EXPORTs it and makes use of three standard Cedar interfaces. "Rope" defines procedures to operate on immutable, garbage collected strings. "IO" is an interface that defines procedures to read and write formatted data to a stream, often the user's computer terminal. "Space" defines procedures to allocate Cedar virtual memory for large objects, in this case the B-tree pages.
______________________________________Exl.ModelLET [Rope: INTERFACE Rope ˜ @Rope.Bed,IO: INTERFACE IO ˜ @IO.Bed,Space: INTERFACE Space ˜ @Space.Bed,] INBTreeProc ˜λ[RopeInst: Rope, IOIsnt:]O, SpaceInst: Space]→ [BTree: INTERFACE BTree, BTreeInst: BTree]IN [Ascii: INTERFACE Ascii ˜ @Ascii.MesaBTree: INTERFACE BTree ˜ @Btree[Ascii],BTreeInst: BTree ˜]@BTreeImpl.Mesa[BTree, Rope,]O.Space,RopeInst, IOInst. SpaceInst]______________________________________
This model, stored in the file "Exl.Model", describes a BTree system composed of an interface "BTree" and an implementation for it. The first three lines declare three names used later. Since they are given values that are object or binary (.bcd) files, they take no parameters. This model assumes those files have already been compiled. Note they could appear as:
Rope˜@Rope.Bcd,
IO˜@IO.Bcd,
Space˜@Space.Bcd
since the types of the three identifiers can be determined from their values. The seventh line binds an identifier "BTreeProc" to a λ-expression with three interface records as parameters. If those are supplied, the function will return (1) an interface type for the BTree system, and (2) an interface record that has that type. Within the body of the closure of the λ-expression, there are bindings for the identifiers "Ascii", "BTree", and "BTreeInst". In all cases, the type could be omitted as well.
The file "Exl.Model" can be evaluated. Its value will be a binding of BTreeProc to a procedure value. The value is a λ-expression that must be applied to an argument list to yield its return values. Another model might refer to the BTree package by:
[BTree. BTreeInst]˜@Exl.Model).BTreeProc[RopeInst, IOInst, SpaceInst]
______________________________________CedarDefs.ModelRope: INTERFACE Rope ˜ @Rope.Bed,IO: INTERFACE IO ˜ @IO.Bed.Space: INTERFACE Space ˜ @Space.Bed]BTree.ModelLet @CedarDefs.Model IN[BTreeProc ˜λ[RopeInst: Rope, IOIsnt:]O, SpaceInst: Space]→ [BTree: INTERFACE BTree. BTreeInst: BTree]IN[Ascii: INTERFACE Ascii ˜ @Ascii.Mesa.BTree: INTERFACE BTree ˜ @BTree[Ascii],BTreeInst: BTree ˜ @BTreeImpl.Mesa[BTree, Rope,]O, Space,RopeInst,]OInst, SpaceInst]]]______________________________________
The prefix part is split into a separate file. The BTree.Model file contains (1) a binding that gives a name to the binding in CedarDefs. Model, and (2) a LET statement that makes the values in CedarDefs.Model accessible in the λ-expression of BTree.Model.
Dividing Example 1 into two models like this allows us to establish standard naming environments, such as a model that names the commonlyused Cedar interfaces. Programmer/users are free to redefine these names with their models if they so desire.
The System modeller is a complete software development system which uses information stored in a system model, which describes a software system in the environment, e.g., the Cedar user or programmer, the modeller performs a variety of operations on the systems described by the system models:
1. It implements the representation of the system by source text in a collection of files.
2. It tracks changes made by the programmer. To do this, it is connected to the system editor and is notified when files are edited and new versions are created.
3. It automatically builds an executable version of the system, by recompiling and loading the modules. To provide fast response, the modeller behaves like an incremental complier: only those modules that change are analyzed and recompiled.
4. It provides complete support for the integration of packages as part of a release.
Thus, the modeller can manage the files of a system as they are changing, providing a user interface through which the programmer edits, compiles, loads and debugs changes interactively while developing software. The models are automatically updated to refer to the changed components. Manual updates of models by the programmer are, therefore, not normally necessary.
The programmer writes a model in SML notation for describing how to compose a set of related programs from their components. The model refers to a component module of the program by its unique name, independently of the location in the file system where its bits are stored. The development of a program can be described by a collection of models, one for each stage in the development; certain models define releases.
As previously indicated, SML has general facilities for abstraction. These are of two kinds:
(1) A model can be organized hierarchially into parts, each of which is a set of named sub-parts called a binding. Like the names of files in a directory, the names in a binding can be used to select any desired part or parts of the binding.
(2) A model can be parameterized, and several different versions can be constructed by supplying different arguments for the parameters. This is the way that SML caters for planned variation in a program.
The distributed computing environment means that files containing the source text of a module can be stored in many places. A file is accessed most efficiently if it happens to be on the programmer's own machine or computer..
When invoked, the modeller uses the objects in a model to determine which modules need to be recompiled. The modeller will get any files it needs and try to put the system together. Since it has unique-ids for all the needed sources, it can check to see if they are nearby. If not, it can take the path name in the model as a hint and, if the file is there, it can be retrieved. The modeller may have difficulty retrieving files, but it will not retrieve the wrong version. Having retrieved as many files as possible, it will compile any source files if necessary, load the resulting binary files, and run the program.
A model normally refers to source files rather than the less flexible binary or object files produced by the compiler, whose interface types are already bound. The system modeller takes the view that these binary files are just accelerators, since every binary file can be compiled using the right source files and parameters. The model has no entry for a binary file when the source file it was compiled from is listed. Such an entry is unnecessary since the binary file can always be reconstructed from the source. Of course, wholesale recompilation is time consuming, so various databases are used to avoid unnecessary recompilation.
Models refer to objects, i.e., source or binary (object) files or other models, using an @-sign followed by a host, directory, and file name, optionally followed by version information. In a model, the expression,
@[Indigo]<Cedar>X.Mesa!(July 25, 1982 16:10:09)
refers to the source version of X.Mesa created on July 25, 1982 16:10:09 that is stored on file server [Indigo] in the directory <Cedar>. The !(. . . ) is not part of the file name but is used to specify explicitly which version of the file is present. The expression,
@[Indigo]<Cedar>X.Bed!(1AB3FBB462BD)
refers to the binary or object version of X.Bcd on [Indigo]<Cedar>X.Bcd that has a 48-bit version stamp "1AB3FBB462BD" (hexadecimal). For cases when the user wants the most recently-saved version of X.Mesa or X.Bcd,
@[Indigo]<Cedar>X.Mesa!H
refers to the most recently stored version of X.Mesa on [Indigo<Cedar>. This "!H" is a form of implicit parameterization. If a model containing such a reference is submitted as part of a software release, this reference to the highest version is changed into a reference to a specific version.
The system modeller takes a very conservative approach, so the users can be sure there is no confusion on which versions have been tested and are out in the field of the distributed software system.
What happens, however, when a new version V2 of an object is created? In this view, such a version is a new object. Any model M1 which refers to the old object V1 continues to do so. However, it is possible to create a new model M2 which is identical to M1 except that every reference to V1 is replaced by a reference to V2. This operation is performed by the modeller and called Notice. In this way, the notion that objects are immutable is reconciled with the fact of evolution.
With these conventions, a model can incorporate the text of an object by using the name of the object. This is done in SML expression by writing an object name preceded by sign "@". The meaning of an SML expression containing an @-expression is defined to be the meaning of an expression in which the @ expression is replaced by its contents. For example, if the object inner.model contains
"lit"
which is an SML expression, the binding
______________________________________ [x:STRING ˜ @inner.sm, y:STRING ˜ "lit"]______________________________________
has identical values for x and y.
With these conventions, a system model is a stable, unambiguous representation for a system. It is easily transferred among programmers and file systems. It has a readable text representation that can be edited by a user at any time. Finally, it is usable by other program utilies such as cross-reference programs, debuggers, and optimizers that analyze intermodule relationships.
The modeller uses the creation date of a source object as its unique identifier. Thus, an object name might have the form BTree.Cedar!(July 22, 1982 2:23:56); in this representation the unique identifier follows the "!" character., such as in the form, BTree.cedar!H. This means to consider all the objects whose names begin BTree.cedar, and take the one with the most recent create date.
As previously explained, Cedar programing consists of a set of modules. There is included two kinds of modules: implementation (PROGRAM) modules, and interface (DEFINITIONS) modules. An interface module contains constants (numbers, types, inline procedures, etc.) and declarations for values to be supplied by an implementation (usually procedures, but also types and other values). A module M1 that calls a procedure in another module M2 must IMPORT an instance Inst of an interface I that declares this procedure. Inst must be EXPORTED by the PROGRAM module M2. For example, a procedure Insert declared in a module BTreeImpl would also be declared in an interface BTree, and BTreeImpl would EXPORT an instance of BTree. A PROGRAM calls Insert by IMPORTing this instance of BTree and referring to the Insert component of the instance. The IMPORTer of BTree is called the client module, and BTreeImp, the EXPORTer, implements Btree. Of course BTreeImpl may itself IMPORT and uses interfaces that are defined elsewhere.
FIG. 17 discloses a very simple system model called BTree, which defines one interface BTree and one instance BTreeInst of BTree.
BTree.model in FIG. 17 refers to two modules, BTree.cedar!(Sept. 9, 1982, 13:52:55) and BTreeImpl.cedar!(Jan. 14, 1983 14:44:09). Each is named by a user-sensible name (e.g., BTree.cedar), pat of which identifies the source language as Cedar, and a creation time (e.g. !(Sept. 9, 1982, 13:52:55)) to ensure uniqueness. The @ indicates that a unique object name follows. Each object also has a file location hint, e.g., ([Ivy]<Schmidt>, i.e., file server, Ivy, and the directory, Schmidt).
BTree.model refers to two other models, CedarInterfaces.model!(July 25, 1982, 14:03:03) and CedarInstances.model!(July 25, 1982, 14:10:12). Each of these is a binding which gives names to four interface or instance modules that are part of the software system. A clause such as
LET CedarInterfaces.model IN . . .
makes the names bound in CedarInterfaces (Acii, Rope, IO, Space) denote the associated values (Ascii.cedar!(July 10, 1982, 12:25:00)[], argument. Applying the first function to its interface arguments is done by the compiler; applying the resulting second function to its instance arguments is done by the loader as it links up definitions with uses.
In the example of FIG. 17, the BTree interface depends on the Ascii interface from CedarInterfaces. Since it is an interface, it does not depend on any implementations. BTreeImpl depends on a set of interfaces which the model does not specify in detail. The "*" in front of the first parameter list for BTreeImpl means that its arguments are defaulted by name matching from the system environment. In particular, it probably has interface parameters BTree, Rope, IO, and Space. All these names are defined in the environment, BTree explicitly and the others from CedarInterfaces through the LET clause, BTreeImpl also depends on Rope, IO and Space instances from CearInstances, as indicated in the second argument list.
The interface parameters are used by the compiler for type-checking, and so that details about the types can be used to improve the quality of the object code. The instance parameters are used by the loader and they specify how procedures EXPORTed by one module should be linked to other modules which IMPORT them.
The system modeller provides an interactive interface for ordinary incremental program development. When used interactively, the role of the modeller is similar to that of an incremental compiler; it tries to do as little work as it can as quickly as possible in order to produce a runnable system. To do this, it keeps track incrementally of as much information as possible about the objects in the active models under use.
For example, consider the following Scenario. Assume a model already exists, say BTree.model, and a user wants to change one module to fix a bug (code error). Earlier, the user has started the modeller with BTree.model as the current model. The user uses the system editor to make a change to BTreeImpl.cedar!(Jan 14, 1983 14:44:09). When the user finishes editing the module and creates a new version BTreeImpl.cedar!(Apr. 1, 1983, 9:22:12), the editor notifies the modeller by calling its Notice procedure, indicating the BTreeImpl.cedar!(Apr. 1, 1983, 9:22:12) has been produced from BTreeImpl.cedar!(Jan. 14, 1983, 14:44:09). If the latter is referenced by the current model, the modeller notices the new version and updates BTree.model!(Jan. 14, 1983, 14:44:11) to produce BTree.model!(Apr. 1, 1983, 9:22:20), which refers to the new version. The user may edit and continue to change more files. When the user wants to make a runnable version of the system, upon command to the modeller, which then compiles everything in correct order and, if there are no errors, produces a binary file.
A more complex scenario involves the parallel development of the same system by two programmers. Suppose both start with a system described by the model M0, and end up with different models M1 and M2. They may wish to make a new version M3 which merges their changes. The modeller can provide help for this common case as follows: If one programmer has added deleted or changed some object not changed by the other, the modeller will add, delete, or change that object in a merged model. If both programmers have changed the same object in different ways, the modeller cannot know which version to prefer and will either explore the changed objects recursively, or ask the user for help.
More precisely, we have
M.sub.3 =Merge[Base˜M.sub.0, New.sub.1 ˜M.sub.1, New.sub.2 ˜M.sub.2 ]
and Merge traces out the three models depth-first. At each level, for a component named p:
______________________________________If Add to result______________________________________Base.p=M1.p=M2.p Base.pBase.p=M.sub.1/2.p≠M2/1.p M.sub.2/1.pBase.p=M.sub.1/2.p, no M2/1.p leave p outno Base.p or M.sub.1/2.p M.sub.2/1.pBase.p≠M.sub.1.p≠M.sub.2.p, all models Merge[Base.p:,M.sub.1.p,M.sub.2.p]ELSE error, or ask what to do.______________________________________
At all points, the modeller maintains a model that describes the current program. When a user makes a decision to save a module or program, this is accomplished by an accurate description in the model. Since the models are simply text files, the user always has the option of editing the model as preferred, so the modeller does not have to deal with specifically obscure special cases of editing.
In a session which is part of the daily evolution of a program of software system, the user begins by creating an instance of the modeller, which provides a window on the user's screen, as shown in FIG. 20, in this case being that of the Cedar environment. The following explanation and subsequent sections to follow give an overview of its use, suggested by the contents of the Figure per se.
The modeller window is divided into four fields, which are, from top to bottom: (1) A set of screen initiated names in field 30 that function as buttons to control the modeller, (2) A field 32 where object names may be typed, (3) A feedback field 34 for compiler progress messages, and (4) A feedback field 36 for modeller messages.
To aid in the explanation modeller, the following example follows the steps the user performs to use the modeller. These steps are illustrated in the flow diagram of FIG. 21.
Step 1. Assume that the modeller instance has just been created. The user decides to make changes to the modules in Example.Model. The name of the model is entered in the field 32 following the "ModelName:" prompt, and initiates the StartModel button in field 30. From this point on the modeller is bound to Example.Model. StopModel in field 30 must be initiated before using this instance of the modeller on another model. StartModel initializes data structures in this instance of the modeller, StopModel frees the data.
Step 2. The user makes changes to objects on the user's personal machine or computer. The system editor calls the modeller's Notice procedure to report that a new version of an object exists. If the object being edited is in the model, the modeller updates its internal representation of the model to reflect the new version. If the changes involve adding or deleting parameters to modules, the modeller uses standard defaulting rules to modify the argument list for the object in the model.
Step 3. Once the user has made the intended edits, the user initiates Begin in field 30, which (a) recompiles modules as necessary, (b) loads their object files into memory, and (c) the programs, the user may want to make changes simple enough that the old module may be replaced by the new module without re-loading and restarting the system. If so, after editing the modules, the user initiates "Continue" in field 30, which tries to replace modules in the already loaded system. If this is successful, the user may proceed with the testing of the program and the new code will be used. If the module is not replaceable, the user must initiate "Begin" in field 30, which will unload all the old modules in this model and load in the new modules.
Step 5. After completing desired changes, the user can initiate "StoreBack" in field 30 to store copies of his files on remote file servers, and then initiate "Unload" to unload the modules previously loaded, and finally initiate "StopModel" to free modeller data structures.
The following is a more further explanation of some of the field 30 initiated functions.
StartModel: The modeller begins by reading in the source text of a model and buiding an internal tree structure traversed by subsequent phases. These phases use this tree to determine which modules must be compiled and loaded and in what order. Since parameters to files may have been defaulted, the modeller uses a database of information about the file to check its parameterization in the model and supply defaults, if necessary. If the database does not have an entry for the version of the file listed in the model, the modeller will read the file and analyze it, adding the parameterization information to the database for future reference. This database is described later.
Notice Operation: The system editor notifies a modeller running on the machine when a new version of a file is created. The modeller searches its internal data structure for a reference to an earlier version of the file. If one is found, the modeller changes the internal data structure to refer to the new version.
While making edits to modules, users often alter the parameterization of modules, i.e., the interface types and IMPORTed interface records. Since editing the model whenever this happens is time-consuming, the modeller automatically adjusts the parameterization, whenever possible, by using the defaulting rules of the modelling language: If a parameter is added and there is a variable with the same name and type as the new parameter, that variable is used for the actual parameter. If a parameter is removed, then the corresponding actual parameter is removed. The modeller re-parses the header of a "noticed" module to determine the parameters it takes.
Some changes made by the user cannot be handled using these rules. For example, if the user changes a module so that it IMPORTs an interface record, and there is no interface record in the model with that name, the modeller cannot known which interface record was intended. Similarly, if the user changes the module to EXPORT a new interface record, the modeller cannot know what name to give the EXPORTed record in the model. In these situations, the user must edit the model by hand to add this information and start the modeller again on the new version of the model.
Compilation and Loading: After the user initiates "Begin," the modeller uses the internal data structure as a description of a software system the user wants to run on the particular machine. To run the system, each module must have been compiled, then loaded and initialized for execution. The modeller examines each module using the dependency graph implied by the internal data structure. Each module is compiled in correct compilation order if no suitable object file is available. Modules that take no parameters are examined first, then modules that depend on modules already analyzed are examined for possible recompilation, and so on, until, if necessary, all modules are compiled. Modules are only recompiled if (1) the modules they depend on have been recompiled, or (2) they were compiled with a different version of the compiler or different compiler switches than those specified in the model. If there are no errors, the modeller loads the modules by allocating memory for the global variables of each module and setting up links between modules by filling in the interface records declared in the module. When loading is completed, execution begins.
StoreBack: Models refer to files stored on central file servers accessable by users on the distributed system. The user types a file name without file server or directory information to the system editor, such as "BTreeImpl.Mesa," and the editor uses information supplied by the modeller to add location information (file server and directory) for the files. If the file name without location information is ambiguous, the user must give the entire file name to the editor. To avoid filling file servers with excess versions, the modeller does not store a new version of a source file on a file server after the source file is edited. Instead, the new versions are saved on the local disk. When the user initiates "StoreBack", all source files that have been edited are saved on designated remote directories. A new version of the model is written to its remote directory, with references to the new versions of source files it mentions.
The compiler may have produced new versions of object files for source files listed in the model. Each object file so produced is stored on the same directory as its corresponding source file.
Multiple Instances of Modellers: More than one modeller may be in use on the same machine. The user can initiate the "NewModel" button to create another window with the four subwindows or fields shown in FIG. 20 and is used in the same manner. Two instances of a modeller can even model two versions of the same system model. Since file names without locations are likely to be ambiguous in this case, the user will have to type file names and locations to the editor and do the same for the "ModelName:" field 32 in the modeller window.
Other aspects of the operation of the modeller and modeller window in FIG. 20 is described in the following sections.
Some models are shared among many users, who refer to them in their own models by using the @-notation and then using returned values from these shared models. An example is the model, "BasicCedar.Model," which returns a large number of commonly used interfaces (interface types) that a user might use. Although it is always possible to analyze all sub-models such as BasicCedar.Model, retrieving the files needed for analysis is very time consuming.
When the user initiates "MakeModelBcd" in field 30, the modeller makes an object file for a model, much as a compiler makes an object file for a source file. This model object file, called a .modelBcd file, is produced so that all parameters except interface records are given values, so it is a projection of the source file for the model and all non-interface record parameters. The .modelBcd file acts as an accelerator, since it is always possible to work from the sources to derive the same result as is encoded in the .modelBcd.
The loading ability of the modeller gives the user the ability to load the object files of any valid model. This speed of loading is proportional to the size of the system being loaded and the inter-module references. As the system gets larger, it takes more time to load. However, the Cedar Binder has the ability to take the instructions and symbol table stored in each object file, merge these pieces of object, and produce an object file that contains all the information of the constituent modules while combining some tables used as runtime. This transformation resolves references from one module to another in the model, which reduces the time required to load the system and also saves space, both in the object file and when the modules are loaded. To speed loading of large systems, this feature has been preserved in the modeller. If "Bind" is initiated after "StartModel" and then "Compile" or "Begin" are initiated, an object file with instructions and symbol tables merged is produced.
The programmer may choose to produce a bound object file for a model instead of a .modelBcd file when (1) the model is very large and loading takes too long or the compression described above is effective in reducing the size of the file or (2) the object file will be input to the program that makes the boot file for the system.
The ability to replace a module in an already loaded system can provide faster turnaround for small program changes. Module replacement in the Cedar type system is possible if the following conditions are met:
(1). The existing global data of the module being replace may change in very restricted ways. Variables in the old global data must not change in position relative to other variables in the same file. New variables can only be added after the existing data. If the order changed, outstanding pointers to that data saved by other modules might be invalidated.
(2). Any procedures that were EXPORTed by the old version of the module must also be EXPORTed by the new version, since the address of these objects could have been passed to other modules, e.g., a procedure that is passed as a parameter.
(3). There are a number of architectural restrictions, such as the number of indices in certain tables, that must be obeyed.
(4). No procedures from the affected module can be executing or stopped as a breakpoint during the short period of time the replacement is occurring.
The modeller can easily provide module replacement since it loaded the modules initially and invokes the compiler on modules that have been changed. When the user initiates "Continue" in the field, the modeller attempts to hasten the compile-load-debug cycle by replacing modules in the system, if possible. Successful module replacement preserves the state of the system in which the replacement is performed.
The modeller calls the compiler through a procedural interface that returns a boolean true if rules (1) and (2) are obeyed; the modeller will also check to see that rules (3) and (4) are obeyed. If all four checks succeed, the modeller will change the runtime structures to use a new pointer to the instructions in the new module, which in effect replaces the old instructions by the new ones.
Some changes are substantial enough to violate rules (1)-(4), so after edits to a set of modules, some modules are replaceable and others are not. When this happens, the modules that are replaceable are replaced by new versions. The modules for which replacement failed are left undisturbed, with the old instructions still loaded. If desire, the user may try to debug those changes that were made to modules that were replaceable. If not, the user can initiate the "Begin" button to unload the current version and reload the system. Since no extra compilations are required by this approach, the user will always try module replacement if there is a possibility that it will succeed and the user wants to preverse the current state of the program or software system.
When the Cedar debugger examines a stopped system, e.g., at a breakpoint, the debugger can follow the procedure call stack and fine the global variables for the module in which the procedure is declared. These global variables are stored in the global frame. The modeller can provide the debugger with module-level information about the model in which this module appears, and provide file location and version information. This is particularly useful when the debugger wants to inspect the symbol table for a module, and the symbol table is stored in another file that is not on the local machine or computer disk or the user.
The programmer/user deals with the model naturally while debugging the system.
Since more than one modeller can be in use on a machine or computer, the modeller(s) call procedures in an independent runtime loader to add each model to a list of models maintained for the entire running system. When the modules of a model are loaded or unloaded, this list is updated, as appropriate. To simplify the design, the list of models is represented by the internal data structures used by the modeller to describe a model. This model has no formal parameters and no file where it is stored in text form, but it can be printed. This allows the debugger to use a simple notion of scope: a local frame is contained in the global frame of a module. This module is listed in a model, which may be part of another model that invokes it, and so on, until this top-most model is encountered. The debugger can easily enumerate the siblings in this containment tree. It can enumerate the procedures in a module, or all the other modules in this model, as appropriate. This type of enumeration occurs when the debugger tries to match the name of a module typed by the user against the set of modules that are loaded, e.g., to set the naming environment for expressions typed to the debugger.
The procedures of the modeller can be categorized into these functional groups:
1. Procedures to parse model source files and build an internal parse tree.
2. Procedures to parse source and object files to determine needed parameterization.
3. Procedures that maintain a table, called the projection table, that expresses relationships between object files and source files, as described below.
4. Procedures that maintain a table, called the file type table, that gives information about files described in models. This includes information about the parameters needed by the file, e.g., interface types, and information about its location on the file system.
5. Procedures that load modules and maintain the top-level model used by the debugger.
6. Procedures used to call the compiler, connect the modeller to the editor, and other utility procedures.
7. Procedures to maintain version maps.
The sections below discuss essential internal data structures used in these groups, illustrations of which are shown in the tables of FIGS. 18 and 19.
The model is read in from a text file and must be processed. The modeller parses the source text and builds an internal parse tree. This parse tree has leaves reserved for information that may be computed by the modeller when compiling or loading information. When a Notice operation is given to the modeller, it alters the internal data structures to refer to new versions of files. Since new models are derived from old models when Notice operations occur, the modeller must be able to write a new copy of the model it is working on.
There is one parse tree per source model file. The links between model files that are "called" by other model files are represented as pointers from one model's internal data structure to another in virtual memory.
The internal data structure represents the dependency graph used to compile modules in correct compilation order by threading pointers from one file name to another in the parse tree. three tables that record the results of computations that are too extensive to repeat. These tables serve as accelerators for the modeller and are stored as files on the local computer disk.
These tables are of three types and are maintained independently from instances of the modeller on a local computer disk.
The information in a table is like a cache for the modeller. It can be automatically reconstructed whenever it is not present, as the information is never purged. When the file containing the table becomes too large, the user simply deletes it from his local disk and the information is reconstructed.
Object Type Table: This table contains a list of objects that are referenced by models and have been analyzed as to their types. An example is shown in FIG. 18. The modeller abstracts essential properties of the objects in models and stores the information in this table. For example, a Cedar source file is listed along with the implied procedure type used by the modeller to compile and load it. The unique name of an object is the key in this table and its type is the value. The object type table also contains information that records whether a file has been edited, and if so, whether it has been saved on a remote file server.
Projection Table: This table keeps a list of entries that describe the results of running the compiler or other programs that takes a source object file and any needed parameters, such as interfaces, and produces a binary object file. An example is shown in FIG. 18. Before invoking, for example, the compiler on a source file to produce an object user-sensible name of the source object, plus the version stamp, the 48-bit hash code of all the other information. An entry is added to the projection table whenever the compiler is successfully run.
If an entry is not in the table, there may be an object file on the disk made by the compiler that predates the information in the projection table. If not, the compiler is invoked to produce the object file. In either case a new entry is added to the table for later use.
It is possible for these tables to fill up with obsolete information. Since they are just caches and can always be reconstructed from the sources, or from information in the .modelBinary objects,.
The projection table does not include the location of object files. Version maps, described below, are used for this.
Version Maps: The central file servers used by the system modeller can store more than one version of a source file in a directory. An example is shown in FIG. 19. Each version is given a version number, which ranges from 1 to 32767 and is typically less than 100. Obtaining the creation time of a source file or the 48-bit version stamp of object files from a central file server takes between 1/4 and 1 second. For directories with many versions of a file, searching for the create time or version stamp can take a few seconds per file.
Since the modeller must determine the explicit version number of the file that is referenced in the model, this slow search for large numbers of files referenced by models is prohibitively excessive. To avoid this excessive searching when it is running, the modeller uses an index between create times or version stamps and full path names that include explicit version numbers for files. Since the version numbers used by the file servers are not unique and may be reused, the modeller uses this index as a cache of hints that are checked when data in the file is actually used. If there is no entry for a file in the cache, or if it is no longer valid, the versions of a file are searched and an entry is added or updated if already present. Commonly referenced files of the software system are inserted in a version map maintained on each computer or machine.
In summary, the Object Type table speeds the analysis of files, the Projection table speeds the translation of objects into derived objects, and Version Maps are used to avoid extensive directory searches.
The modeller keeps its caches on each machine or computer. It is also desirable to include this kind of precomputed information with a stored model, since a model is often moved from one computer or machine to another, and some models are shared among many users, who refer to them in their own models by using the @-notation. An example is the model CedarInterfaces.model, which returns a large number of commonly used interfaces that a program might need. Furthermore, even with the caches, it is still quite extensive to do all the typechecking for a sizable model.
For these reasons, the modeller has the ability to create and read back compiled models. A compiled model contains
(1) a tree which represents a parsed and typechecked version of the model;
(2) object type and projection tables with entries for all the objects in the model;
(3) a version map with entries for all the objects in the model.
When the user initiates the "MakeModelBcd" button in field 30 of FIG. 20, the modeller makes this binary object for the current model, much as a compiler makes a binary file from a source file. In a .modelBcd object any parameters of the model which are not instances may be given specific argument values. This is much like the binary objects produced by the compiler, in which the interface parameters are fixed. The .modelBcd objects acts merely as an accelerator, since it is always possible to work from the sources of the model and the objects it references, to derive the same result as is encoded in the .modelBcd.
As just indicated, .modelBcd file can be produced for a model that has been analyzed by initiating the "MakeModelBcd" button. The .modelBcd file contains the same information described in the previous tables. Only information relevant to the model being is analyzed is stored. The .modelBcd contains (a) a representation of the internal parse tree that results from reading and parsing the source file for the model, (b) an object type table for source files referenced by the model, (c) a projection table describing the object files are are produced, for example, by the compiler, and (d) a version map that describes, for each source and object file in (b) and (c), a file location including a version number.
A model may refer to other models in the same way it refers to other source files. The projection table includes references to .modelBcd files for these inner models.
The information stored in the model-independent tables or present in .modelBcd files is used in four different ways: three ways when the modeller is used, and once by the release process, which is described later.
StartModel Analysis: Each application of a source file to a parameter list in the model is checked for accuracy and to see if any parameters have been defaulted. The version information (create time) following the source file name is employed to look up the parameters needed by the file in the file type table. If no entry is present, the source file must be parsed to get its parameters. The version map is used to obtain an explicit file on a file server. If there is no entry for the create time of this file in a version map, all versions of the source file on the directory listed in the model are examined to see if they have the right create time. If so, an entry for that version is added to the version map and the file is read and its type is added to the object type table. If so such version can be found by enumeration, an error is reported in field 36.
If the version of the source file is given as "!H", meaning the highest version on that directory, the directory is probed for the create time of the highest version, and that create time is used as if it were given instead of "!H".
FIG. 22 illustrates by flow diagram how a reference to "[Ivy]<Schmidt>X.Mesa" of July 25, 1982 14:03:02 is treated by the StartModel analysis.
Compilation Analysis: After the user initiates "Begin" or "Compile" in field 30, the modeller constructs object files for each source file in the model. Each source file and its parameters is looked up in the projection table. If not present, the modeller constructs the 48-bit version stamp that an object file would have if it had been compiled from the source and parameters given. The version map is used to search for an object file with this 48-bit version stamp. If not found in the version map, the modeller searches for an object file in the directory where the source file is stored. If found, an entry is added to the version map and to the projection table.
The modeller does not search for object files compiled from source files that have just been edited since it has knowledge that these have to be compiled.
If the modeller must compile a source file because it cannot find an object file previously compiled, the source file is read using the version map entry for the source and an object file produced on the local computer disk. Information about this object file is added to the model-independent tales and version maps. The object file is stored on a file server later when "StoreBack" is initiated. The compilation analysis for this is illustrated in FIG. 23.
Loader Analysis: Each object file must be read to copy the object instructions into memory. The modeller loader, as illustrated in the loading analysis of FIG. 24, looks up the 48-bit version stamp in the version map to find the explicit version of the file to read.
Since the version maps are hints, the presence of an entry for a file in a version map does not guarantee that the file is actually present on the file server and, therefore, each successful probe to the version map delays the discovery of a missing file. For example, the fact that a source file does not exist may not be discovered until the compilation phase, when the modeller tries to compile it.
When the modeller stores file type, projection, and version map information in .modelBcd files, it stores only information relevant to the model in use. When the modeller reads .modelBcd files, it takes the information from the .modelBcd and adds it to cache tables maintained on each machine or computer. When a module is compiled for the first time, this information is added to the tables manage centrally on each computer. This information can, over time, become obsolete and require large amounts of disk space, since these tables are stored in files on the local computer disk. If these files are deleted from the local disk, the modeller will reconstruct the information as it uses it.
As previously indicated,]:
(1) Checks that M and each component of M is legal: syntactically correct, type-correct, and causes no compiler errors.
(2) Ensures that all objects needed by any component of M are components of M, and that only one version of each object exists (unless multiple versions are explicitly specified).
(3) Builds the system described by M.
(4) appropriate implementor/user to correct the model.
Releases can be frequent, since performing each release imposes a low cost on the Release Master and on the environment programmers. The Release Master does not need to know any details about the packages being released, which is important when the software of the system becomes too large to be understood by any single programmer/user. The implementor/user of each package can continue to make changes until the release occurs, secure in the knowledge that the package will be verified before the release completes. Many programmers make such changes at the last minute before the release. The release process supports a high degree of parallel activity by programmers engaged in software development. ˜ [BTree ˜ @[indigo]<Int>BTree.Model!H --ReleaseAs [Indigo]<Cedar>--.Runtime ˜ @[Indigo]<Int>Runtime.Model!H --ReleaseAs[Indigo]<Cedar>--__________________________________________________________________________
The Top model is used during the development phase as a description of models that will be in the release and gives the locations of these objects while they are being developed. The Top model provides the list of moldels that will be released. Models not mentioned in the Top model will not be released.
Every model M being released must have a LET statement at the beginning that makes the components in the Top model accessible in M. Thereafter, M must use the names from Top to refer to other models. Thus, M must begin
______________________________________LET@[Indigo<Int>Top.Model!H IN [. . .RTypes: INTERFACE ˜ Runtime,. . .______________________________________
Clients of a release component, e.g., RTTypes, are not allowed to refer to its model by @-reference, since there is no way to tell whether that model is part of the release. Aside from the initial reference to Top, a release component may have @-references only to sub-components of that component.
A model M being released must also have a comment that gives its object name in the Top Model (e.g. BTree), and the working directory that has a copy of the model, e.g.,
--ReleaseName BTree
--WorkingModelOn [Indigo]<Int>BTree.Model
These comments are redundant but allow a check that Top and the component, and hence the Release Master and the implementor/user, agree about what is being released.
M must also declare the release position of each file, by appending it as a comment ater the filename in the model, e.g.,
@[Ivy]<Work>XImpl.Mesa!H--ReleaseAs [Indigo]<Cedar>XPack>--[]
A global ReleaseAs comment can define the default release position of files in the model (which may differ from the release position of the model itself). Thus if the model contains a comment,
--DefaultReleaseAs [Indigo]<Cedar>BTrees>--
then the user may omit the
--ReleaseAs [Indigo[<Cedar>BTrees>--
clauses.
The modeller must be able to analyze large collections of modules quickly, and must provide interfaces to the compiler, loader, debugger, and other programs. Described first are the basic algorithms used for evaluation and then a description of the algorithms used for releases. The cache tables used have been previously explained which gently improve performance in the normal case of incremental changes to a large software system.
In order to build a program or system, the modeller must evaluate the model for the program. As previously explained, a model is an expression written in SML notation. Evaluating an SML expression is done in three steps:
(1) The Standard β-reduction evaluation algorithm of the typed lambda calculus converts the expression into one in which all the applications are of primitive objects, namely system modules. Each such application corresponds to compilation or loading of a module. β-reduction works by simply substituting each argument for all occurrences of the corresponding parameter. SML operations such as selecting a named component of a binding are executed as part of this process. Thus, in the example,
LET Instances˜@CedarInstances.model IN Instances.Rope
evaluates to
@[Indigo]<Cedar>RopeImpl.cedar!(July 10, 1982, 17:10:24)[. . . ][. . . ]
where the arguments of RopeImpl are filled in according to the defaulting rules.
(2) Each application of a .cedar object is evaluated by the compiler, using the interface arguments computed by (1). The result is a .binary or .Bcd object. Of course, each interface argument must itself be evaluated first; i.e., the interfaces on which a module depends must be compiled before the module itself can be compiled.
(3) Finally, each application of a .Bcd or software system.
Step (1) is done when the user initiates the StartModel screen button shown in FIG. 20 or on the affected subtree whenever the current model is modified by a Notice operation. For StartModel, system system, INTEFACE B]→[[A]→[B]]
i.e., it is a function taking two interface arguments and returning, after it is compiled, another function that takes an instance of A and returns an instance of B. The modeller checks that the arguments supplied in the model have thee types, and defaults them if appropriate. SML typechecking is discussed in detail in the Article of B. W. Lampson et al, "Practical Use of a Polymorphic Applicative Language", Proceedings of the 10th Symposium on Principles of Programming Languages, Austin, Tex., January 1983.
After the entire model has been evaluated, the modeller has determined the type of each module and has checked to determine that every module obtains the arguments of the type it wants. Any syntactic or type errors discovered are reported to the user. If there are none, then whenever a value is defined in one module and used in another, the two modules agree on its type. Nothing at this point has yet been compiled or loaded.
After step (1) , the value of the model is a tree with one application for each compilation or loading operation that must be done. The compilation dependencies among the modules are expressed by the aguments: or system, each application of a source module must be evaluated by the compiler, as described in (2). During this evaluation, the compiler may find errors within the module. This step is done when the user initiates the "Compile" or "Begin" button.
After step (2), the value of the model is a tree in which each application of a source object has been replaced by the binary object that the compiler produced. To get from this tree to a runnable program or system, each binary object must be loaded, and each instance record filled in with the procedures EXPORTed from the modules that implement it. The details of how this is done are very dependent on the machine architecture and the runtime data structures of the implementing language.
After preparation of all models that are to be released, the Relase Master runs the Release Utility, Release, which makes three passes over the module being released. for correction of errors caught in this phase.
The Move phase moves the files of the release onto the release directory and makes new versions of the models that refer to files on the release directory instead of the working directory. For each model listed in the release position list, Move:
(1) reads in the model from the working directory,
(2) moves each file explicitly mentioned in the model to its release position,
(3) writes a new version of the source file for the model in the release directory.
This release version of the model is like the working version except that (a) all working directory paths are replaced by paths on the release directory, (b) a comment is added recording the working directory that contained the working version of the model, and (c) the LET statement referring to the Top model is changed to refer to the one on the release directory.
For example, the model may look like the following:
______________________________________ReleaseName BTreeModelCameFromModelOn [Indigo]<Int>Btree.ModelDefaultCameFrom [Indigo]<Int>BTrees>LET @[ivy}<Rel>ReleasePosition.Model IN [. . .RTTypes:INTERFACE ˜ @[Indigo]<Cedar>XPack>file.bed!1234CameFrom [Indigo]<Int>XPack>--,. . .______________________________________
Any references to highest version, "!H", are changed to be explicit create times as the model is written.
At the end of phase Move, the working position model is automatically converted to a release position model that defines the same variables as the working position model, but sets those variables to refer to the model stored on the release directory. A release position model might be
______________________________________Position ˜ [BTreeModel ˜ @[Indigo]<Cedar>BTree.Model!1234,RuntimeModel ˜ @[Indigo]<Cedar>Runtime,Model!]2345]______________________________________
Note that the LET switch is a deviation from explicit parameterization that allows us to change the nature of each model from being a development version to being a released version. The LET switch could be avoided if every model took a parameter that controlled whether its LET statement should refer to the working position model or the release position model. The SML language could be augmented with a type "BOOLEAN" and an IF-THEN-ELSE expression to accomplish this. Because Release has to rewrite models anyway to eliminate "!H" references, the LET switch is chosen to be accomplished automatically.
Phase Move also constructs a directed graph of models in reverse dependency order that will be used in phase Build. In this dependency graph, if Model A refers to model B, then B has an edge to A.
FIG. 22 illustrates the movement of files by this phase.
The Build phase takes the dependency graph computed during the move phase and uses it to traverse all the models in the release. For each model:
(1) All models on incoming edges must have been examined.
(2) For every source file in the model, its object file is moved to the release directory from the working directory.
(3) A.modelBed file is made for the version on the release directory.
(4) If a special comment in the model is given, a fully-bound object file is produced for the model, usually to use as a boot file.
After this is done for every model, a version map of the entire release is stored on the release directory.
FIG. 23 illustrates the movement of files by this phase.
At the conclusion of phases Check, Move and Build, Release has established that:
(1) Check: All reachable objects exist, and derived objects for all but the top object have been computed. This means the files input to the release are statically correct.
(2) Move: All objects are on the release directory. All references to files in these models are by explicit create time (for source files) or version stamps (for object files).
(3) Build: The system has been built and is ready for execution. All desired accelerators are made, i.e., .modelBcd files and a version map for the entire release.
Phase Check. In order to know the parameterization of files referenced in the model, some part of each system file must be read and parsed. Because of the large number of files involved, phase Check maintains object type and projection tables and a version map for all the files on their working directories. These tables are filled by extracting the files stored in the .modelBcd files for the models being submitted to the release. Any models without .modelBcd accelerators are read last in phase Check and the result of analyzing each file is entered into the database. The version map information about object file location(s) and projection table are used later in phase Build.
Because files can be deleted by mistake after the .modelBcd file is made and before phase Check is run, Release checks that every version of every file in the release is present on the file server by verifying the file location hints from the .modelBcd files.
Phases Move and Build. The Move and Build phases could have been combined into a single phase. Separating them encourages the view that the Build phase is not logically necessary, since any programmer can build a running system using the source models and source files that are moved to the release directory during the Move phase. The Build phase makes a runnable system once for all users and stores the object files on the release directory.
The Build phase could be done incrementally, as each model is used for the first time after a release. This would be useful when a release included models that have parameters that are unbound, which requires the user to build the model when the model is used and its parameter are given values.
The Check phase file type and projection tables and version map are used to make production of the .modelBcd files faster. The projection table is used to compute the version stamps of object files needed, and the version map is used to get the file name of the object file. This object file is then copied to the release directory. The file type entry, projection entry and new release position of source and object files are recorded in the .modelBcd being built for the released model.
The Build phase has enough information to compile sources files if no suitable object files exist. To speed up releases, it is preferred that the programmer/user make valid object files before the operation of Move and Build. If such an object file is not on the same directory as the source file, the programmer/user is notified of his error and ask to prepare one. If the Release Master ran the compiler, he would most likely compile a file that the programmer had fogotten to recompile, and this file might have compilation errors in it. The ability to automatically compile every file during a release is useful in extensive bootstraps, however. For example, a conversion to a new instruction set, where every module in the release must be compiled, is easily completed using a cross-compiler during the phase Build.
The Build phase produces the version map of the release by recording the create time or version stamp of every file stored by Release on the release directory, along with file server, directory, and version number for the file. The version maps supplied by the .modelBcd files that were submitted to the release cannot be used, since they refer to files on their development directories and not on the release directories. This released version map is distributed to every machine or computer. Although the .modelBcd files also have this information, it is convenient to have allthe version information released in one map.
FIG. 24 is an example of a single version map.
The working position model may list other nested working position models. The objects defined in the nested working position model are named by qualifying the name of the outer object. For example, if Top contained
______________________________________Top ˜ [. . .NestedSet ˜ @[Indigo]<Int>NestedWPM.Model!H -- ReleaseAs-Indigo]<Cedar>. . .______________________________________
Then, the elements of the nested working position model can be referred to using "." notation, e.g., Top.NestedSet.Element. The "ReleaseAs" clause in Top indicates the directory in which the analogous release position model is written. The same algorithm is used to translate the working model into a release model.
A model refers to objects, i.e. source files, binary (object) files or other models, by their unique names. In order to build a system from a model, however, the modeller must obtain the representations of the objects. Since objects are represented by files, the modeller must be able to deal with files. There are two aspects to this:
(1) Locating the file which represents an object, starting from the object's name.
(2) Deciding where in the file system a file should reside, and when it is no longer needed and can be deleted.
It would be desirable if an object name could simply be used as a file system name. Unfortunately, file systems do not provide the properties of uniqueness and immutability that object names and objects must have. Furthermore, most file systems require a file name to include information about the machine or computer that physically stores the file. Hence, a mapping is required from object names to the full pathnames that unambiguously locate files in the file system.
To locate a file, the modeller uses a location hint in the model. The object reference @[Ivy]<Schmidt>BTreeImpl.cedar!(Jan. 14, 1983, 14:44:09) contains such a hint, [Ivy]<Schmidt>. To find the file, the modeller looks on the file server Ivy in the directory Schmidt for a file named BTreeImpl.cedar. There may be one or more versions of this file; they are enumerated, looking for one with a creation date of Jan. 14, 1983, 14:44:09. If such a file is found, it must be the representation of this object.
The distributed environment introduces two types of delays in access to objects represented by files: (1) If the file is on a remote machine, it has to be found. (2) or computer and directory has a copy of the version desired can be very time consuming. Even when a file location hint is present and correct, it may still be necessary to determine the Version Map, discussed previously. Note that both source objects, whose unique identifiers are creation dates, and binary objects, whose unique identifiers are version stamps, appear in the version map. The full pathname includes the version number of the file, which is the number after the "!". This version number makes the file name unique in the file system so that a single reference is sufficient to obtain the file.
Thus, the modeller's strategy for minimizing the cost of referencing objects has three paths:
(1) Consult the object type table or the projection table, in the hope that the information needed about the object is recorded there. If it is, the object need not be referenced at all.
(2) Next, consult the version map. If the object is there, a single reference to the file system is usually sufficient to obtain it.
(3) If there is no entry for the object in the version map, or if there is an entry but the file it mentions does not exist, or does computer or machine and in each .modelBcd object. A .modelBcd version map has an entry for each object mentioned in the model. A machine version map has an entry for each object which has been referenced recently on that machine. In addition, commonly referenced objects of the software system are added to the machine version map as part of each release.
Since the version maps are hints, a version map entry for an object does not guarantee that the file is actually present on the file server. Therefore, each successful probe to the version map delays the discovery of a missing file. For example, the fact.
While the system modeller has been described in conjunction with specific embodiments, it is evident that alternatives, modifications and variations will be apparent to those skilled in this art in light of the foregoing description. Accordingly, it is intended to embrace all such alternatives, modifications and variations as fall within the spirit and scope of the appended claims. | https://patents.google.com/patent/US4558413 | CC-MAIN-2018-34 | refinedweb | 30,050 | 53.41 |
Dear community,
Could you point me to some documentation or explain how to incorporate a date range filter into an HCI search query.
I've got this, but need a date range in there e.g. last 24 hours.
{
"indexName": "ECMReport",
"facetRequests": [
{
"fieldName": "HCI_namespace"
}
]
}
Hedde
Hi Hedde,
In the queryString itself, you can use this syntax for specific fields of type date:
dateField:[2017-10-19 TO *]
Examples:
"dateField:2000-11" – The entire month of November, 2000.
"dateField:2000-11T13" – Likewise but for an hour of the day (1300 to before 1400, i.e. 1pm to 2pm).
"dateField:[2000-11-01 TO 2014-12-01]" – The specified date range at a day resolution.
"dateField:[2014 TO 2014-12-01]" – From the start of 2014 till the end of the first day of December.
"dateField:[* TO 2014-12-01]" – From the earliest representable time thru till the end of the day on 2014-12-01.
"datefield:[1972-05-20T17:33:18.772Z TO *]" - From a specific instant in time to now
The "[" & "]" brackets indicate inclusive searches, and you can replace them on either side with "{" or "}" for exclusive ranges.
-Ben | https://community.hitachivantara.com/thread/12398-hci-query-api-date-range-filter | CC-MAIN-2018-43 | refinedweb | 189 | 63.59 |
Details
- Type:
Bug
- Status:
Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 1.7.0
- Fix Version/s: 1.7.2, 1.6.9, 1.8-beta-1
- Component/s: None
- Labels:None
- Testcase included:
- Number of attachments :
Description
I'd like to use a default value in a closure argument, but at the moment,
it's not working, and I was wondering if the thing I'm trying is not
supported...
This is my code:
Sheet.metaClass.dump ={ Integer maxRows = Integer.MAX_VALUE -> }
Code from Tim Yates:
This works:
def max = Integer.MAX_VALUE
String.metaClass.dump = { Integer maxRows = max ->
delegate.substring( 0, delegate.length() < maxRows ? delegate.length() : maxRows )
}
assert 'hello'.dump( 2 ) == 'he'
assert 'hello'.dump() == 'hello'
but as you say, putting the Integer.MAX_VALUE in the closure definition throws the MissingPropertyException.
Activity
the example works on trunk... somehow this looks familiar... haven't we fixed that already?
I just fixed it on trunk. Builds on 1.7.x and 1.6.x have not completed yet.
but it worked here without your fix... strange
I hope you are talking about the first part of the JIRA code here. 2nd part is the workaround Tim suggested.
Anyway, I first reproduced the error and then fixed it.
Below is what should fail without my current fix (as it does on):
class Sheet{} Sheet.metaClass.dump = { Integer maxRows = Integer.MAX_VALUE -> } new Sheet().dump()
ah, sorry for the confusion, I had a bug in my test, that made it work.. lol
Fixed
I haven't looked at your fix yet. Does it help with GROOVY-3278?
OK, just looking, fix only applies to closures. Feel free to look at GROOVY-3278 if you have time.
I hardly see any overlap between the two issues. So, I guess not - my fix deals just with initial values of closure parameters and has nothing to do with annotations.
Seems to be similar to
GROOVY-1347but for closures rather than methods | http://jira.codehaus.org/browse/GROOVY-4134?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel | CC-MAIN-2015-14 | refinedweb | 324 | 71.51 |
Creating a Simple Program
Let’s produce our 1st program mistreatment the C# artificial language. The program can print a line of text during a console window. Note that we are going to be mistreatment Console Application because the project sort for the subsequent tutorials. this can be simply an outline of what you may learn within the following lessons. i’ll make a case for here the structure and syntax of a straightforward Simple C# program.
Open up Visual Studio. Go to File > New Project to open the New Project Window. You will be presented with a window asking you of the type and name of the project you want to create.
Choose Console Application as the project type and name it MyFirstProgram. A Console Application is a program that runs in command prompt(console) and has no visual or graphical interface. We will deal with this type of project because it will be easier to demonstrate the programming language features. After pressing OK, Visual Studio will create a solution file in a temporary directory. A solution is a collection of projects. The solution file with file extension .sln contains details about the projects and files associated with it and many more. For most of our tutorials, a solution will only contain 1 project. Creating a new project creates a .csproj file which contains details about the project and its associated files. In our example, our solution contains one console application project.
Since we choose Console Application as the project type, we are presented with the Code Editor.
The Code Editor is where you type your codes. Codes typed in the editor are color coded (syntax-highlighted) so it will be easier for you to recognize certain parts of your code. Color Coding is another great feature of the Visual Studio family. There are three combo boxes to the top of the code editor which allows you to easily navigate your code in the solution. The first combo box (1) allows you to select which project you want to navigate to. The second combo box (2) will list all the different components of the code and the combo box on the top right (3) will list all the members of the class, structure, or enumeration where the cursor is positioned inside. Don’t worry about the terms I used, they will be discussed in later lessons.
A .cs file named Program.cs is created and is included to the project. It will contain the codes for your program. All C# code files has .cs file extensions. You will be presented with a prewritten code to get you started, but for now, delete everything and replace it with the following code: Simple Program in C#
namespace MyFirstProgram { class Program { static void Main() { System.Console.WriteLine("Welcome to Visual C# Tutorials!"); } } }
The numbers on the left side are not part of the actual code. They are only there so it will be easier to reference which code is being discussed by simply telling the line numbers. In Visual Studio you can go to Tools > Options > Text Editor > C# and then check the Line Numbers check box to show line numbers in your Visual Studio’s code editor. Note that the line numbers in your code editor may not be aligned with the line numbers in the examples.
Structure of a C# Program
The code in Example one is that the simplest program you’ll be able to create in C#. It’s purpose is to show a message to the console screen. each language has its own basic syntax, that ar rules to follow once writing your code. Let’s attempt to justify what every line of code will.
Line one is a namespace declaration, that declares a namespace used as containers for your codes and for avoiding name collisions. Namespaces are going to be lined thoroughly in another lesson. Right now, the namespace represents the name of your project. Line 2 is an open curly brace ( { ). Curly braces define a code block. C# may be a block-structured language and every block will contain statements or a lot of valid code blocks. Note that each opening curly brace ( { ) should have a matching closing brace ( } ) at the end.Everything within the wavy braces in Line a pair of and ten is that the code block or body of the namespace.
Line 3 declares a new class. Classes square measure a subject of object-oriented programming and you may learn everything concerning it in later lessons. For now, the codes you write should be contained inside a class. You can see that it conjointly has its own combine of curly braces (Line four and 9), and everything between them is that the class’ code block.
Line five is named the Main method. a technique encapsulates a code so executes it once the strategy is named. Details in making a technique are explained in an exceedingly later lesson. the most technique is that the place to begin of the program. It implies that it’s the entry purpose of execution and everything within the most technique square measure the primary ones to execute on balance the initializations are completed. image the most technique because the exterior door of your house. you may learn additional regarding the most technique in an exceedingly later lesson. the most technique and different ways you may produce additionally includes a set of kinky braces that defines its code block and within it square measure the statements which will be dead once the strategy is named.
Statements are commands or operations. every statement should finish with a punctuation mark (;). Forgetting to feature the punctuation mark can lead to a software error. Statements ar situated within code blocks. AN example of a press release is that the following code (Line 7):
System.Console.WriteLine("Welcome to Visual C# Tutorials!");
This is the code that displays the message “Welcome to Visual C# Tutorials!”. we’d like to use the WriteLine() method and pass the string message within it. A string or string literal is a group of characters and they are enclosed in double quotes (“). A character is any letter, number, symbol, or punctuation. For now, the whole line simply means “Use the WriteLine method located in the Consoleclass which is located in the System namespace”.
More of those are explained within the forthcoming lessons.
C# ignores areas and new lines. Therefore, you’ll be able to write an equivalent program in Example one in precisely one line. however that may create your code extraordinarily laborious to scan and rectify. Also, statements will span multiple lines as long as you terminate the last line with a punctuation mark. One common error in programming is adding semicolons at every end of a line though multiple lines represent one statement. take under consideration the following example.
System.Console.WriteLine( "Welcome to Visual C# Tutorials!");
Since C# ignores white area, the on top of snipping is suitable. however the subsequent isn’t.
System.Console.WriteLine( ; "Welcome to Visual C# Tutorials!");
Notice the punctuation at the top of 1st line. this can manufacture a systax error as a result of the 2 lines of code ar thought of collectively statement and you merely add a punctuation at the top of one statement. Some statements (as we’ll see in later lessons) will have their own code blocks and you do not ought to add semicolons at the top of every block.
Always remember that C# is a case-sensitive language. That means you want to additionally bear in mind the correct casing of the codes you sort in your program. Some exceptions area unit string literals and comments that you’ll learn later. the subsequent lines won’t execute becase of wrong casing.
system.console.writeline("Welcome to Visual C# Tutorials!");
SYSTEM.CONSOLE.WRITELINE("Welcome to Visual C# Tutorials!");
sYsTem.cONsoLe.wRItelIne("Welcome to Visual C# Tutorials!");
Changing the casing of a string literal does not stop the code from running. the subsequent is completely okay and has no errors.
System.Console.WriteLine("WELCOME TO VISUAL C# TUTORIALS!");
But what is going to be displayed is exectly what you have got indicated within the string literal. additionally notice the employment of indention. Everytime you enter a brand new block, the codes within it ar indented by one level.
{
statement1;
}
This makes your code additional decipherable as a result of you’ll be able to simply confirm that code belongs to that block. though it’s ex gratia, it’s extremely counseled to use this follow. One nice feature of Visual Studio is its auto-indent feature thus you do not have to be compelled to worry concerning indention once getting into new blocks.
Saving Your Project and Solution
To save your project and solution, you can go to File > Save All or use the shortcut Ctrl+Shift+S. You can also press the
button in the toolbar.
If you merely wish to avoid wasting one file, go to File > Save (FileName) where FileName is the name of the file to be saved. you’ll use the shortcut Ctrl+S or click the
button within the toolbar.
To open a project or solution file, go to File > Open, or find the
button in the toolbar. Browse for the project of the solution file. A solution file has an extension name of .sln and a project file has an extension name of .csproj. When gap an answer file, all the coupled project to it answer are going to be opened also along with the files associated for every of the comes.
Compiling the Program
We discovered that our code must be incorporated first to Microsoft Intermediate Language before we will run it. To gather our program, go to Debug> Build Solution or simply hit F6. this can accumulate every one of the comes at interims the appropriate response. to influence one to extend, go to the appropriate response individual and right snap a venture, at that point pick Build.
Rebuild simply recompiles a solution or project. I will not need you to perpetually build the project if you’ll merely run the program as a result of capital punishment the program (as represented next) mechanically compiles the project.
You can currently realize the viable program of your project with .exe extension. to seek out this, move to the answer folder at the placement you such as after you saved the solution/project. you’ll understand here another folder for the project, and inside, understand the folder named bin, then enter the rectify folder. There you may finally understand the viable file.(If you cannot realize it in the Debug folder, attempt the Release folder).
Executing the Program
When we execute a program, Visual Studio automatically compiles our code to Intermediate Language. There are modes of executing/running a program, the Debug Mode and the Non-Debug Mode.
The Non-Debug Mode runs or executes the program disabling the debugging features of the IDE. The debugging features will be discussed in a later lesson but it allows you to step through your code and monitor the state of your application which is usefull for finding potential errors in your code. The program will be executed the same way it will be executed when it is run by the user who will use your program. By running the program in Non-Debug mode you’ll be prompted to enter any key to continue once the program reaches the tip. you’ll run in Non-Debug mode by going to Debug > begin while not Debugging in the menu bar. you’ll conjointly use the shortcut Ctrl+F5. you’ll get the subsequent output:
Welcome to Visual C# Tutorials! Press any key to continue . . .
Note that the message “Press any key to continue…” is not part of the actual output. This will only show if you run your program in Non-Debug mode. It is only there to prompt you to press any key to exit or continue the program.
The Debug Mode is easier to access and is the default for running programs in Visual Studio. This mode is used for debugging to hunt for the cause of an error in your code. You will be ready to use break points and helper tools once exceptions area unit encountered once your program is running. Therefore, i like to recommend you to use this mode after you wish to search out errors in your program throughout runtime.To run mistreatment correct Mode, you’ll be able to go to Debug > begin Debugging or merely hit F5. as an alternative, you’ll be able to click the
located at the toolbar.
Using rectify Mode, you program can show and straightaway disappear. this can be as a result of throughout rectify Mode, once the program reaches the tip of code, it’ll mechanically exit. to stop that from happening, you’ll use the System.Console.ReadKey() method as a workaround that stops the program associated asks the user for an input. (Methods are mentioned thoroughly during a later lesson.)
namespace ConsoleApplication1 { class Program { static void Main() { System.Console.WriteLine("Welcome to Visual C# Tutorials!"); System.Console.ReadKey(); } } }
Now run the program once more in correct Mode. The program can currently pause to simply accept Associate in Nursing input from you, merely hit Enter to continue or exit the program.
I would suggest to use the Non-Debug mode with great care we do not ought to add the additional Console.ReadKey() code at the top. From currently on, whenever I say run the program, i’ll be presumptuous that you simply use the Non-Debug mode unless otherwise noted. we are going to use rectify mode after we reach the subject of Exception Handling.
Importing Namespaces
Namespaces in a nutshell is a way to group code or act as a container and it can be referenced by its name.We characterized our own namespace named MyFirstProgram yet there are a large number of namespaces inside the .NET Framework Class Library. An illustration is that the System namespace that contains codes that region unit fundamental for an essential C# application. The Console class we keep an eye on region unit exploitation to print lines is truly inside the System namespace. we watch out for region unit exploitation the completely qualified name of the Console class which fuses the namespace System all through this exercise.
System.Console.WriteLine("Welcome to Visual C# Tutorials!"); System.Console.ReadKey();
This can be tedious if you may be repeatedly typewriting this over and over. luckily, we will import namespaces. we will use victimisation statements to import a namespace. Here’s the syntax:
using namespace_to_import;
Where namespace_to_import is the namespace you which to import. This instructs the whole program that you are using the contents of that namespace. So instead of using the following line of code:
System.Console.WriteLine("Hello World!");
we can simply write the following code when we import the System namespace:
Console.WriteLine("Hello World");
Using statements that imports namespaces area unit generally placed at the upmost a part of your code. Here is that the updated version of Example two that imports the System namespace.
using System; namespace MyFirstProgram { class Program { static void Main() { Console.WriteLine("Welcome to Visual C# Tutorials!"); Console.ReadKey(); } } }
You can still use the full name of a class though if there are other classes which have the same name. Namespaces will be discussed in greater detail in another lesson.
You are now familiar with the workflow of creating a simple C# program using the basic structure and syntax of the language. The next lessons will sharpen your knowledge of C# even further. | https://compitionpoint.com/simple-program-in-c-sharp/ | CC-MAIN-2021-21 | refinedweb | 2,622 | 65.42 |
Chapter 2: The NetworkX API
%load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format = 'retina'
Introduction
from IPython.display import YouTubeVideo YouTubeVideo(id='sdF0uJo2KdU', width="100%")
In this chapter, we will introduce you to the NetworkX API. This will allow you to create and manipulate graphs in your computer memory, thus giving you a language to more concretely explore graph theory ideas.
Throughout the book, we will be using different graph datasets to help us anchor ideas. In this section, we will work with a social network of seventh graders. Here, nodes are individual students, and edges represent their relationships. Edges between individuals show how often the seventh graders indicated other seventh graders as their favourite.
The data are taken from the Konect graph data repository
Data Model
In NetworkX, graph data are stored in a dictionary-like fashion.
They are placed under a
Graph object,
canonically instantiated with the variable
G as follows:
G = nx.Graph()
Of course, you are free to name the graph anything you want!
Nodes are part of the attribute
G.nodes.
There, the node data are housed in a dictionary-like container,
where the key is the node itself
and the values are a dictionary of attributes.
Node data are accessible using syntax that looks like:
G.nodes[node1]
Edges are part of the attribute
G.edges,
which is also stored in a dictionary-like container.
Edge data are accessible using syntax that looks like:
G.edges[node1, node2]
Load Data
Let's load some real network data to get a feel for the NetworkX API. This dataset comes from a study of 7th grade students.
This directed network contains proximity ratings between students from 29 seventh grade students from a school in Victoria. Among other questions the students were asked to nominate their preferred classmates for three different activities. A node represents a student. An edge between two nodes shows that the left student picked the right student as his or her answer. The edge weights are between 1 and 3 and show how often the left student chose the right student as his/her favourite.
In the original dataset, students were from an all-boys school. However, I have modified the dataset to instead be a mixed-gender school.
import networkx as nx from datetime import datetime import matplotlib.pyplot as plt import numpy as np import warnings from nams import load_data as cf warnings.filterwarnings('ignore')
G = cf.load_seventh_grader_network()
Understanding a graph's basic statistics
When you get graph data, one of the first things you'll want to do is to check its basic graph statistics: the number of nodes and the number of edges that are represented in the graph. This is a basic sanity-check on your data that you don't want to skip out on.
Querying graph type
The first thing you need to know is the
type of the graph:
type(G)
networkx.classes.digraph.DiGraph
Because the graph is a
DiGraph,
this tells us that the graph is a directed one.
If it were undirected, the type would change:
H = nx.Graph() type(H)
networkx.classes.graph.Graph
Querying node information
Let's now query for the nodeset:
list(G.nodes())[0:5]
[1, 2, 3, 4, 5]
G.nodes() returns a "view" on the nodes.
We can't actually slice into the view and grab out a sub-selection,
but we can at least see what nodes are present.
For brevity, we have sliced into
G.nodes() passed into a
list() constructor,
so that we don't pollute the output.
Because a
NodeView is iterable, though,
we can query it for its length:
len(G.nodes())
29
If our nodes have metadata attached to them,
we can view the metadata at the same time
by passing in
data=True:
list(G.nodes(data=True))[0:5]
[(1, {'gender': 'male'}), (2, {'gender': 'male'}), (3, {'gender': 'male'}), (4, {'gender': 'male'}), (5, {'gender': 'male'})]
G.nodes(data=True) returns a
NodeDataView,
which you can see is dictionary-like.
Additionally, we can select out individual nodes:
G.nodes[1]
{'gender': 'male'}
Now, because a
NodeDataView is dictionary-like,
looping over
G.nodes(data=True)
is very much like looping over key-value pairs of a dictionary.
As such, we can write things like:
for n, d in G.nodes(data=True): # n is the node # d is the metadata dictionary ...
This is analogous to how we would loop over a dictionary:
for k, v in dictionary.items(): # do stuff in the loop
Naturally, this leads us to our first exercise.
Exercise: Summarizing node metadata
Can you count how many males and females are represented in the graph?
from nams.solutions.intro import node_metadata #### REPLACE THE NEXT LINE WITH YOUR ANSWER mf_counts = node_metadata(G)
Test your implementation by checking it against the
test_answer function below.
from typing import Dict def test_answer(mf_counts: Dict): assert mf_counts['female'] == 17 assert mf_counts['male'] == 12 test_answer(mf_counts)
With this dictionary-like syntax, we can query back the metadata that's associated with any node.
Querying edge information
Now that you've learned how to query for node information, let's now see how to query for all of the edges in the graph:
list(G.edges())[0:5]
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)]
Similar to the
NodeView,
G.edges() returns an
EdgeView that is also iterable.
As with above, we have abbreviated the output inside a sliced list
to keep things readable.
Because
G.edges() is iterable, we can get its length to see the number of edges
that are present in a graph.
len(G.edges())
376
Likewise, we can also query for all of the edge's metadata:
list(G.edges(data=True))[0:5]
[(1, 2, {'count': 1}), (1, 3, {'count': 1}), (1, 4, {'count': 2}), (1, 5, {'count': 2}), (1, 6, {'count': 3})]
Additionally, it is possible for us to select out individual edges, as long as they exist in the graph:
G.edges[15, 10]
{'count': 2}
This yields the metadata dictionary for that edge.
If the edge does not exist, then we get an error:
>>> G.edges[15, 16]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-21-ce014cab875a> in <module> ----> 1 G.edges[15, 16] ~/anaconda/envs/nams/lib/python3.7/site-packages/networkx/classes/reportviews.py in __getitem__(self, e) 928 def __getitem__(self, e): 929 u, v = e --> 930 return self._adjdict[u][v] 931 932 # EdgeDataView methods KeyError: 16
As with the
NodeDataView, the
EdgeDataView is dictionary-like,
with the difference being that the keys are 2-tuple-like
instead of being single hashable objects.
Thus, we can write syntax like the following to loop over the edgelist:
for n1, n2, d in G.edges(data=True): # n1, n2 are the nodes # d is the metadata dictionary ...
Naturally, this leads us to our next exercise.
Exercise: Summarizing edge metadata
Can you write code to verify that the maximum times any student rated another student as their favourite is 3 times?
from nams.solutions.intro import edge_metadata #### REPLACE THE NEXT LINE WITH YOUR ANSWER maxcount = edge_metadata(G)
Likewise, you can test your answer using the test function below:
def test_maxcount(maxcount): assert maxcount == 3 test_maxcount(maxcount)
Manipulating the graph
Great stuff! You now know how to query a graph for:
- its node set, optionally including metadata
- individual node metadata
- its edge set, optionally including metadata, and
- individual edges' metadata
Now, let's learn how to manipulate the graph. Specifically, we'll learn how to add nodes and edges to a graph.
Adding Nodes
The NetworkX graph API lets you add a node easily:
G.add_node(node, node_data1=some_value, node_data2=some_value)
Adding Edges
It also allows you to add an edge easily:
G.add_edge(node1, node2, edge_data1=some_value, edge_data2=some_value)
Metadata by Keyword Arguments
In both cases, the keyword arguments that are passed into
.add_node()
are automatically collected into the metadata dictionary.
Knowing this gives you enough knowledge to tackle the next exercise.
Exercise: adding students to the graph
We found out that there are two students that we left out of the network, student no. 30 and 31. They are one male (30) and one female (31), and they are a pair that just love hanging out with one another and with individual 7 (i.e.
count=3), in both directions per pair. Add this information to the graph.
from nams.solutions.intro import adding_students #### REPLACE THE NEXT LINE WITH YOUR ANSWER G = adding_students(G)
You can verify that the graph has been correctly created by executing the test function below.
def test_graph_integrity(G): assert 30 in G.nodes() assert 31 in G.nodes() assert G.nodes[30]['gender'] == 'male' assert G.nodes[31]['gender'] == 'female' assert G.has_edge(30, 31) assert G.has_edge(30, 7) assert G.has_edge(31, 7) assert G.edges[30, 7]['count'] == 3 assert G.edges[7, 30]['count'] == 3 assert G.edges[31, 7]['count'] == 3 assert G.edges[7, 31]['count'] == 3 assert G.edges[30, 31]['count'] == 3 assert G.edges[31, 30]['count'] == 3 print('All tests passed.') test_graph_integrity(G)
All tests passed.
Coding Patterns
These are some recommended coding patterns when doing network analysis using NetworkX, which stem from my personal experience with the package.
Iterating using List Comprehensions
I would recommend that you use the following for compactness:
[d['attr'] for n, d in G.nodes(data=True)]
And if the node is unimportant, you can do:
[d['attr'] for _, d in G.nodes(data=True)]
Iterating over Edges using List Comprehensions
A similar pattern can be used for edges:
[n2 for n1, n2, d in G.edges(data=True)]
or
[n2 for _, n2, d in G.edges(data=True)]
If the graph you are constructing is a directed graph, with a "source" and "sink" available, then I would recommend the following naming of variables instead:
[(sc, sk) for sc, sk, d in G.edges(data=True)]
or
[d['attr'] for sc, sk, d in G.edges(data=True)]
Further Exercises
Here's some further exercises that you can use to get some practice.
Exercise: Unrequited Friendships
Try figuring out which students have "unrequited" friendships, that is, they have rated another student as their favourite at least once, but that other student has not rated them as their favourite at least once.
Hint: the goal here is to get a list of edges for which the reverse edge is not present.
Hint: You may need the class method
G.has_edge(n1, n2). This returns whether a graph has an edge between the nodes
n1 and
n2.
from nams.solutions.intro import unrequitted_friendships_v1 #### REPLACE THE NEXT LINE WITH YOUR ANSWER unrequitted_friendships = unrequitted_friendships_v1(G) assert len(unrequitted_friendships) == 124
In a previous session at ODSC East 2018, a few other class participants provided the following solutions, which you can take a look at by uncommenting the following cells.
from nams.solutions.intro import unrequitted_friendships_v2 # unrequitted_friendships_v2??
from nams.solutions.intro import unrequitted_friendships_v3 # unrequitted_friendships_v3??
Solution Answers
Here are the answers to the exercises above.
import nams.solutions.intro as solutions import inspect print(inspect.getsource(solutions))
""" Solutions to Intro Chapter. """ def node_metadata(G): """Counts of students of each gender.""" from collections import Counter mf_counts = Counter([d["gender"] for n, d in G.nodes(data=True)]) return mf_counts def edge_metadata(G): """Maximum number of times that a student rated another student.""" counts = [d["count"] for n1, n2, d in G.edges(data=True)] maxcount = max(counts) return maxcount def adding_students(G): """How to nodes and edges to a graph.""" G = G.copy() G.add_node(30, gender="male") G.add_node(31, gender="female") G.add_edge(30, 31, count=3) G.add_edge(31, 30, count=3) # reverse is optional in undirected network G.add_edge(30, 7, count=3) # but this network is directed G.add_edge(7, 30, count=3) G.add_edge(31, 7, count=3) G.add_edge(7, 31, count=3) return G def unrequitted_friendships_v1(G): """Answer to unrequitted friendships problem.""" unrequitted_friendships = [] for n1, n2 in G.edges(): if not G.has_edge(n2, n1): unrequitted_friendships.append((n1, n2)) return unrequitted_friendships def unrequitted_friendships_v2(G): """Alternative answer to unrequitted friendships problem. By @schwanne.""" return len([(n1, n2) for n1, n2 in G.edges() if not G.has_edge(n2, n1)]) def unrequitted_friendships_v3(G): """Alternative answer to unrequitted friendships problem. By @end0.""" links = ((n1, n2) for n1, n2, d in G.edges(data=True)) reverse_links = ((n2, n1) for n1, n2, d in G.edges(data=True)) return len(list(set(links) - set(reverse_links))) | https://ericmjl.github.io/Network-Analysis-Made-Simple/01-introduction/02-networkx-intro/ | CC-MAIN-2022-33 | refinedweb | 2,086 | 58.58 |
of course, half the problem is not knowing how to mathematically solve the initial problem in the first place =)
Moderators: SecretSquirrel, just brew it!
MorgZ wrote:wats the quickest java implementation?
Im tempted to give it a go since im pretty nifty at speedy algorithsm
blitzy wrote:I'm glad my programming classes are in object pascal at the moment... that C++ code looks like it would make my brain melt
of course, half the problem is not knowing how to mathematically solve the initial problem in the first place =)
just brew it! wrote:My family probably thought I was on drugs or something a couple of nights ago during dinner -- I was trying to work through potential algorithms in my head, and must've seemed like I was on another planet.
mac_h8r1 wrote:Yahoolian, 928131635 is the value I get when I run your program for 55.75. Any thoughts?
JBI, Glad to keep you on your toes!
So, considering that this was one problem of 9, who thinks that, working with two others, they could win a competition given 4.5 hours?
This was not the most difficult, btw
. I posted this one 'cause it was the only one I worked on that didn't get accepted. There may be another that I post, as I'm COMPLETELY in the dark regarding that one.. I posted this one 'cause it was the only one I worked on that didn't get accepted. There may be another that I post, as I'm COMPLETELY in the dark regarding that one.
mac_h8r1 wrote:Yahoolian, 928131635 is the value I get when I run your program for 55.75. Any thoughts?
Yahoolian wrote:That would explain it. I'd doubt that Java is faster than C++/C, because it does bounds checking on all array lookups.
MorgZ wrote:wats the quickest java implementation?
Im tempted to give it a go since im pretty nifty at speedy algorithsm
But in an iterative implementation, it probably wouldn't be too hard to convince the JVM that array bounds checks are unnecessary.
Assuming, of course, that your JVM contains a just-in-time compiler.
Did you just copy-paste his code, or could it be a transcription error?
int cents = (int)Double.parseDouble( s ) * 100;
int cents = (int)(Double.parseDouble( s ) * 100);
JustBrewIt wrote:Seriously... if you actually want to get a job programming, C++, Java, or even specialized (but "real world") languages like Transact-SQL are more marketable skills than Object Pascal (which is used commercially to some extent, but not much). Pascal is great for teaching general algorithm and data structure concepts though; that's why it is used a lot in programming classes.
blitzy wrote:anyone care to show how the program works through pseudocode? It's quite an interesting problem
This algorithim recursively calculates the number of unique ways to
make change for a given amount of money, using coins of specified
denominations. Inputs are the list of denominations to be used, and
the value to make change for. All values are in cents.
If list of denominations to use is empty, then
the result is 0.
Else if amount to make change for is 0, then
the result is 1.
Else if we've already calculated a value for this list of denominations and
amount of money, then
the result is the value calculated previously (retrieve from 2D
array indexed by the largest denomination of coin currently in the
list, and amount we're making change for).
Else if the largest denomination in the list is less than or equal to
the amount we're making change for, then
subtract the largest denomination from the amount we're
making change for, and recursively calculate how many ways we can
make change for the remaining amount, using the same list of denominations.
Also recursively calculate the number of ways we can make change for the
total amount, using only denominations smaller than the largest one.
The sum of these two values is the result.
Else
recursively try again using the total amount, but only considering denominations
smaller than the largest one currently in the list.
If we calculated a new value, save it in a 2D array indexed by the largest
denomination in the list of coins, and the amount we're making change for.
if (cache[start][target] != 0)
return cache[start][target];
import java.io.*;
import java.util.*;
class Money{
public static final int MAX_CENTS = 30000;
final static int value[] = { 0, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000 };
static long cache[][] = new long[ value.length ][ MAX_CENTS + 1 ];
static final String filePath = "D:\\Money\\src\\";
public static void main ( final String []args)
{
long beginTime = System.currentTimeMillis();
try {
BufferedReader file = new BufferedReader (new FileReader (filePath + "dollars.txt") );
String s = file.readLine();
while (s != null)
{
int cents = (int)(Double.parseDouble( s ) * 100);
System.out.println( s + "\t" + maxWaysToMake( cents ) );
s = file.readLine();
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println( "Elapsed milliseconds: " + ( System.currentTimeMillis() - beginTime ) );
}
public static long maxWaysToMake( final int cents )
{
int start = value.length - 1;
while ( value[start] > cents )
start--;
return maxWaysToMake( start, cents );
}
public static long maxWaysToMake( int start, final int cents)
{
// System.out.println( "\ncall: " + ++call + "\nstart: " + start + "\ntarget: " + target);
// if value already computed, return previously computed value
// doing this first results in a huge speed up
if (cache[start][cents] != 0)
return cache[start][cents];
// check for trivial terminal conditions
else if (start == 0)
return 0;
else if (cents == 0)
return 1;
else if (value[start] <= cents)
cache[start][cents] = maxWaysToMake(start, cents - value[start]);
cache[start][cents] += maxWaysToMake(start - 1, cents);
return cache[start][cents];
}
}
Yahoolian wrote:Oh yeah, I forgot to add that I moved the
if (cache[start][target] != 0)
return cache[start][target];
lines to the front of the function, that makes it go from 16 milliseconds to 0 on my computer( AXP 2500+ @ 200 * 10.5 ).
Interesting... I would not have expected that. The only other two tests ahead of it were simple tests for values being equal to 0, which should be nearly instantaneous in the grand scheme of things.
I suspect that this may be a peculiarity of the Java compiler, or within the margin of error of the timing routine used.
Yahoolian wrote:Well for the input of 55.75 the function is called 4939 times, and 1348 times when the value is cached, I guess those two less comparisions and one less array lookup add up quite a bit. | https://techreport.com/forums/viewtopic.php?f=20&t=17547&p=216110 | CC-MAIN-2017-39 | refinedweb | 1,088 | 62.38 |
Operating System
Services for UNIX 3.0 Technical Note
Abstract
This paper describes an approach for including UNIX applications under Interix as components in the Microsoft® Component Object Model (COM). It also describes a simple DLL that encapsulates a UNIX application and a Microsoft Visual Basic® client that uses that component. Also covered is how the interface is extended to allow an Excel spreadsheet to use a UNIX component.
Encapsulating UNIX Applications as COM Components Requirements The Basics Building the TIDEWRAP.DLL Building the Visual Basic Client Running the Excel Spreadsheet Future Directions
The Component Object Model is a binary-level specification that allows applications to be built using interchangeable components. Since the specification is binary, it's language-independent components can be written in C++, Java, C, or the KornShell. Client applications that make use of COM are largely Win32-based (although there's nothing in COM itself that restricts it to a Windows environment). Applications that use COM to bind components together can upgrade or customize those components dynamically. For more information about COM, see the books listed at the end of this paper.
The UNIX application used as an example is tide v1.6.2, an open source program that calculates tide tables based on a given longitude and latitude. It can write these tables to standard output or display them in an X window. This paper describes a method for encapsulating tide in a Win32 DLL (that is, as a COM object), demonstrates its inclusion in a Visual Basic client, and then extends the interface to allow tide to be installed as a component for an Excel spreadsheet.
The principles here can be used for any well-behaved UNIX system application.
The tide application consists of 13 source files and over 7,000 lines of code. (Version 2 is considerably larger.) It was ported to Interix by changing some of the paths in the files tide.c and xtide.c.
To build and run the example software, you will need:
A Microsoft® Windows NT®– or Windows® 2000–based or Windows XP system that has Services for UNIX 3.0 installed.
An Interix Software Development Kit to build the tide application.
Microsoft(r Visual C/C++ to build the DLL. The example code here was built with version 5.0 with the latest Microsoft service pack for MSVC 5.0; the ATL libraries are those of version 5.0 and 6.0.
Visual Basic® 5.0 or 6.0 to build the Visual Basic client.
Excel 97 to demonstrate the inclusion of the data in an Excel spreadsheet (Office 97 or later).
Note: To follow the examples, you should already know something about creating DLLs with the Active Template Library (ATL) and about packaging COM objects. The example client and the DLL are not tutorial programs. This is a demonstration of the COM principle.
The tide application is the command-line version of xtide; tide writes to standard output rather than opening an X window. We define a COM interface to pass this information. The encapsulating DLL is written to invoke the Interix tide application to start an Interix process.
The architecture of the completed system is shown below.
The client makes a call to tidewrap.dll. The DLL invokes POSIX.EXE (and thereby the Interix subsystem) to run tide; the DLL captures the output and passes it back to VBTIDE.EXE. The DLL does not have exclusive use of the application; it could be invoked by another Interix user (logged in over telnet, perhaps) while it's being called by VBTIDE.EXE.
To build a DLL that wraps a UNIX application, you need to think like a UNIX programmer and like a COM programmer. The UNIX programmer has to think about getting the command to produce the correct output; the COM programmer has to think about capturing that output. The difficult part is to get the POSIX.EXE command line correct.
When you unpack the tar file containing the COM example, it un-packs into two directories:
tidewrap
The code that defines the actual COM object, the tidewrap.dll dynamic link library. This directory also contains tides.xls, the Excel spreadsheet that uses the component, and the Visual Basic files for the VB client, VBTIDE.EXE.
tide
The code for the tide application, version 1.6.2.
Building the tidewrap.dll library is the process of encapsulating the application. In this example, we've followed these steps:
Build the Interix application, tide. In this case, tide is a well-behaved UNIX system application that runs from the command line and writes its output to standard out.
Define the COM interface (ITideTable in this case).
Implement the interface in the DLL. The basic idea is to invoke POSIX.EXE to run the Interix application, capture the standard output, and pass that data.
To do this, you need to get the application command line correct for POSIX.EXE. The developer needs to be careful if there is command-line quoting involved.
Finally, you build the DLL.
This DLL depends on the ATL library. If you move the DLL to a system that does not have ATL installed, you'll need to copy the ATL run-time library to that system.
The version of tide used for this project was 1.6.2. Alternate harmonics files are available from.
To build tide, follow these steps:
Run the xmkmf command.
Enter the command make depend. (If the Makefile is not correctly processed by the makedepend utility, check to make sure you are working on a local NTFS drive.)
Type the command make
Only a few small modifications were made to the tide source to compile on Interix: the macro _ALL_SOURCE was defined in the Imakefile to provide access to additional APIs and macros in <math.h>, and a minor change was made to everythi.h and tide.c to support the multiple-rooted file system on Interix
At this point, you may want to experiment with the tide command. It supports a large number of options, but the only ones used here are
–nowarn
Disable the warning text that both tide and xtide print.
-list
Display a list of locations known to the program (and found in the harmonics file).
-location location
Display tides for the specified location. The location must be in the harmonics file.
To test that the tide program is working correctly, you can give the command:
$ tide –nowarn -list
You should see 1,700 or so lines of output like this:
Morro Bay, California
Baltimore (Chesapeake Bay), Maryland
Seattle, Washington
The xtide/tide programs can be built to look for the harmonics file in a specific location, but this requires source code changes. The easier solution is to use .tiderc and .xtiderc files in your home directory to specify the default location and the –nowarn option. A sample ~/.tiderc file might be:
-nowarn
-hfile /C/users/bob/src/InterixCOM/xtide-1.6.2/harmonics
If you have an X server, you may want to run the graphical version, even though it is not used in the DLL:
$ xtide –graph –location "San Francisco, Pier 22 , California
The file tidewrap.idl defines the interface ITideTable. The actual implementation of the interface (the class CTideTable) is in the file TideTable.cpp; the CTideTable class is declared in TideTable.h. The actual file was created by the MSVC ATL wizard.
Since we wanted to make the COM object useable from scripting applications like VBScript and JavaScript, the interface needs to support ActiveX automation; that is, it makes use of IDispatch::Invoke as well as its own custom interface.
The actual IDL file is straightforward.
// tidewrap.idl : IDL source for tidewrap.dll
//
// This file will be processed by the MIDL tool to
// produce the type library (tidewrap.tlb) and marshalling code.
import i.oaidl.idlll;
import i.ocidl.idlll;
[
object,
uuid(22A6AA3E-7F2A-11D2-8DB3-006097ED27DA),
dual,
helpstring(i-ITideTable Interfacels),
pointer_default(unique)
]
interface ITideTable : IDispatch
{
[id(1), helpstring(iimethod ListLocationsle)] HRESULT ListLocations([in]
BSTR partial, [out, retval] VARIANT *locations);
[id(2), helpstring(ismethod GetPrintableTableld)] HRESULT
GetPrintableTable([in] BSTR location, [out, retval] VARIANT *tidetable);
};
[
uuid(22A6AA31-7F2A-11D2-8DB3-006097ED27DA),
version(1.0),
helpstring(i-tidewrap 1.0 Type Librarylp)
]
library TIDEWRAPLib
{
importlib(irstdole32.tlbla);
importlib(irstdole2.tlbll);
[
uuid(22A6AA3F-7F2A-11D2-8DB3-006097ED27DA),
helpstring(i-TideTable Classlh)
]
coclass TideTable
{
[default] interface ITideTable;
};
};
To register the interface (as embodied in the tidewrap.dll library), the nmake file calls the utility regsvr32.
The DLL contains code to assemble the command line to invoke POSIX.EXE correctly. The command line is passed to the Win32 CreateProcess() API; Win32 defines its own behaviors for command- line arguments, and you need to understand those behaviors in order to construct the arguments correctly. POSIX.EXE parses its command line and uses everything after the /c option to start a single Interix application. If the single application is a shell, then one could incorporate a single shell command (including such constructs as pipelines, do/done, etc.) using the shell's –c option.
The important work is done in the implementation of the ItideTable interface. (Remember, the interface specification is generic, but the Interix implementation must handle our case.)
The bulk of the work is done in DoInterixCmd() in the TideTable.cpp file. It invokes an Interix command, captures the command's standard output in a vector, sizes the vector, and then creates an array of BSTRs (Basic strings); the array is placed in a VARIANT and passed back. Eventually, the routine returns the exit status of POSIX.EXE. (This is the easiest exit status to capture; it's also the least useful.)
Handles for both stdin and stderr for the POSIX.EXE command line are created pointing to the null device, using CreateFile(). In this case, we used AtlReportError() to capture any errors or exceptions, since it works nicely with Visual Basic and Visual Basic for Applications.
Standard output is created as an anonymous named pipe using CreatePipe(). One end of the pipe, hstdout, is for the Interix process, and the other end, houtput, is for the object to read data.
The important things to note here:
The command in this implementation cannot take input; standard input is assigned the NUL (/dev/null) handle.
Line endings are removed from the output. This is because Interix processes use a line feed character as an end-of-line marker while Windows processes use a carriage return-line feed pair. Removing line endings from all output simplifies the design of the client.
In fact, the output could have been handled as a SAFEARRAY of BSTRs; the array need not have been returned in a VARIANT.
The only curious part about the command line passed to POSIX.EXE is that format of the command line is Win32 up to the name of the program being invoked, but the arguments to the Interix command are in the Interix format. For example, from the DOS command line, you might enter:
C:\WINNT\POSIX.EXE C:\Interix\bin\ksh -c tide -nowarn –list
It's a very good idea to open a CMD.EXE console window and experiment in order to get the command line correct. You might even start in an Interix shell window to get the shell command right; then switch to a CMD.EXE command to get that shell command correctly embedded in an invocation of POSIX.EXE; then move that POSIX.EXE command line into the DLL source code. For example, to search the list for locations that shouldn't be used:
Ksh$ tide –nowarn –list | grep "Don't Use"
Once this line accomplishes what it should, you can work with POSIX.EXE, testing the quoting necessary there:
C:\> POSIX.EXE /C ksh –c 'tide –nowarn –list | grep "Don\'t"'
This is the command line you'll eventually use (adding more \ characters because it's now a C string):
Fullcmd = "POSIX.EXE /C ksh –c 'tide –nowarn –list |grep \"Don\\'t
Use\"'"
The Fullcmd string can be used as the argument to the Win32 CreateProcess() call, as in DoInterixCmd(). The command shouldn't be made in a system() call. The system() call implicitly passes the argument to a shell, but this command line will not necessarily be parsed by the shell.
The command line submitted to POSIX.EXE need not use a shell to parse its contents. For example, the command used in ITideTable::GetPrintableTable() doesn't use a shell at all; it asks POSIX.EXE to invoke the tide command directly. The command used in ITideTable::ListLocations() does use a shell because it invokes grep in a pipeline.
The client code is encapsulated in the files VBTIDE.vbp, VBTIDE.vbw, and Form1.frm.
The client itself is simple. It consists of a single form (see illustration, next page). You can enter any regular expression in the first field; the list displayed in the listbox will be filled with the locations that match. Before you can build the client, you'll need to add a reference to the type library:
Start Visual Basic.
Select VBTIDE.
Select Project | References… in order to ensure that the project references include the registered tidewrap.dll file.
Select the corresponding type library (in this case, the TideTable 1.0 Type Library).
Before running the client, you need to ensure that the tide command is in your Windows path. If you've typed make install for tide then tide is installed in /usr/X11R5/bin. In a CMD.EXE window, you can type:
path=%path%;C:\SFU\usr\X11R5\bin;C:\SFU\bin
(You can simplify this by installing tide in C:\SFU\bin.)
The actual code of the client is quite straightforward.
In the DoSearch_Click() subroutine, the LocationArray is declared as type VARIANT. The Itf variable is the connection to the COM object. After calling ListLocations, the For loop fills the LocationArray. As usual with Visual Basic and COM objects, the function in the DLL is simply a property of the Itf variable.
(Error handling has been deleted for space reasons.)
Option Explicit
Private Itf As TIDEWRAPLib.TideTable
Private Sub DoSearch_Click()
Dim LocationArray As Variant
Dim i As Integer
Set Itf = New TIDEWRAPLib.TideTable
On Error GoTo except
Locations.Clear
LocationArray = Itf.ListLocations(SearchString.Text)
For i = LBound(LocationArray) To UBound(LocationArray)
Locations.AddItem LocationArray(i).
TideList.Text = i.l.
Exit Sub
End Sub
The GetTides_Click() subroutine is nearly identical, except that it calls the GetPrintableTable property and fills the TideList.Text.
The supplied spreadsheet tides.xls will make use of the TideTable library. Follow these steps:
Ensure that the tide program is in your Windows path, as already demonstrated.
Run the spreadsheet.
In cell A1, fill in a location; then activate the COM component macro with a CTRL-T.
If you look at the Visual Basic for Applications code provided, you'll see it's similar to the Visual Basic code. The difference is in the use of the data. The Excel macro includes a PlotTides() function which puts the data into spreadsheet cells and then builds a graph from those cells: There are also additional calculations for current.
Microsoft intends to provide additional COM programming support in future releases of the Interix Professional Software Development Kit. These features will be added over time. Among other planned features, the SDK will support:
Return exit status of the Interix process.
Handling of standard input and standard error as well as standard output. (In this version, they're simply connected to /dev/null.)
RPC as an integration strategy for distributed COM.
Monolithic threads-based communication (as though Win32 applications could have Interix-enabled threads).
Recommended Reading
Essential COM, Don Box, Addison-Wesley, 1998. ISBN 0-201-63446-5.
Inside COM, Dale Rogerson, Microsoft Press, 1997. ISBN 1-57231-349-8.
Beginning ATL COM Programming, Grimes and Stockton, Templeman and Reilly, Wrox Press, 1998. ISBN 1-867000-11-1.
Active Template Library: A Developer's Guide, Tom Armstrong, M&T Books, 1998. ISBN 1-55851-580-1. | http://technet.microsoft.com/en-us/library/bb463196.aspx | crawl-002 | refinedweb | 2,660 | 57.67 |
This aim of this program to replace a particular word with asterisks in the string by using the c++ programming code. The essential function of vector and string class essay a key role to achieve the prospective results. The algorithm is as follows;
START Step-1: Input string Step-2 Split the string into words and store in array list Step-3: Iterate the loop till the length and put the asterisk into a variable Step-4: Traverse the array foreah loop and compare the string with the replaced word Step-5: Print END
Now, the following code is carved out based on the algorithm. Here, the strtok() method of string split the string and returns the array list type of vector class.
#include <cstring> #include <iostream> #include <vector> #include <string.h> //method for spliting string std::vector<std::string> split(std::string str,std::string sep){ char* cstr=const_cast<char*>(str.c_str()); char* current; std::vector<std::string> arr; current=strtok(cstr,sep.c_str()); while(current!=NULL){ arr.push_back(current); current=strtok(NULL,sep.c_str()); } return arr; } int main(){ std::vector<std::string> word_list; std::cout<<"string before replace::"<<"Hello ajay yadav ! you ajay you are star"<<std::endl; std::cout<<"word to be replaced::"<<"ajay"<<std::endl; word_list=split("Hello ajay yadav ! you ajay you are star"," "); std::string result = ""; // Creating the censor which is an asterisks // "*" text of the length of censor word std::string stars = ""; std::string word = "ajay"; for (int i = 0; i < word.length(); i++) stars += '*'; // Iterating through our list // of extracted words int index = 0; for (std::string i : word_list){ if (i.compare(word) == 0) // changing the censored word to // created asterisks censor word_list[index] = stars; index++; } // join the words for (std::string i : word_list){ result += i + ' '; } std::cout<<"output::"<<result; return 0; } }
As seen in the above code, all string operation code is bundled into the retrieveChar() method, later on, which call is passed to program main() execution.
String before replace::Hello ajay yadav ! you ajay you are star Word to be replaced::ajay Output::Hello **** yadav ! you **** you are star | https://www.tutorialspoint.com/replacing-words-with-asterisks-in-cplusplus | CC-MAIN-2021-31 | refinedweb | 349 | 60.55 |
30. Re: Spamassassin Junkmail and Notjunkmail Learning in Mountain Lionpterobyte Dec 10, 2012 2:45 AM in response to bdemore
That would be the userid not the name. In any case you don't need to worry about this. Just make sure you have the accounts named junkmail and notjunkmail and feed them with spam and ham. Both learn_junk_mail and spamtrainer will find the mailbox and the id and train from those mailboxes.
31. Re: Spamassassin Junkmail and Notjunkmail Learning in Mountain LionRobb Allan May 16, 2013 7:55 AM in response to bdemore
I believe the original settings parameter name is incorrect. Try:
sudo serveradmin settings mail | grep junk
and you will see the following:
mail:postfix:junk_mail_userid = "junkmail"
mail:postfix:not_junk_mail_userid = "notjunkmail"
mail:imap:junk_mail_userid = ""
mail:imap:not_junk_mail_userid = ""
If the "mail:postfix:..." settings are blank, set them to junkmail and notjunkmail.
32. Re: Spamassassin Junkmail and Notjunkmail Learning in Mountain LionArmand Welsh Oct 21, 2013 10:51 PM in response to pterobyte
I am still completely stumped. I create two public folder in dovcot, junkmail and notjunkmail. I cannot figure out how to get spamtrainer to find the junkmail and notjunkmail imap folders when scanning/learining. it always looks for (and fails to find) GUID of the junkmail and notjunkmail users.
from what I am reading, the point of this is to not have to create these accounts, but to just create a couple public folders, or to create standard folders on all user accounts.. but this spamtrainer doesn't find them what the heck are the command line arguments to use the public folders junkmail and notjunkmail.
33. Re: Spamassassin Junkmail and Notjunkmail Learning in Mountain LionUptimeJeff Oct 22, 2013 1:26 PM in response to Robb Allan
Did you try the options for top-level (-t) ?
I'm not 100% sure if the top level function works with a public folder namespace.
You can always read directly with something like
You'll want to do something like - this is untested in this specific form.. hopefully gets you on track.
SharedSpam="/Library/Server/Mail/Data/mail/SpamTrainer/.JunkMail" SharedHam="/Library/Server/Mail/Data/mail/SpamTrainer/.NotJunkMail" SpamDB="/Library/Server/Mail/Data/scanner/amavis/.spamassassin" sa_PATH="/Applications/Server.app/Contents/ServerRoot/usr/bin/sa-learn" $sa_PATH -u _amavisd --dbpath "$SpamDB" --no-sync --spam $SharedSpam/{cur,new} $sa_PATH -u _amavisd --dbpath "$SpamDB" --no-sync --ham $SharedHam/{cur,new}
This simply tells sa-learn to read directly from your spam/ham directories.
You can add automatic purging and all sorts of other goodies....
To learn more:
man sa-learn
34. Re: Spamassassin Junkmail and Notjunkmail Learning in Mountain Lionscottl31 Nov 14, 2013 10:56 AM in response to Robb Allan
Hi,
I have been trying to figure this out. If I'm not mistaken, this thread is all about using the "junkmail" and "notjunkmail" accounts to learn spam. But it seems it's only if the users are using IMAP. Correct?
Our users are using POP3, so we can spam train by having them forward each spam message to the "junkmail" account, right? If so, can anybody tell me by the following if it is set up correctly, or do I need to do anything else?
I ran:
sudo serveradmin settings mail | grep junk
I got:
mail:postfix:spam_quarantine = "junk-quarantine@example.com"
mail:postfix:spam_notify_admin_email = "junk-admin@example.com"
mail:postfix:junk_mail_userid = "junkmail"
mail:postfix:not_junk_mail_userid = "notjunkmail"
mail:imap:junk_mail_userid = ""
mail:imap:not_junk_mail_userid = ""
Also, how do the quarantine and notify admin accounts work? Depending on your answer, if I want to set up accounts for them, how do I change those example.com defaults to the real accounts I set up?
This has been exhausting trying to find this out, thanks to Apple's lack of documentation.
Thanks very much!
Scott | https://discussions.apple.com/thread/4481820?start=30&tstart=0 | CC-MAIN-2014-23 | refinedweb | 632 | 62.48 |
Recently the business.
On the following link you can find more about latest Yugabyte funding and company evaluation.
In the NewSQL field Yugabyte becomes second unicorn, after the CockroachDB
According to the DB Engine rankings, both distributed databases are on the rise which confirm NewSQL as an excellent concept for a new age.
On the following link you can find out more:
Although I haven’t tested CockroachDb yet, it shares the similar concept with Yugabyte: Raft protocol, Facebook’s RocksDB distributed key/value store and Postgres API on top.
According to the documentation, the major difference between them is in the level of compatibility with Postgres, where Yugabyte has higher level when compared to Cockroach.
You can check Cockroach compatibility with Postgres here:
and Yugabyte compatibility with Postgres here:
In essence, like most of the other new SQL databases, YugabyteDb is created by leveraging layer architecture:
- Query layer YSQL (Postgres API), YCQL (Cassandra API) and Yedis (Redis) which are endpoint that accept client requestst and is responsible for query compilation, execution plan optimization and query execution
- DocDB (Document Store) is distributed document store inspired by Google Spanner, created on top of Facebook RocksDb which has the following features
- write consistent based on Raft protocol
- failure resiliency based on the number of nodes/replicas
- automatic sharding and load balancing in case of hash partitioning
- Zone/region Cloud aware data placement based on the Tablespace concept
Despite YugabyteDb is Apache 2 licensed product, normally you’ll need to purchase Yugabyte Platform to easily install and manage your clusters and get support.
During the installation you can choose from the following list of different deployment options which should satisfy all your needs:
- Cloud (AWS, Azure, GCP)
- VM Ware Tanzu
- RedHat OpenShift
- Kubernetes
- On-premises
On the following picture you can see the starting screen of the Yugabyte Platform Web UI.
Three node cluster is the smallest production ready configuration you can have.
With 3 nodes, cluster can survive falling of one node with no interruptions.
I’ve tested that case while streaming data into YugabyteDB, and it really works like a charm.
Transactions handling in Yugabyte:
Transactions are the most critical part of every rdbms.
Yugabyte is ACID compliant distributed database that supports SERIALIZABLE and SNAPSHOT (REPEATABLE READ) isolation levels, while READ COMMITED is mapped to REPEATABLE READ.
When transaction needs to update multiple rows across multiple shards/tablets and across multiple nodes, Yugabyte relies on globally synchronized clock called Hybrid Logical Clocks (HLCs) which is similar with True Time in terms of Google Spanner.
HLC is critical for ordering events (transactions) across multiple shards/nodes since it has a tight error bounds among nodes in the cluster.
This is much better than to use ancient 2PC (two phase commit) for committing distributed transactions.
Yugabyte “performance tests”
Reason why I put double quotes around performance tests is because they are not classical performance tests on production cluster.
Main goal of tests that I’ve performed is to try some feature on my local VirtualBox cluster to see conceptually how it works.
For that reason, instead of real measurement, I’ll use terms like “faster” or “slower”, and if you want the real numbers, you can try the same test on your system to get the real values.
I’m comparing Yugabyte with Postgres 13 single instance database, two completely different rdbms who share the same interface.
It is also important to note that Postgres has fewer options when you need to satisfy HA and scale out requirements along with the volume of data.
Test 1: Loading 1.5 million records in a table
For initial load, I’m getting better result with Postgres, mainly due to work that distributed database need to perform behind the scenes, starting with table sharding, replication (3 times for three node cluster), indexing, network round trips etc.
For that reason, this is expected result.
Test 2: Reading 1.5 million records
To read all rows from the table, Yugabyte needs to read all shards across all nodes.
Even in single instance rdbms, reading all rows from hash partitioned tables are slower than from unpartitioned table.
If you add shards placed on different nodes plus network latency on top of that, it is expected that Postgres is faster than YugabyteDb.
Test 3: Reading small number of records
In this test Yugabyte and Postgres both return result in approximately the same amount of time.
Therefore, if you have index on column that avoids FTS (full table scan), and your query returns small number of rows (WHERE condition on highly selective column in query) is best use case.
Reason for that is HASH partitioned table on shards, and cached indexes across nodes.
There might be some variants in results which depend on whether all rows are coming from one shard/node or not.
This is a kind of load you can expect in microservice based architecture.
Here are couple of slides from the performance tests:
Execution plan tests:
In this test I’m using famous SCOTT schema from Oracle examples which is imported into Postgres and YugabyteDB.
Here is explain plan for query of interest in Postgres:
explain analyze select * from test_in.emp e, test_in.dept d where e.deptno = d.deptno; Hash Join (cost=23.95..40.02 rows=480 width=244) (actual time=11.210..11.700 rows=14 loops=1) Hash Cond: (e.deptno = d.deptno) -> Seq Scan on emp e (cost=0.00..14.80 rows=480 width=142) (actual time=6.069..6.072 rows=14 loops=1) -> Hash (cost=16.20..16.20 rows=620 width=102) (actual time=5.040..5.169 rows=4 loops=1) Buckets: 1024 Batches: 1 Memory Usage: 9kB -> Seq Scan on dept d (cost=0.00..16.20 rows=620 width=102) (actual time=5.014..5.142 rows=4 loops=1) Planning Time: 29.897 ms Execution Time: 11.763 ms
The same query in case of YugabyteDb:
explain analyze select * from emp e, dept d where e.deptno = d.deptno; Nested Loop (cost=0.00..213.89 rows=1000 width=244) (actual time=36.547..65.982 rows=14 loops=1) -> Seq Scan on emp e (cost=0.00..100.00 rows=1000 width=142) (actual time=32.725..32.924 rows=14 loops=1) -> Index Scan using dept_pkey on dept d (cost=0.00..0.11 rows=1 width=102) (actual time=2.302..2.302 rows=1 loops=14) Index Cond: (deptno = e.deptno) Planning Time: 0.408 ms Execution Time: 66.180 ms
Here it is important to note is that Postgres will use Hash join, while Yugabyte will use Nested loop.
If you look at the estimated costs/rows, Yugabyte is using predefined values (rows=1000), while Postgres estimation is accurate (it’s cost based, not heuristics based).
All in all, Postgres CBO generates better execution plan than Yugabyte, and execution time for this test is 6x faster.
Reason for that is complexity that every distributed database has to face with: locality, network round trips across the nodes, sharding by HASH by default etc.
My guess is that might be a reason why YugabyteDb allows you to use hints by enabling pg_hint_plan Postgres extension by default.
The same extension doesn’t work (or at least I failed to make hint to work) with Postgres 13.
To correct execution plan in Yugabyte can be produced by using hints like in this example:
explain analyze select /*+ HashJoin(e d) */ * from emp e, dept d where e.deptno = d.deptno; Hash Join (cost=112.50..215.14 rows=1000 width=244) (actual time=4.333..4.522 rows=14 loops=1) Hash Cond: (e.deptno = d.deptno) -> Seq Scan on emp e (cost=0.00..100.00 rows=1000 width=142) (actual time=2.480..2.646 rows=14 loops=1) -> Hash (cost=100.00..100.00 rows=1000 width=102) (actual time=1.829..1.830 rows=4 loops=1) Buckets: 1024 Batches: 1 Memory Usage: 9kB -> Seq Scan on dept d (cost=0.00..100.00 rows=1000 width=102) (actual time=1.799..1.814 rows=4 loops=1) Planning Time: 0.304 ms Execution Time: 4.722 ms
This time we have correct execution plan which is about 2x faster than Postgres, although estimations (e.g. rows = 1000) are still wrong.
Summary:
Yugabyte is modern, scalable, geo-distributed, resilient (every shard/tablet is replicated among data nodes) database, which is very easy to use and probably the most Postgres compatible distributed database on the market.
If you are coming from the Oracle world, you’ll learn to appreciate simplicity of all operations that are part of daily DBA routine such as backup and recovery, creating cluster of nodes, horizontal scalability and monitoring.
In a minute you can install and setup cluster either on the Cloud or on-prem or Kubernetes.
On a positive side I would also add readiness to listen by adding missing features or to deal with other issues.
It is important to understand what use cases Yugabyte is trying to solve.
If you are migrating legacy architecture & applications into a modern microservice based architecture where you are joining a couple of tables and execute queries with highly selective WHERE clause (usually primary key – foreign key relations), then YugabyteDb is a right choice for transactional/OLTP loads.
In other cases it might be better to stay with classical SQL databases such as Oracle/Postgres/MySQL/MS SQL.
What I miss the most is inability to leverage Yugabyte for data analysis/BI types of workload, which would probably require to add additional analytic columnar storage engine, in addition to the existing DocDB.
It means if you want to perform data analysis for AI or Business Intelligence, you’ll need to move data out by creating an ETL workflow and ingest data into BI database which adds complexity and expenses.
That is probably the reason why LIST partitioning is not supported yet, while RANGE partition is possible but not recommended to use due to possible partition imbalance.
However, since moving towards microservice based architecture is predominant, there will be more than enough cases where Yugabyte will be a perfect fit.
I’ve also found a couple of issues in database Web console where UI could be better, transaction save point, missing features (for example, it is only possible to perform recovery on database, but not on tablespace or table level) and bugs, but nothing unsolvable.
Since YugabyteDb will cover just a fraction of use cases, that means you’ll still need to maintain classical rdbms databases, which is something your DBAs don’t like (they want to maintain one Db for all cases).
Execution plans are weak point of YugabyteDb, but we need to understand the context first.
Oracle for example, is a database leader, and it has been developing RBO/CBO (Rule and Cost based optimizer) for decades, and it has been 24 years since Oracle introduced CBO in version 8.
Despite maturity and with all technologies implemented over the years (cardinality feedback, adaptive plans, SQL plan baselines, profiles, outlines, histograms etc.), it still often generates wrong execution plans, or decide to change the plan.
While Oracle and other rdbms are mainly single instance systems (everything is happening within a single namespace), with distributed databases it’s many times more complex.
This is why I would suggested for all distributed databases to write simple queries with PK-FK relations over a few tables, which is actually use case for microservice based architecture.
You might still need to correct optimizer to correct execution plans which is mainly rule based (based on heuristics not on real costs), and for that you can use pg_hint_plan.
In the next blog I’ll describe another wonderful distributed database, which is quite different from this one.
Disclaimer:
All impressions and opinions presented in this article are all mine.
If you are considering YugabyteDb or any other NewSQL distributed database, you will need to perform deep analysis for your particular case. | https://www.performatune.com/en/yugabytedb-distributed-sql-database-for-a-new-age/ | CC-MAIN-2022-21 | refinedweb | 2,004 | 53.1 |
Enter/update/exit animation
Now that you know how to use transitions, it's time to take it up a notch. Enter/exit animations.
Enter/exit animations are the most common use of transitions. They're what happens when a new element enters or exits the picture. For example: in visualizations like this famous Nuclear Detonation Timeline by Isao Hashimoto. Each new Boom! flashes to look like an explosion.
I don't know how Hashimoto did it, but with React & D3, you'd do it with enter/exit transitions.
Another favorite of mine is an old animated alphabet example by Mike Bostock, the creator of D3, that's no longer online.
That's what we're going to build: An animated alphabet. New letters fall down and are green, updated letters move right or left, deleted letters are red and fall down.
You can play with a more advanced version here. Same principle as the alphabet, but it animates what you type.
We're building the alphabet version because the string diffing algorithm is a pain to explain. I learned that the hard way when giving workshops on React and D3…
See?
Easy on paper, but the code is long and weird. That, or I'm bad at implementing it. Either way, it's too tangential to explain here. You can read the article about it.
Animated alphabet
Our goal is to render a random subset of the alphabet. Every time the set updates, old letters transition out, new letters transition in, and updated letters transition into a new position.
We need two components:
Alphabet, which creates random lists of letters every 1.5 seconds, then maps through them to render
Lettercomponents
Letter, which renders an SVG text element and takes care of its own enter/update/exit transitions
You can see the full code on GitHub here.
Project setup
To get started you'll need a project. Start one with
create-react-app
or in CodeSandbox. Either works.
You'll need a base App component that renders an SVG with an
<Alphabet>
child. Our component is self-contained so that's all you need.
Something like this 👇
import Alphabet from './components/Alphabet`;const App = () => (<svg width="100%" height="600"><Alphabet x={32} y={300} /></svg>)
I follow the convention of putting components in a
src/components directory.
You don't have to.
Remember to install dependencies:
d3 and
react-transition-group
The Alphabet component
The
Alphabet component holds a list of letters in component state and renders
a collection of
Letter components in a loop.
We start with a skeleton like this:
// src/components/Alphabet.jsimport React from "react";import * as d3 from "d3";import { TransitionGroup } from "react-transition-group";import Letter from "./Letter";class Alphabet extends React.Component {static letters = "abcdefghijklmnopqrstuvwxyz".split("");state = { alphabet: [] };componentDidMount() {// start interval}shuffleAlphabet = () => {// generate new alphabet};render() {let transform = `translate(${this.props.x}, ${this.props.y})`;return (// spit out letters);}}export default Alphabet;
We import dependencies and define the
Alphabet component. It keeps a list of
available letters in a static
letters property and an empty
alphabet in
component state.
We'll start a
d3.interval on
componentDidMount and use
shuffleAlphabet to
generate alphabet subsets.
To showcase enter-update-exit transitions, we create a new alphabet every
second and a half. Using
d3.interval lets us do that in a browser friendly
way.
// src/components/Alphabet/index.jscomponentDidMount() {d3.interval(this.shuffleAlphabet, 1500);}shuffleAlphabet = () => {const alphabet = d3.shuffle(Alphabet.letters).slice(0, Math.floor(Math.random() * Alphabet.letters.length)).sort();this.setState({alphabet});};
Think of this as our game loop: Change alphabet state in consistent time intervals.
We use
d3.interval( //.., 1500) to call
shuffleAlphabet every 1.5 seconds.
Same as
setInterval, but friendlier to batteries and CPUs because it pegs to
requestAnimationFrame. On each period, we use
shuffleAlphabet to shuffle
available letters, slice out a random amount, sort them, and update component
state with
setState.
This process ensures our alphabet is both random and in alphabetical order.
Starting the interval in
componentDidMount ensures it only runs when our
Alphabet is on the page. In real life you should stop it on
componentWillUnmount. Since this is a tiny experiment and we know
<Alphabet> never unmounts without a page refresh, it's okay to skip that
step.
Declarative render for enter/exit transitions
Our declarative enter/exit transitions start in the
render method.
// src/components/Alphabet/index.jsrender() {let transform = `translate(${this.props.x}, ${this.props.y})`;return (<g transform={transform}><TransitionGroup enter={true} exit={true}{this.state.alphabet.map((d, i) => (<Letter letter={d} index={i} key={d} />))}</TransitionGroup></g>);}
An SVG transformation moves our alphabet into the specified
(x, y) position.
We map through
this.state.alphabet inside a
<TransitionGroup> component and
render a
<Letter> component for every letter. Each
Letter gets a
letter
prop for the text, an
index prop to know where it stands, and a
key so
React can tell them apart.
The key property
The key property is how React identifies components. Pick wrong, and you're gonna have a bad time. I spent many hours debugging and writing workarounds before I realized that basing my key on the index was a Bad Move™. Obviously, you want the letter to stay constant in each component and the index to change.
That's how x-axis transitions work.
You move the letter into a specific place in the alphabet. You'll see what I
mean when we look at the
Letter component.
TransitionGroup
React TransitionGroup gives us coordinated control over a set of transitionable
components. Each Letter is going to be a
<Transition>, you'll see.
We need TransitionGroup to gain declarative control over the enter/exit cycle.
Transition components can handle transitions themselves, but they need an
in
prop to say whether they're in or out of the visualization.
Flip from
false to
true, run an enter transition.
true to
false, run an exit transition.
We can make this change from within our component, of course. When responding
to user events for example. In our case we need that control to come from
outside based on which letters exist in the
alphabet array.
TransitionGroup handles that for us. It automatically passes the correct
in
prop to its children based on who is and isn't being rendered.
As an added bonus, we can use TransitionGroup to set a bunch of default
parameters for child Transitions. Whether to use
enter animations,
exit
animations, stuff like that. You can read
a full list in the docs.
The Letter component
We're ready for the component that can transition itself into and out of a visualization. Without consumers having to worry about what's going on behind the scenes 👌
The skeleton for our
Letter component looks like this:
// src/components/Letter.jsimport React from "react";import * as d3 from "d3";import Transition from "react-transition-group/Transition";const ExitColor = "brown",UpdateColor = "#333",EnterColor = "green";class Letter extends React.Component {defaultState = {y: -60,x: this.props.index * 32,color: EnterColor,fillOpacity: 1e-6};state = this.defaultState;letterRef = React.createRef();onEnter = () => {// Letter enters the visualization};onExit = () => {// Letter drops out transition};componentDidUpdate(prevProps, prevState) {// update transition}render() {const { x, y, fillOpacity, color } = this.state,{ letter } = this.props;return (// render Transition with text);}}export default Letter;
We start with some imports and define a
Letter component with a default
state. We keep
defaultState in a separate value because we're going to
manually reset state in some cases.
A
letterRef helps us hand over control to D3 during transitions, the
onEnter callback handles enter transitions,
onExit exit transitions, and
componentDidUpdate update transitions. Render is where it call comes
together.
Each of these transition methods is going to follow the same approach you learned about in the swipe transition example. Render from state, transition with D3, update state to match.
You can make this component more flexible by moving the various magic numbers
we use into props. Default
y offset, transition duration, colors, stuff like
that. The world is your oyster my friend.
onEnter
We start with the enter transition in the
onEnter callback.
// src/components/Letter.jsonEnter = () => {// Letter is entering the visualizationlet node = d3.select(this.letterRef.current)node.transition().duration(750).ease(d3.easeCubicInOut).attr("y", 0).style("fill-opacity", 1).on("end", () => {this.setState({y: 0,fillOpacity: 1,color: UpdateColor,})})}
We use
d3.select to grab our DOM node and take control with D3. Start a new
transition with
.transition(), specify a duration, an easing function, and
specify the changes. Vertical position moves to
0, opacity changes to
1.
This creates a drop-in fade-in effect.
When our transition ends, we update state with the new
y coordinate,
fillOpacity, and
color.
The result is an invisible letter that starts at -60px and moves into 0px and full visibility over 750 milliseconds.
onExit
Our exit transition goes in the
onExit callback.
// src/components/Alphabet/onExit = () => {// Letter is dropping outlet node = d3.select(this.letterRef.current)node.style("fill", ExitColor).transition(this.transition).attr("y", 60).style("fill-opacity", 1e-6).on("end", () => this.setState(this.defaultState))}
Same as before, we take control of the DOM, run a transition, and update state when we're done. We start with forcing our letter into a new color, then move it 60px down, transition to invisible, and reset state.
But why are we resetting state instead of updating to current reality?
Our components never unmount.
We avoid unmounts to keep transitions smoother. Instead of unmounting, we have to reset state back to its default values.
That moves the letter back into its enter state and ensures even re-used letters drop down from the top. Took me a while to tinker that one out.
render
Hard work is done. Here's how you render:
// src/components/Alphabet/Letter.jsrender() {const { x, y, fillOpacity, color } = this.state,{ letter } = this.props;return (<Transitionin={this.props.in}unmountOnExit={false}timeout={750}onEnter={this.onEnter}onExit={this.onExit}><textdy=".35em"x={x}y={y}style={{fillOpacity: fillOpacity,fill: color,font: "bold 48px monospace"}}ref={this.letterRef}>{letter}</text></Transition>);}
We render a
Transition element, which gives us the transition super powers we
need to run enter/exit transitions. Update transitions work on all React
components.
The outside
TransitionGroup gives us the correct
in prop value, we just
have to pass it into
Transition. We disable
unmountOnExit to make
transitions smoother, define a
timeout which has to match what we're using in
our transitions, and define
onEnter and
onExit callbacks.
There's a lot more to the API that we can use and you should check that out in the docs. Docs don't go into detail on everything, but if you experiment I'm sure you'll figure it out.
Inside the transition we render an SVG
<text> element rendered at an
(x, y)
position with a
color and
fillOpacity style. It shows a single letter taken
from the
letter prop.
That's it 👍
Boom. We're done.
You can play with a more complex version of this example here:. Try typing different strings and see how the visualization reacts.
The typing example uses the same Letter components to declaratively render its string, but it drives the input through your typing instead of an automatic shuffler.
Key takeaways for transitions are:
- use d3 for transitions
- use React to manage SVG elements
- use TransitionGroup and Transition for the enter/update/exit pattern | https://reactfordataviz.com/animation/enter-update-exit/ | CC-MAIN-2022-40 | refinedweb | 1,903 | 50.43 |
That would be awesome [2]
Bumping to the top...
Would love this feature: Have autocomplete work across buffers, not only the currently active file. Would work wonders for web development.
+1 for global/language-aware auto completion. +2 if it's aware of function signatures & arguments.
Essential for large projects. This would allow most of the people on my team to break the tractor-beam hold that Eclipse has on them and move to an editor that doesn't have all the visual appeal of a bucket of rusty nails. My Python sucks, but I'll set aside some time this weekend to see how much work this would be -- perhaps easier if a TAGS-like file format can be made that a Sublime plugin can slurp down.
Agree. It will be great for my C#, C++ projects...
There is SublimeCodeIntel which offers code completion for some languages.
There is a ctags package for Sublime (github.com/SublimeText/CTags), too.
I vaguely remember that there is also a package dedicated to C/C++ projects, but I forgot its name.
+1 for autocompletion over files in a project, but only over files with the same extension
I wrote a plugin that pulls completions from every open tab:
import sublime_plugin, sublime
class AutocompleteAll(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
window = sublime.active_window()
# get results from each tab
results = [v.extract_completions(prefix) for v in window.views() if v.buffer_id() != view.buffer_id()]
results = (item,item) for sublist in results for item in sublist] #flatten
results = list(set(results)) # make unique
results.sort() # sort
return results
If you want to limit it to files with the same extension, add something like this:
if(view.file_name() is None):
extension = ''
else:
name, extension = view.file_name().rsplit('.',2)
extension = '.' + extension
views = ]
for v in window.views():
fileName = v.file_name()
if (fileName is None or v.buffer_id() != view.buffer_id() and fileName.endswith(extension)):
views.append(v)
# get results from each tab
results = [v.extract_completions(prefix) for v in views]
# the rest is the same
Nice, didn't now about extract_completions method.By the way, when was it introduced ?
extract_completions has been around since ST1 days
Well, it's strange, I found it in ST 1 API documentation, but this very useful method is not mentioned in new ST 2 API docs. So I didn't know it exists.
@iamnoah I'm not sure how to run that. Is it in package control?
Just copy/paste/save as autocomplete_all.sublime-plugin and drop it in your /Packages/User folder.
If you don't have any luck with giving that file a ".sublime-plugin" extension (I didn't), give it a ".py" extension.
Or go to Tools > New Plugin... then paste the code over the contents of the opened file.
does anyone know how to modify this plugin to use all of the files in the project instead of only the open ones?
Hello,
any news on the feature asked by intrepion ? As my python also sucks (or i did not manage to get enough into the docs), it would be great to just indicate what is there to modify in the given script.
+1 for that!
Here's a package that autocompletes on open files. It's in package control too as "all autocomplete".
github.com/alienhard/SublimeAllAutocomplete
It's not exactly what you asked (whole project), but it usually gets the job done.
Why not use SublimeClang plug-in? | https://forum.sublimetext.com/t/autocomplete-over-all-tabs-project/3779/19 | CC-MAIN-2017-09 | refinedweb | 573 | 68.36 |
Re: Custom error messages when XSD validation fails?
Discussion in 'XML' started by Artie, Apr 21, 2008.
- Similar Threads
XSD validation with custom namespaces ?, Dec 27, 2005, in forum: Java
- Replies:
- 2
- Views:
- 565
Validation of XSD (XML Schema) against XSDRushi, Dec 6, 2005, in forum: XML
- Replies:
- 1
- Views:
- 694
Custom error messages when XSD validation fails?Artie, Apr 21, 2008, in forum: XML
- Replies:
- 1
- Views:
- 1,622
- Martin Honnen
- Apr 21, 2008
Custom Membership Provider - Custom Error MessagesBrett Ossman, Mar 11, 2009, in forum: ASP .Net Security
- Replies:
- 0
- Views:
- 921
- Brett Ossman
- Mar 11, 2009
Redirect to unc path folders fails when "Show HTTP Friendly Error Messages" checkbox is checked forPraveen Bengeri, Apr 19, 2004, in forum: ASP General
- Replies:
- 1
- Views:
- 500
- Tom Kaminski [MVP]
- Apr 19, 2004 | http://www.thecodingforums.com/threads/re-custom-error-messages-when-xsd-validation-fails.606825/ | CC-MAIN-2016-18 | refinedweb | 133 | 57.81 |
30 October 2009 02:16 [Source: ICIS news]
SINGAPORE (ICIS news)--Thailand's PTT Phenol plans to expand its phenol and acetone capacities in February 2010 when a derivative 150,000 tonne/year bisphenol-A (BPA) unit starts up, a company source said on late on Thursday.
The plant in Map Ta Phut, Rayong province, would be shut in late February for expansion, the source said, adding that phenol output would be raised by 50,000 tonnes/year to 250,000 tonnes/year and acetone production would be increased by 31,000 tonnes/year to 155,000 tonnes/year.
PTT Phenol is jointly owned by Thai energy major PTT, PTT Chemical and Aromatics (?xml:namespace>
For more on phenol | http://www.icis.com/Articles/2009/10/30/9259418/ptt-phenol-to-expand-phenol-and-acetone-capacity-in-feb.html | CC-MAIN-2015-06 | refinedweb | 119 | 53.55 |
On Sat, Sep 4, 2010 at 3:28 AM, Stefan Behnel <stefan_ml at behnel.de> wrote: > What about adding an intermediate namespace called "cache", so that the new > operations are available like this: > I had been thinking that the lru_cache should be a class (with a dict-like interface), so it can be used explicitly and not just as a decorator. It could provide a wrap() method to be used as a decorator (or implement __call__ to keep the current semantics, but explicit is better than implicit) widget_cache = lru_cache() widget_cache[name] = widget @lru_cache().wrap def get_thingy(name): return something(name) # get_thingy.cache is an lru_cache instance print(get_thingy.cache.hits). -- Daniel Stutzbach, Ph.D. President, Stutzbach Enterprises, LLC <> -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/python-dev/2010-September/103468.html | CC-MAIN-2017-30 | refinedweb | 126 | 63.39 |
How to Upload YouTube Videos to wikiHow
It is now possible to upload YouTube videos via wikiHow. Right now this functionality is only in a test phase, so while you are encouraged to make and upload videos that may help explain articles, please do not add videos directly to articles at this time. Follow these steps to upload videos and add them to the Video namespace.
[edit] Steps
- Click on the "Upload Video" link in the Editing tools menu.
- Read the instructions on the wikiHow:Upload Video page. Be sure that the video you plan to upload meets our licensing requirements and is compatible with YouTube's system.
- Click on the "Upload YouTube video here" link to be brought to the special video upload page.
- Fill in the upload form with the title for your video, the description of the video, and its keywords. This is the information that will be used to identify the video on YouTube.
- Click on the "Submit" button. You will be brought to an upload screen.
- Click on the "Browse" button to look for the video on your computer.
- Locate the video and then click "Upload" to upload the video.
- Wait. Depending upon the size of the video and the speed of your connection, it may take some time to upload and process the video.
- Look for the confirmation screen; understand that it may take YouTube's system a few minutes to process your uploaded video and make it available for viewing.
- Use the displayed code from the confirmation screen (e.g., "{{#ev:youtube|25hlFfGTGEo}}") to add the video to a page in the Video namespace.
[edit] Tips
- YouTube has a great deal of information on improving your video-making skills.
- Experiment with different ways of using videos to illustrate your how-to article.
[edit] Warnings
- Videos uploads are logged and will be reviewed by other wikiHow community members. Do not upload inappropriate materials or content that violates copyrights. | http://www.wikihow.com/Upload-YouTube-Videos-to-wikiHow | crawl-002 | refinedweb | 324 | 73.17 |
FPointer
FPointer : Callbacks with arguments and return values¶
In a previous cookbook article (Mbed's FunctionPointer) the Mbed's library callback mechanism was described and also worked demonstrations were presented. If you have not yet read that article then please do so now. This cookpage article is a continuation from that.
The FPointer class type¶
One of the limiting factors of the FunctionPointer type was that the callback required a function prototype of void/void. It can neither take any arguments nor can it return a value. FPointer differs from FunctionPointer in one crucial way. It's callback function prototype is of the type:-
FPointer callback function prototype
uint32_t myCallback(uint32_t);
It can be seen that FPointer callbacks can take a single argument of type uint32_t and return the same uint32_t data type. This allows FPointer to send and return values in multiple ways. The full definition of the FPointer can be found here:-
Import libraryFPointer
FPointer - A callback system that allows for 32bit unsigned ints to be passed to and from the callback.
If your callback only needs to take or return a uint32_t then it's possible to use it "as is". However, if you need to pass multiple arguments to a callback and/or of differing types then it may at first not be obvious how to. However, since the Mbed's microcontroller (LPC17xx) has a natural data width of 32bits, a uint32_t can also be a pointer. That allows us to create data structures and pass pointers to those structures.
In the FunctionPointer article a simple demonstration showed the use of "stub-callbacks" used to call a common callback with additional arguments. Here, we will use FPointer to develop a library that is generic in implementation and shows how to make a callback to a user's application/program with the extra data needed. A brief recap of the simple specification follows:-
Quote:
We have four inputs and we want to display this as BCD on two LEDs, led1 and led2. We want this display to be interrupt driven so as not to have to "poll" the pins and update the display. Additionally, led4 should show how the change came about, on if it was a rising edge, off if it was a falling edge.
Let's begin by creating a library class type and we'll then follow that with a user's application that uses this library.
myLib.h
#ifndef MY_LIB_H #define MY_LIB_H #include "mbed.h" #include "FPointer.h" typedef struct { int value; int direction; } MYDATA; #define MYDATA_VALUE_P(x) ((MYDATA *)x)->value #define MYDATA_DIRECTION_P(x) ((MYDATA *)x)->direction // InterruptIn stores it's PinName in a protected area // but doesn't provide a method to get which pin after // it's been created. So extend InterruptIn and add an // extra method to allow us to get this information. class myInterruptIn : public InterruptIn { public: myInterruptIn(PinName p) : InterruptIn(p) {}; PinName pinName(void) { return _pin; } }; class myLib { protected: myInterruptIn _pA; myInterruptIn _pB; myInterruptIn _pC; myInterruptIn _pD; FPointer _callback; MYDATA _myData; void common(PinName p, int direction) { if (p == _pA.pinName()) _myData.value = 0; else if (p == _pB.pinName()) _myData.value = 1; else if (p == _pC.pinName()) _myData.value = 2; else if (p == _pD.pinName()) _myData.value = 3; _myData.direction = direction; _callback.call((uint32_t)&_myData); } void _pAcb_rise(void) { common(_pA.pinName(), 1); } void _pAcb_fall(void) { common(_pA.pinName(), 0); } void _pBcb_rise(void) { common(_pB.pinName(), 1); } void _pBcb_fall(void) { common(_pB.pinName(), 0); } void _pCcb_rise(void) { common(_pC.pinName(), 1); } void _pCcb_fall(void) { common(_pC.pinName(), 0); } void _pDcb_rise(void) { common(_pD.pinName(), 1); } void _pDcb_fall(void) { common(_pD.pinName(), 0); } public: myLib(PinName pA, PinName pB, PinName pC, PinName pD) : _pA(pA), _pB(pB), _pC(pC), _pD(pD) { _pA.rise(this, &myLib::_pAcb_rise); _pA.fall(this, &myLib::_pAcb_fall); _pB.rise(this, &myLib::_pBcb_rise); _pB.fall(this, &myLib::_pBcb_fall); _pC.rise(this, &myLib::_pCcb_rise); _pC.fall(this, &myLib::_pCcb_fall); _pD.rise(this, &myLib::_pDcb_rise); _pD.fall(this, &myLib::_pDcb_fall); } void attach(uint32_t (*function)(uint32_t) = 0) { _callback.attach(function); } template<class T> void attach(T* item, uint32_t (T::*method)(uint32_t)) { _callback.attach(item, method); } }; #endif
Now that we have created our library here is how a user's application would look using it:-
main.cpp
#include "mbed.h" #include "myLib.h" DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led4(LED4); myLib lib(p24, p23, p22, p21); uint32_t myCallback(uint32_t arg) { switch( MYDATA_VALUE_P(arg) ) { case 0: led1 = 0; led2 = 0; case 1: led1 = 0; led2 = 1; case 2: led1 = 1; led2 = 0; case 3: led1 = 1; led2 = 1; } led4 = ( MYDATA_DIRECTION_P(arg) ) ? 1 : 0; return 0; } int main() { lib.attach(&myCallback); while(1); }
The above shows us two important points/features. At first glance myLib.h appears to be a little more complex than the demonstration presented in the previous article. This is often true of libraries and it stems from the fact that libraries are usually generic in nature (for example the library doesn't know in advance what pins you are going to assign to the InterruptIns) and secondly adds a data structure to the mix. Not shown here also is the doxygen comments library writers put in to allow for documenting any API or usage of the library. But the first important concept is a library is usually "done once, used often". Take a look at the "application" main.cpp. As you can see, from the user's perspective the implementation is a whole lot simpler. So long as the user creating the application has ample documentation and/or examples of use, using the library becomes very simple.
The second important feature and most relevent to this article is the use of the FPointer callback. As used here when it calls back to the user's application it is passing a pointer to a data structure that, in this instance, holds two variables: value and direction. This makes FPointer's callback mechanism very powerful and flexible. | https://os.mbed.com/cookbook/FPointer | CC-MAIN-2019-51 | refinedweb | 988 | 57.77 |
On Thu, Nov 3, 2011 at 3:48 PM, Aditya Narayan <adynnn@gmail.com> wrote:
> I am concatenating two Integer ids through bitwise operations(as
> described below) to create a single primary key of type long. I wanted to
> know if this is a good practice. This would help me in keeping multiple
> rows of an entity in a single column family by appending different
> extensions to the entityId.
> Are there better ways ? My Ids are of type Integer(4 bytes).
>
>
> public static final long makeCompositeKey(int k1, int k2){
> return (long)k1 << 32 | k2;
> }
>
You could use an actual CompositeType(IntegerType, IntegerType), but it
would use a little extra space and not buy you much.
It doesn't sound like this is the case for you, but if you have several
distinct types of rows, you should consider using separate column families
for them rather than putting them all into one big CF.
--
Tyler Hobbs
DataStax <> | http://mail-archives.apache.org/mod_mbox/cassandra-user/201111.mbox/%3CCAAam9sujzv8TdcBK-ebCqkhZcbOE-eUW9=x1W1GAgQ=+Sdo0YQ@mail.gmail.com%3E | CC-MAIN-2016-44 | refinedweb | 157 | 63.29 |
Quoridor: Playing A Maze Game On The Console With Python
Integration weeks at Marmelab are amazing! Barely arrived, I shook hands of my new coworkers. Then, François told me: "Do you know Quoridor?". I said "No". So he explained me the rules. We played a game. I lost! And he told me that Quoridor will be the game I will work on during my integration period. Every challenge will have its own constraints.
So my first challenge develop a playable Quoridor game in a Terminal using Python. Brutal, but very exciting!
Quoridor in a Nutshell
Quoridor is a board game playable from two to four persons. At the beginning, each player has a pawn placed in the middle of their side. Their goal is to reach the opposite side.
Players play one after the other. Players can choose between moving their pawn, or putting up a fence.
Move You Pawn
You can move your pawn according to a few rules:
- One square at a time in all directions except diagonally [1],
- as long as you do not cross a fence [2],
- behind another pawn [5] (jump action),
- in diagonal when a fence is behind your opponent [3, 4],
Put Up a Fence
Fences are two squares long, and you can place them between any squares - except that you cannot add a fence which disallows the pawns to reach their goal.
There is a limit of fences a player can put up: 10 fences for a 2 players game, and 5 fences for 3 or 4 players games.
Before moving on, take a moment to think about how YOU would implement such a game. No straightforward, isn't it?
Development Process
Throughout the challenges, I learned the processes that marmelab engineers use every day. It's based on agile methodologies and rituals such as planning poker, daily meetings, retrospective, ....
What I appreciate the most is the process of pull requests, and for several reasons.
Code Review
Each pull request (PR) is reviewed by at least one other developer. Code reviews are important to detect bugs, bad architecture/code, and also to share the knowledge. It is a good opportunity to progress quickly if you follow the recommendations.
Development Progression
The PR title has a prefix which is either [WIP] or [RFR]:
- WIP (work in progress) is the default status. You can add a checklist to explain what you did and what is missing.
- RFR (ready for review) means that the work is over and you need a final review. In general, there are still improvements to do after a code review.
At a glance, you know whether you can review the PR. Convenient!
Feature Screenshot
Adding a screenshot of the feature result enables the reviewer to see what the feature is, and you can have UI reviews as well.
Commit Frequency
The commit frequency surprised me. Even if the work is not over or at the end of your work day, you push your work to the origin. In that way, you will have feedback quickly. It is a bit disturbing when you learnt to push only when the commit works. But I understood that a remote coworker cannot help you well if you do not show them the code. It is possible to use video conferencing, but it is better to keep track of the work. Moreover, the customers can see what you did during the day.
Learning Python In One Week
I had heard about Python, but I never played with it. So this challenge was a good opportunity to test it, and check if it is as easy as it seems.
I am a java developer. I like fluent APIs. I prefer to read the code as I read a book. Python was a good surprise in that perspective.
Here are some examples.
- conditional
return Item.PAWN_1 if index == 0 else Item.PAWN_2
- list comprehensions
fences = [[Direction.NO for i in range(FENCE_SIZE)] for j in range(FENCE_SIZE)]
- indentation to delimit blocks
def add_random_fence(fences): center_x = randint(0, FENCE_SIZE - 1) center_y = randint(0, FENCE_SIZE - 1) direction = randint(Direction.HORIZONTALLY, Direction.VERTICALLY) if can_add_fence(fences, center_x, center_y, direction): return Fence(center_x, center_y, direction) return add_random_fence(fences)
I was suprised by the indentation rule. I never thought of using indentation to delimit blocks. Sure, you have fewer markers, but if you add one extra space, your code may not work anymore.
The Challenges I Met
Code Structure
The main files of that project are:
- game.py: the controller
- console.py: the view
- board.py and pawn.py: the model
The game contains the board (the list of fences) and the list of pawns.
A fence is defined with the top left square and a direction (horizontal or vertical)
The main challenges are not how to store the game and the rules, but how to show the game.
Drawing In the Console, One Character at a Time
Displaying a Quoridor board in the console was a long and tedious work. After every feature, the board changed.
On the left is the first display, and on the right the final one. You can see that it changed a bit!
Even if the interface changes, the internal representation is the same. The game gives the console a 2D array, which is a full representation of the squares, the pawns, the fences, and the places where to put up fences. In that way, the console can iterate over this array line after line to print the game.
Moving a Pawn With The Keyboard
The first idea was to use the arrows on the keyboard. I tried to use keyboard but I spent too much time integrating it in my project. So I decided not to listen to the events on the keyboard but to wait for a keystroke. So two actions instead of one. What a pity!
Putting Up a Fence
I did not have enough time to develop that feature. But it is a real challenge to only use the keyboard to add a fence. I thought of asking for the top left square with the direction of the fence like 23v (second column, third line, vertically). The board display should change to show the column and row numbers.
Make It Work, Make It Fast, and Make It Well
Time flies when you only have 4 days and a half. At the end of my challenge, the game was not fully playable.
What I came up with is is a two-player game where players can only move their pawn. Fences are put up randomly at each start of the game. No way to add them manually.
You can have a look at the code in the marmelab/quoridor-python GitHub repository.
"Challenge" is the right word to describe what I felt during this period. I was challenged on what I have done (technical choices, UI, the way I code, ...). I was under pressure. But I am glad about the result I reached and how I reached it.
To sum up what I learned about marmelab work during this week:
- reach a working result,
- reach it quickly,
- and reach it well with high-value code quality.
I am excited to know what will be my next challenge. | https://marmelab.com/blog/2019/10/24/quoridor-part-1.html | CC-MAIN-2022-27 | refinedweb | 1,204 | 74.49 |
Lustre
This pages should help you to get a running lustre cluster based on debian systems.
Contents
You can either build your own Lustre Debian packages from GIT or download these packages from
and
If you download all packages incl. the kernel package you can continue with chapter Installation of Lustre 2.2 in Debian Squeeze.
If you download only the Lustre packages without the kernel and kernel module package, e.g. because you want to compile your own custom kernel, please continue with chapter Building Lustre kernel.
Building Lustre 2.2 for Debian Squeeze
Building Lustre packages from GIT
Change to a any Lustre building directory and clone the actual GIT tree of Debian Lustre project:
git clone
Then you need the original source tarball of Lustre.
wget
Finally you can build your packages like this:
cd lustre dpkg-buildpackage
(If you don't want to sign your packages, you can add the parameters -us -uc to dpkg-buildpackage)
Now you'll find your packages in your Lustre building directory.
Building Lustre 2.2 kernel for Debian Squeeze
Install the linux-patch-lustre_2.2.0-5_all.deb package:
sudo dpkg -i linux-patch-lustre_2.2.0-5_all.deb
The Lustre patches for Linux kernel 2.6.32 will be placed in /usr/src/kernel-patches/lustre.
To go on please now install the kernel source package from Debian Squeeze:
apt-get source linux-2.6 cd linux-2.6-2.6.32 /usr/src/kernel-patches/lustre/scripts/apply
All the Lustre patches are being applied to the kernel sources. Now you can create your kernel. First prepare your sources:
fakeroot make-kpkg --config=menuconfig --revision deblust.1.0 --append-to-version "-lustre-2.2" configure
Please choose a meaningful revision name. Save your configuration as .config file and then initiate the building process:
fakeroot make-kpkg --initrd --revision deblust.1.0 --append-to-version "-lustre-2.2" kernel_image kernel_headers kernel_source
Depending on your system this can take a long time.
With the help of the script /usr/src/kernel-patches/lustre/scripts/unpatch you can remove the Lustre kernel patches from the sources.
Building Lustre 2.2 modules
Install the Lustre kernel image and Lustre source package:
sudo dpkg -i linux-image-2.6.32-lustre-2.2_deblust.1.0_amd64.deb sudo dpkg -i linux-headers-2.6.32-lustre-2.2_deblust.1.0_amd64.deb sudo dpkg -i linux-source-2.6.32-lustre-2.2_deblust.1.0_all.deb sudo dpkg -i lustre-source_2.2.0-5_all.deb
Please reboot into the new Lustre kernel. Use the module-assistant to start the module building process:
sudo m-a auto-install lustre
Then the module kernel package should be there and the modules installed.
Installation of Lustre 2.2 in Debian Squeeze
For a minimal test cluster at least 4 machines are recommended:
- Lustre test client
- Lustre MGS/MDT (Management Server/Metadata Target)
- Lustre OST1 (Object Storage Target)
- Lustre OST2
The MGS stores configuration information for all the Lustre file systems in a cluster and provides this information to other Lustre components, whereas the MDT stores namespace metadata (filenames, directories, access permissions, file layout). The MGS/MDT is also an entry point. The OST stores the data.
Preparing the systems
Install on all machines:
sudo dpkg -i linux-image-2.6.32-lustre-2.2_deblust.1.0_amd64.deb sudo dpkg -i lustre-modules-2.6.32-lustre-2.2_2.2.0-5_amd64.deb sudo dpkg -i lustre-utils_2.2.0-3_amd64.deb sudo dpkg -i ldiskfsprogs_1.42.3-1_amd64.deb
Now you are ready to boot the kernel an all machines. Then load the kernel modules with:
modprobe lnet modprobe lustre modprobe ldiskfs
If you're running ypbind or something else on your system which uses port 988 you should make sure that the ptctl module is loaded very early in the boot process (as lustre needs port 988 for communications), See the ?KnowledgeBase for details.
MGS/MDT
Create a new and free partition (as large as possible), e.g. /dev/sda4 and format it as MGS/MDT:
mkfs.lustre --fsname=temp --mgs --mdt /dev/sda4
temp is the name of our filesystem. This can be changed of course. The formatting process could take a long time.
Mount the new partition:
mount -t lustre /dev/sda4 /srv/mdt
You can choose another mountpoint of course.
OST
Create a new and free partition (as large as possible), e.g. /dev/sda4 and format it as MGS/MDT:
mkfs.lustre --ost --fsname=temp --mgsnode=192.168.80.100@tcp0 /dev/sda4
temp is the name of our filesystem. Please note that we have to set the IP adress or Hostname of the Lustre MGS node (here: 192.168.80.100).
Mount the new partition:
mount -t lustre /dev/sda4 /srv/ost1
You can choose another mountpoint of course.
Repeat for OST2.
Client
Go to the client machine and mount your new Lustre file system:
mount -t lustre 192.168.80.100@tcp0:/temp /mnt/lustre
Verify that the file system started and is working:
lfs df -h
Go to /mnt/lustre (or whatever your mount point is) and run a first basic test:
dd if=/dev/zero of=/lustre/zero.dat bs=4M count=20
Please check also your kernel logs for any error messages.
Using Quota
The binaries and drivers for lustre in debian are compiled with quota enabled. So if you like to use quota this is quite simple:
lfs quotacheck -ug $path/to/mounted/lustre/fs lfs setquota -u $user 1000 2000 10000 20000 $path/to/mounted/lustre/fs lfs quota -u $user $path/to/mounted/lustre/fs | https://wiki.debian.org/Lustre?action=recall&rev=10 | CC-MAIN-2019-22 | refinedweb | 940 | 59.09 |
The C# Jagged is an array whose elements are also an array, i.e., it is an array of arrays. These elements inside a jagged array can be of different dimensions and even can be of different sizes.
A Jagged array in C# can be declared and initialized as follows:
Int[][] JaggedAr = new int[2][];
Here size 2 represents the number of arrays, i.e., two in JaggedAr[][].
We have to initialize the arrays inside before using the Jagged.
JaggedAr[0] = new int[]{5,9,6};
JaggedAr[1] = new int[]{2,5};
Let us see an example code demonstrating on Jagged arrays.
C# Jagged Array Example
The below-shown example explains to you the declaration and use of the Jagged Array.
using System; class program { public static void Main() { string[] NameOfEmployee = new string[2]; NameOfEmployee[0] = "John"; NameOfEmployee[1] = "Winson"; string[][] JaggedAr = new string[2][]; JaggedAr[0] = new string[] { "Bachelors", "masters", "Doctrate" }; JaggedAr[1] = new string[] { "Bachelors", "Masters" }; for(int i = 0;i<JaggedAr.Length;i++ ) { Console.WriteLine(NameOfEmployee[i]); Console.WriteLine("-------"); string[] arrayin = JaggedAr[i]; for(int j = 0; j< arrayin.Length;j++) { Console.WriteLine(arrayin[j]); } Console.WriteLine(); } Console.ReadLine(); } }
ANALYSIS
NameOfEmployee[] is a string array in which there are two elements.
JaggedAr[][] is a jagged having two string arrays.
JaggedAr[0] has three elements —— Bachelors, masters, and Doctorate.
JaggedAr[1] has two elements in it —– Bachelors, Masters.
Since JaggedAr.Length is 2, When i = 0, 0<2 condition returns true. So, the control enters the parent loop and prints NameOfEmployye[0], which is.
John
——
Now JaggedAr[0] is stored in arrayin[]
When j=0, j<arrayin.Length, i.e., 0<3 since JaggedAr[0] is having three elements.
0<3 returns true. So, C# prints Bachelors
Again j++, i.e., 1
Now, 1 < 3 returns true. So, it prints Masters
Again j++, i.e., 2
Next, 2 < 3 returns true, and It prints Doctorate.
Again j++, i.e., 3
Now, 3 < 3 returns false come out of child loop
Now Console.WriteLine() is executed.
Again it increments i in the parent loop. This time i=1, so 1<2 returns true. Thus enters the loop and prints NameOfEmployee[1], i.e.,
Winson
———-
arrayin = JaggedAr[1]
j=0 and j<arrayin.Length, which is 2, and it returns true. So, the control enters the child loop and prints arrayin[0]
Bachelors
j++ = 1 and 1<2 returns true. Enters the child loop and prints arrayin[1], i.e.,
Masters
j++ = 2 and 2<2 returns false. So, it comes out of the child loop and executes.
Console.WriteLine();
Now increments I by 1 so i++ = 2
2<2 returns false, so it comes out of the parent loop. | https://www.tutorialgateway.org/csharp-jagged-array/ | CC-MAIN-2022-40 | refinedweb | 450 | 69.18 |
spyrorocks 1 Posted May 14, 2006 (edited) Hello. I know that you are now allowed to post The word that must not be spoken on this fourm, but i am just asking for some help with one . Is there a simpler way to capture keystrokes without having to get the hex value for every key, then doing a if statement?$i = 1 #Include <Misc.au3> #include <String.au3> $usr = DllOpen("user32.dll") $sleep = 200 $log = "" while $i = 1 if _IsPressed("23", $usr) then $log = $log & _HexToString(23) sleep($sleep) endif wendexept i have to do this:if _IsPressed("23", $usr) then $log = $log & _HexToString(23) sleep($sleep) endiffor every single key. Is there a easyer way to log all keystrokes? Edited May | https://www.autoitscript.com/forum/topic/26101-_ispressed-is-there-a-simple-way/ | CC-MAIN-2019-04 | refinedweb | 122 | 82.85 |
To All - Ref: Kernel snap-shot of 0603 (presumed similar to V0.9 kernel) Found: File: linux/include/asm-parisc/io.h Lines: 27 - 40 Do: Comment out the #ifdef at (appox.) line 27 and matching #endif at (appox) line 40 Situation (sitrep): Box model 720 doesn't have PCI BA - Box model 720 EISA BA was an option (mine has one, I don't have a card, so I am not building that driver.) Without either BA's defined - in/out Byte, Word, Long does not have a prototype in mem.c (amoung other places) - the compiler guesses (incorrectly) at what inb() and outb() mean. Makes a difference. More to follow as I work my way through: serial.c pc_keyb.c lasi_82596.c parport_gsc.c scsi.c sim700.c inode.c array.c binfmt_som.c binfmt_elf.c and various other bits and bytes. Hey - No one ever said this was a clean build, did they? Mike On Tue, 05 Jun 2001, you wrote: > On Tue, Jun 05, 2001 at 09:14:05AM -0500, djweis@sjdjweis.com wrote: > > > > On Tue, 5 Jun 2001, Richard Hirst wrote: > > > > > So with the nfsroot you have the D310 booting, but with the 0.9 ISO > > > it stops after serial driver initialisation. > > > > No, if I boot off the cd, I get IPL errors. When I netboot the kernel off > > the cd, it stopped at serial init. I don't think it actually stopped, I > > think it no longer printed but still booted. > > Ah, ok. I'd misunderstood you. So the kernel on the CD is no > different from the one you built yourself. That's a relief! > > Have you checked both serial ports, just in case the one the > kernel finds isn't the one you are using? > > From the boot msgs you sent earlier, it looks like you turned > SERIAL_DEBUG_AUTOCONF on. Does it actually run the loopback > test at serial.c:3671 successfully? > > Richard > > > > _______________________________________________ > parisc-linux mailing list > parisc-linux@lists.parisc-linux.org > | https://lists.debian.org/debian-hppa/2001/06/msg00019.html | CC-MAIN-2018-34 | refinedweb | 331 | 75.5 |
Linux
2019-11-19
NAME
pidfd_open - obtain a file descriptor that refers to a process
SYNOPSIS
#include <sys/types.h>
int pidfd_open(pid_t pid, unsigned int flags);
DESCRIPTION
The pidfd_open() system call creates a file descriptor that refers to the process whose PID is specified in pid. The file descriptor is returned as the function result; the close-on-exec flag is set on the file descriptor.
The flags argument is reserved for future use; currently, this argument must be specified as 0.
Currently, there is no glibc wrapper for this system call; call it using syscall(2).
pid = fork(); if (pid > 0) { /* If parent */
pidfd = pidfd_open(pid, 0);
... }
pidfd = pidfd_open(pid, 0);
... }
Even if the child has already terminated by the time of the pidfd_open() call, its PID will not have been recycled and the returned file descriptor will refer to the resulting zombie process. Note, however, that this is guaranteed only if the following conditions hold true:If any of these conditions does not hold, then the child process (along with a PID file descriptor that refers to it) should instead be created using clone(2) with the CLONE_PIDFD flag.
Use cases for PID file descriptors
A PID file descriptor returned by pidfd_open() (of by clone(2) with the CLONE_PID flag) can be used for the following purposes:The pidfd_open() system call is the preferred way of obtaining a PID file descriptor for an already existing process. The alternative is to obtain a file descriptor by opening a /proc/[pid] directory. However, the latter technique is possible only if the proc(5) filesystem is mounted; furthermore, the file descriptor obtained in this way is not pollable and can’t be waited on with waitid(2).
EXAMPLE
The program below opens a PID file descriptor for the process whose PID is specified as its command-line argument. It then uses poll(2) to monitor the file descriptor for process exit, as indicated by an EPOLLIN event.
Program source
#define _GNU_SOURCE #include <sys/types.h> #include <sys/syscall.h> #include <unistd.h> #include <poll.h> #include <stdlib.h> #include <stdio.h>
#ifndef __NR_pidfd_open #define __NR_pidfd_open 434 /* System call # on most architectures */ #endif
static int pidfd_open(pid_t pid, unsigned int flags) { return syscall(__NR_pidfd_open, pid, flags); }
int main(int argc, char *argv[]) { struct pollfd pollfd; int pidfd, ready;
if (argc != 2) { fprintf(stderr, "Usage: %s <pid>\n", argv[0]); exit(EXIT_SUCCESS); }
pidfd = pidfd_open(atoi(argv[1]), 0); if (pidfd == -1) { perror("pidfd_open"); exit(EXIT_FAILURE); }
pollfd.fd = pidfd; pollfd.events = POLLIN;
ready = poll(&pollfd, 1, -1); if (ready == -1) { perror("poll"); exit(EXIT_FAILURE); }
printf("Events (0x%x): POLLIN is %sset\n", pollfd.revents, (pollfd.revents & POLLIN) ? "" : "not ");
exit(EXIT_SUCCESS); } | https://reposcope.com/man/en/2/pidfd_open | CC-MAIN-2022-21 | refinedweb | 447 | 63.19 |
Angular has become very popular over the past couple of years. You can use this open-source JavaScript framework to build web and mobile apps. If you've been thinking about learning Angular but don't know where to start, following this series might be a good idea.
The aim of this series is to cover the basics of Angular while creating a very simple app that shows information about different countries. Angular is written in TypeScript, so it makes sense that you write your own code in TypeScript as well.
There's no need to worry if you have never used TypeScript before. To put it simply, TypeScript is just typed JavaScript with additional features. I have also written a series titled TypeScript for Beginners on Envato Tuts+, where you can learn the basics of TypeScript first.
If you are already familiar with TypeScript, you can just go ahead and start creating your first Angular app.
The first step would be to install Node.js. You can head to the official website and download the appropriate version. The node package manager will be installed as part of Node.js.
The next step is to install TypeScript by running the following command. I recommend that you install a TypeScript version over 2.1.
npm install -g typescript
Finally, you have to install the Angular CLI by running the following command. Installing Angular CLI will make the process of creating your Angular app easier.
npm install -g @angular/cli
Now, you can create a new Angular app right out of the box by running the following command inside the terminal. Before running the command, make sure that you have moved to the directory where you want to create the app.
ng new country-app
Installing all the dependencies for the project takes some time, so please be patient while Angular CLI sets up your app. After the installation completes, you will see a folder named
country-app in the current directory. You can run your app right now by changing the directory to
country-app and then running
ng serve in the console.
cd country-app ng serve --open
Adding
--open will automatically open your app in the browser at.
The country information app that we are creating will have three components. The
HomeComponent will show the top three countries under various categories like population, GDP, and area. You will be able to click the name of each country to read more about it. The additional information about the country is listed using another component, which we will be calling the
CountryDetailComponent. There will be one more component in our app, which will be used to display a list of all the countries that we have stored in our app.
Since this is your first Angular app, our main aim will be to keep things simple without adding any complicated functionality. Once you have a good grasp of the basics, creating more complex apps will not seem like a daunting task.
The image below is of the homepage or
HomeComponent in our country information app. As you can see, there are three countries under each category, and they have been placed in descending order. While creating the
HomeComponent, you will learn how to sort different countries before displaying them inside the template.
The following image shows the "all countries page" or
AllCountriesComponent of our app. The layout of this component is very similar to the
HomeComponent. The only difference is that this time we are listing all the countries along with their capitals.
If you click on the box of any country rendered inside either the
HomeComponent or the
AllCountriesComponent, you will be taken to the country detail page or
CountryDetailComponent. The information provided about a country is not editable.
There is a back button after the details of each country. This back button takes you back to the previous component or page. If you came to the
CountryDetailComponent from the
HomeComponent, you will be taken back to the
HomeComponent. If you arrived at the
CountryDetailComponent from the
AllCountriesComponent, you will be taken back to the
AllCountriesComponent.
Referring to different components that we are creating as pages is not technically correct. However, I am using terms like homepage or
HomeComponent interchangeably because seeing a lot of unfamiliar terms like routing, components, and decorators can be intimidating for readers who have never created an Angular app before. Using these terms loosely for this series can help you learn quickly instead of getting confused by the jargon.
Before we begin creating our app, you need to be comfortable with the basic concepts of Angular. This section will very briefly cover important topics like components and templates.
Components are the building blocks of an Angular app. They allow you to control the UI of your app. A basic component consists of two parts: a decorator and a class definition. You can specify the application logic for a component inside the class.
The component decorator is used to specify information like a custom selector to identify the component, the path to the HTML template, and the style rules to be applied to the component.
Here is a basic component decorator that sets all three values for
CountryDetailComponent:
@Component({ selector: 'app-country-detail', templateUrl: './country-detail.component.html', styleUrls: ['./country-detail.component.css'] })
All the components that we create will have a custom selector which specifies the tag that renders the component inside the browser. These custom tags can have any name you want. For example, we will be creating a
countryDetailComponent in the third tutorial of the series, and we will use our own custom tag called
app-country-detail to render this component in the browser.
Any component that you create will consist of a template that controls what is rendered on the application page. For example, the
countryDetailComponent has two
div tags which act as a wrapper around the main content of the component. Each piece of information about a country is put inside its own
p tag, and the name of the country is put inside an
h2 tag. All these tags can be stored together as a template for the
countryDetailComponent and then rendered as a unit. This template of the component can be saved as an HTML file or specified directly inside the decorator using the
template attribute.
Different components of our app will need to retrieve the data to display on screen. We will be creating a service class that will contain functions to help us retrieve this data and sort or modify it one way or another. We will then use the functionality of different component classes to display this data to the user.
You can consider a
Service to simply be any value, function, or feature that your application needs. Getting all the countries stored inside our application is a service, and so is sorting and displaying them. All the three components in our class will be using functions from our service to retrieve data.
When creating components for your app, you will have to import dependencies from different modules. For example, we will be importing
Component from the
@angular/core whenever we create a component of our own. You can also use the same syntax to import dependencies that were created by you. The part inside curly brackets is used to specify the dependency that you want to import, and the part after
from is used to specify where Angular can find the dependency.
Here is a code snippet from the
country-app that we will be creating. As you can see, we are importing
Component and
OnInit from the
@angular/core. Similarly, we are importing a
Country and
CountryService from files that we created ourselves.
import { Component, OnInit } from '@angular/core'; import { Country } from '../country'; import { CountryService } from '../country.service';
After you ran the
ng new country-app command, the Angular CLI created a bunch of files and folders for you. Seeing so many files can be intimidating as a beginner, but you don't need to work with all those files. When creating our country app, we will only be modifying the files already existing inside the
src/app folder as well as creating new files in the same directory. Right now, you should have five different files in the
src/app folder. These files create an application shell which will be used to put together the rest of our app.
The
app.component.ts file contains the logic for our component written in TypeScript. You can open this file and update the
title property of the
AppComponent class to 'Fun Facts About Countries'. The
app.component.ts file should now have the following code.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Fun Facts About Countries'; }
The
app.component.html file contains the template for our
AppComponent class. Open the
app.component.html file and replace the boilerplate HTML code inside it with the following line:
<h1>{{title}}</h1>
By wrapping
title inside the curly brackets, we are telling Angular to put the value of
title property of the
AppComponent class inside the
h1 tag.
We will be updating this file in the last tutorial of the series to render new components that we will be creating. For now, it just needs to show the title of our app.
The changes made to this file will be automatically reflected in the browser at. Just make sure that the console is still open and you have already typed in the
ng serve command from the beginning of the tutorial.
Different functions and features of the app will be controlled by multiple simpler components that we will create later. You can think of this application shell as a car and different components that we will create as parts of that car like the engine and the wheels. Each component will perform its specific function, and you can put them all together to create the whole car.
The aim of this tutorial was to help you install all the necessary tools that you need to create an Angular app and quickly go over some fundamental Angular concepts.
To summarize, you need to know the basics of TypeScript before you can create an Angular app. In the next step, you need to install Node.js, TypeScript, and the Angular CLI. After that, you can just run a bunch of commands from the Getting Started section of this tutorial, and your first Angular app will be up and running.
Our country app will do a lot more than just show the title. In the next tutorial, you will create a few classes and services that will be used to store and retrieve data about different countries. These classes and services will be useful in the third and fourth tutorials, where we will create different components of our app.
While we're working through this tutorial series, don't forget to check out Envato Market to see what's available for use and study for both Angular and JavaScript, in… | https://www.4elements.com/blog/read/creating_your_first_angular_app_basics | CC-MAIN-2019-18 | refinedweb | 1,854 | 53.92 |
Created on 2003-11-21 06:29 by joshhoyt, last changed 2008-02-05 04:13 by gvanrossum. This issue is now closed.
This patch adds a call to PyErr_CheckSignals to
SRE_MATCH so that signal handlers can be invoked during
long regular expression matches. It also adds a new
error return value indicating that an exception
occurred in a signal handler during the match, allowing
exceptions in the signal handler to propagate up to the
main loop.
Rationale:
Regular expressions can run away inside of the C code.
There is no way for Python code to stop the C code from
running away, so we attempted to use setrlimit to
interrupt the process when the CPU usage exceeded a limit.
When the signal was received, the signal function was
triggered. The sre code does not allow the main loop to
run, so the triggered handlers were not called until
the regular expression finished, if ever. This
behaviour makes the interruption by the signal useless
for the purposes of constraining the running time of
regular expression matches.
I am unsure whether the PyErr_CheckSignals is
lightweight enough to be called inside of the for loop
in SRE_MATCH, so I took the conservative approach and
only checked on recursion or match invocation. I
believe that the performance hit from this check would
not be prohibitive inside of the loop, since
PyErr_CheckSignals does very little work unless there
is a signal to handle.
Logged In: YES
user_id=21627
Can you give an example for a SRE matching that is so slow
that the user may press Ctrl-C?
Logged In: YES
user_id=21627
Fredrik, what do you think about this patch?
here is an example (from)
python -c 'import re; num=25; r=re.compile("a?"*num+"a"*num);
r.match("a"*num)'
At work I have seen a real world case of a regular expression which ran
for minutes rendering the application unresponsive. We would have been
glad to be able to interrupt the regular expression engine and getting a
traceback.
I'm attaching a working patch against 2.5.1 and a short test program.
#! /usr/bin/env python
import signal
import re
import time
def main():
num=28 # need more than 60s on a 2.4Ghz core 2
r=re.compile("a?"*num+"a"*num)
signal.signal(signal.SIGALRM, signal.default_int_handler)
signal.alarm(1)
stime = time.time()
try:
r.match("a"*num)
except KeyboardInterrupt:
assert time.time()-stime<3
else:
raise RuntimeError("no keyboard interrupt")
if __name__=='__main__':
main()
hm. just noticed that calling PyErr_CheckSignals slows down regular
expression matching considerably (50%).
I'm adding another patch, which only checks every 4096th iteration for
signals.
Couldn't apply cleanly the patch, as it appears to be a diff in other
format.
Anyway, applied it by hand, and now I attach the correct svn diff.
The test cases run ok with this change, and the problem is solved.
Regarding the delay introduced, I tested it with:
$ ./python timeit.py -s "import re;r=re.compile('a?a?a?a?a?aaaaa')"
"r.match('aaaaa')"
Trunk:
100000 loops, best of 3: 5.4 usec per loop
100000 loops, best of 3: 5.32 usec per loop
100000 loops, best of 3: 5.41 usec per loop
Patch applied:
100000 loops, best of 3: 7.28 usec per loop
100000 loops, best of 3: 6.79 usec per loop
100000 loops, best of 3: 7.00 usec per loop
I don't like that. Anyway, I do NOT trust for timing the system where
I'm making the timing, so you may get different results.
Suggestions?
./python Lib/timeit.py -n 1000000 -s "import
re;r=re.compile('a?a?a?a?a?aaaaa')" "r.match('aaaaa')" gives me for
Trunk:
1000000 loops, best of 3: 3.02 usec per loop
1000000 loops, best of 3: 2.99 usec per loop
1000000 loops, best of 3: 3.01 usec per loop
Patched:
1000000 loops, best of 3: 3.04 usec per loop
1000000 loops, best of 3: 3.04 usec per loop
1000000 loops, best of 3: 3.14 usec per loop
which would be ok, I guess.
(This is on a 64bit debian testing with gcc 4.2.3).
Can you test with the following:
if ((0 == (sigcount & 0xffffffff)) && PyErr_CheckSignals())
(i.e. the code will (nearly) not even call PyErr_CheckSignals).
I guess this is some c compiler optimization issue (seems like mine does
a better job at optimizing :)
Mind if I assign this to Facundo? Facundo, if you wish to pass this on,
just unassign it.
Retried it in a platform where I trust timing, and it proved ok.
So, problem solved, no performance impact, all tests pass ok. Commited
in r59862.
Thank you all!
I think this is worth backporting to 2.5.2. This and r60054 are the
*only* differences between _sre.c in 2.5.2 and 2.6.
Backported to 2.5.2 as r60576. (The other deltas are not backported.) | http://bugs.python.org/issue846388 | CC-MAIN-2017-04 | refinedweb | 832 | 76.62 |
I've written a test that analyzes links from a webpage and then clicks on each of them in a loop and then returns to the main page. However, every iteration repeatedly parses the entire webpage and overwrites the links array. However, only one link is required per iteration. I understand that this is inefficient. How can I optimize this?
I tried to parse the links only once and then loop them through. After the first iteration, it returns (to the main page) and tries to click on the second link, but it's not interactive (I think it's because of the web elements that are stored in the links array and change each time, though) You to switch page).
def setUp(self): self.driver = webdriver.Chrome() self.driver.get('') def test_01(self): driver = self.driver links = () time.sleep(3) links = driver.find_elements_by_css_selector("a") for i in range(len(links)): links = driver.find_elements_by_css_selector("a") links(i).click() driver.get('') time.sleep(3)
I expect a more efficient solution. | https://proxies-free.com/tag/optimization/ | CC-MAIN-2019-39 | refinedweb | 169 | 60.11 |
Meeting: XML Processing Model WG Date: 8 Mar 2007 Agenda: Meeting number: 58, T-minus 34 weeks Chair: Norm Scribe: Norm ScribeNick: Norm Roll: Norm, Rui, Andrew, Henry, Murray, Richard, Alex, Michael Regrets: Alessandro, Mohamed, Paul # Administrivia Topic: Accept this agenda? -> Accepted. Topic: Accept minutes from the previous meeting? -> Accepted. Topic: Next meeting: telcon 15 Mar 2007 Murray gives regrets # Technical agenda Topic: Review of the 28 Feb 2007 Editor's draft Henry and I reviewed it in person. Murray: I found the options and parameters wording a bit confusing. Henry: I remain unsure whether removing the distinct name for containers or language constructs and calling everything a step is the right thing or not. I can see both sides. Does anyone else have any concerns? Richard: I looked at the options and parameters alternatives, but didn't read the rest. Alex: We need to say something about in-scope namespaces to the parameters. Norm: I guess we'll come back to this a week from today. Topic: Consideration of options and parameters Norm: Murray, what did you find different than you expected? Murray: I thought options were like command line options. They're like an INI file as opposed to a command line options. Norm: Tries to explain...fails. Henry: I think the odd case is XSLT. We should think about things like delete-matching. It's absolutely the case that the options are passed to the step. What I don't understand is how to describe parameters. Richard: The difference as far as I understood it is that both are pairs of names/values. There's a set of fixed, named arguments that a step has (those are the options). Some kinds of steps can also take an arbitrary other mapping from names to values and those are the parameters. Pipeline implementors don't know in advance what parameters a step will have, but they do know what options they can take. In fact, they have to map those options from the XProc file to the implementation mechanism for the options. Henry: Equivalently, the options supply values that are in the interface to the step implementation. Whereas parameters are all going to be packed up and handed as one "argument" in the interface. Murray: I'm not entirely sure if I agree with Richard and Henry. It seems way to complicated, but it may be accurate. What I'd like to ask is what's wrong with the view that it's like command line options vs. an INI file. Richard: If I was going to do that, I'd have said it was more like the distinction between command line arguments and the environment. It'll ignore the extra environment variables but complain if it gets extra command line arguments. Norm: I wonder if we want to do away with p:parameter and just pass parameters to XSLT as an input? Henry: No, not really. Because we want to be able to set parameters on the command line to the pipeline. Norm: I think the editor should just take another wack at it. Henry: Be up-front about it and say that this mechanism is really only for the XSLT component. Alex: XQuery will also be in that camp. Michael: I wanted to hear the end of what Murray said... Murray: A thought: we could have on the command line that you could set a name/value pair and you could re-use that option. The processor is expected to create an entity with that name and value. Then the pipeline author could reference the entity. Richard: That would seem to imply that the pipeline document would have to be re-parsed each time. Michael: XML processors are not required to expand entities. So you could leave the entity references in the data structure. Providing a different replacement text for magic entities of the sort that Murray describes doesn't reqiure reparsing. Murray: We don't have a variables yet. Henry: We have pipeline parameters. Murray: What I'm talking about is that within the pipeline document itself we don't have a macro mechanism. Henry: I thought it was the case that we said that for XPaths, the parameters were available to discharge variable references in XPath. Richard: I think you can use parameters scoped to group. Michael: The one difference between variables and parameters is that the pipeline author cannot know what a variable is if it's just sait. Alex: Syntactically, default values are allowed, but that's not clear in the draft. Norm: I think we did say that the in-scope parameters would be available as variable references in XPath expressions. Henry: In 6.7.1 the syntax for declaring parameters doesn't include a mechanism for setting the default. Murray: But we did discover that we're using parameters in a different way. Alex: We've discussed structured parameters in email, but we're not doing that in V1, right? Richard: Wait, why do you need to declare parameters? Richard: In p:group, option doesn't make much sense. You only want parameters. Some discussion of whether it makes sense to declare parameters... Henry: Being able to define defaults for parameters is valuable. Murray: There's a defined set of options for any given component. But when it comes to parameters, they're open ended. Alex: For XSLT, we'd say parameter name="*" which would tell tools that this component takes any number of parameters. I think the right semantic is that you can set any parameter on any step. That would be legal. But that wouldn't be the case. Henry: The place I see defaults happening is on the p:pipeline or on the p:group. If I don't pass them in, they get default values so that they can be used or imported. Henry: What's the right thing to say here? It seems to me that those are pipeline options that are going to be imported as parameters to some styleshete. Norm: I think that just invites confusion. Murray: You can have an option on the command line that sets some parameter. Setting a parameter on the command line overrides the setting inside the pipeline. Henry: But that makes it seem like pipelines have options and pipelines. Norm: I don't think it makes sense for p:pipelines to have options. Henry: I think it's sensible. It's a little odd to think of it as having parameters. Pressing the Unix analogy further, it's a bit like -Dx=y to the C compiler. Alex: If we go look at things people are used to like parameters to XSLT, once you start using them, the values you set can't be changed from the command line, that only happens at the top level. Norm describes what he thinks. Henry: This means that p:pipeline only has parameters. Norm: It's a bug in the current spec that we don't allow implementations to specify values for top-level p:parameters. Richard: Pipelines are supposed to be components. If XSLT has parameters and options then I think it should be possible to make a pipeline a completely transparent wrapper around XSLT. So why can't p:pipeline have parameters and options? Henry: Options are things which control variability that's intrinsic to the nature of the step. Regardless of any contingent properties of any execution of a step, it always needs options. Parameters are things that are relevant to what conditionalizes the step. So if you had a step that produced a constant output, then it could only have options. At the other end of the scale, the pipeline compound step has no semantics of its own, it only makes sense for it to have parameters. Alex: There's a simpler way to think about this: what would a pipeline option be? I can't think of a single option that we need for a pipeline. Richard: There aren't any things that are intrinsic to all pipelines, but when you define a pipeline you are both declaring it and using it. Once you've declared it, that particular pipeline can only accept certain particular arguments. Richard: I want a pipeline that's exactly like the XSLT step except that it takes the name of the stylesheet as an option. So you always need a "stylesheet URI" option but you may also want arbitrary parameters. Norm: I'd do that with a required parameter. Richard: What about name conflicts? Now if I want to have a parameter to my stylesheet with the same name, I can't do it. Norm asks about how to refer to both options and parameters. Richard describes how shell scripts avoid this problem. It boils down to maybe we should just use namespaces after all. Henry: But I don't want people to have to declare more namespaces than they read. Richard: We could extend XPath with an an option() function to access the options. Norm: Yes, I thought of that too. ADJOURNED. | http://www.w3.org/XML/XProc/2007/03/08-minutes.html | CC-MAIN-2015-27 | refinedweb | 1,512 | 74.69 |
This section describes how to determine which version of the Shell or common controls DLLs your application is running on and how to target your application for a specific version.
All but a handful of the programming elements discussed in the Shell and common controls documentation are contained in three DLLs: Comctl32.dll, Shell32.dll, and Shlwapi.dll. Because of ongoing enhancements, different versions of these DLLs implement different features. Throughout the Shell and common controls reference documentation, each programming element is given with a version number. This version number indicates that the programming element was first implemented in that version and will also be found in all subsequent versions of the DLL. If no version number is specified, the programming element is implemented in all versions. The following table outlines the different DLL versions and how they were distributed dating back to Microsoft Internet Explorer 3.0, Microsoft Windows 95, and Microsoft Windows NT 4.0.
Note 1: The 4.00 versions of Shell32.dll and Comctl32.dll are found on the original versions of Windows 95 and Windows NT 4.0. New versions of Commctl.dll were shipped with all Internet Explorer releases. Shlwapi.dll shipped with Internet Explorer 4.0, so its initial version number here is 4.71. The Shell was not updated with the Internet Explorer 3.0 release, so Shell32.dll does not have a version 4.70. While Shell32.dll versions 4.71 and 4.72 were shipped with the corresponding Internet Explorer releases, they were not necessarily installed (see note 2). For subsequent releases, the version numbers for the three DLLs are not identical. In general, you should assume that all three DLLs may have different version numbers, and test each one separately.. No other versions of Internet Explorer update Shell32.dll..
Note 4: ComCtl32.dll version 6 is not redistributable. If you want your application to use ComCtl32.dll version 6, you must add an application manifest that indicates that version 6 should be used if it is available.
Starting with version 4.71, the Shell and common controls DLLs, among others, began exporting DllGetVersion. This function can be called by an application to determine which DLL version is present on the system. It returns a structure that contains version information.
For systems. This structure contains the hotfix number that identifies the service pack and provides a more robust way to compare version numbers than DLLVERSIONINFO. Because the first member of DLLVERSIONINFO2 is a DLLVERSIONINFO structure, the new structure is backward-compatible.
The following sample function the ullVersion member to compare versions, build numbers, and service pack releases. The MAKEDLLVERULL macro simplifies the task of comparing these values to those in ullVersion.
#define PACKVERSION(major,minor) MAKELONG(minor,major)
DWORD GetDll.cbSize = sizeof(dvi);
hr = (*pDllGetVersion)(&dvi);
if(SUCCEEDED(hr))
{
dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion);
}
}
FreeLibrary(hinstDll);
}
return dwVersion;
}
The following code example illustrates how you can use GetDllVersion to test if Comctl32.dll is version 4.71 or later.
if(GetDllVersion(TEXT("comctl32.dll")) >= PACKVERSION(4,71))
{
//Proceed.
}
else
{
// Use an alternate approach for older DLL versions.
}
To ensure that your application is compatible with different targeted versions of Comctl32.dll and Shell32.dll, a version macro was added to the header files. This macro is used to define, exclude, or redefine certain definitions for different versions of the DLL. The macro name is _WIN32_IE, and this macro in your project, it is automatically defined as 0x0500. To define a different value, you can add the following to the compiler directives in your make file; substitute the desired version number for 0x0400.
/D _WIN32_IE=0x0400
Another method is to add a line similar to the following in your source code before including the Shell and Common Control header files; substitute the desired version number for 0x0400.
#define _WIN32_IE 0x0400
#include <commctrl.h> | http://msdn.microsoft.com/en-us/library/bb776779(VS.85).aspx | crawl-002 | refinedweb | 643 | 51.65 |
.
Now you have two components. Then three. Then four. Eventually you’ll have X number of components, each with its own complexity. The good stuff.
Components let you isolate parts of your large application so you can have a separation of concerns, and if anything breaks you can easily identify where things went wrong. Regardless, components are also meant to be reusable: you want to avoid duplicated logic, and you also want to keep watch for over-abstraction. Reusing components comes with the Don’t Repeat Yourself (Benefits), but it isn’t carved in stone as taught in Goodbye, clean code.
More often than not, components will have some data or functionality that another component needs. This could be to avoid duplication, or to keep the components in synchronization.
Whatever the reason, some components might need to communicate, and the way to do this in React is through props.
Components and props
Components are like JavaScript functions that can accept any number of arguments.
Ideally, a function’s arguments are used for its operation.
With components, these arguments are called props. Props (short for properties) are object arguments. An
ErrorMessage can look something like:
function ErrorMessage(props) { return ( <div className="error-message"> <h1> Something went wrong </h1> <p> {props.message} </p> </div> ) }
Because
ErrorMessage will be reused many times across the app, it will pass a different
message in its props. But this is just one component, and this example doesn’t even tell where the
message prop came from, which matters.
Prop drilling
React is all about updating the DOM of your application whenever it is absolutely necessary. To do this effectively, React uses a virtual DOM (VDOM) to update the actual DOM through a process known as reconciliation. Let’s take a simple dashboard app as an example:
function App() { const [title, setTitle] = React.useState("Home"); const [username, setUsername] = React.useState("John Doe"); const [activeProfileId, setActiveProfileId] = React.useState("A1B2C3"); return ( <div className="app"> <h1>Welcome, {username}</h1> <Dashboard {...{ activeProfileId, title, username}}/> </div> ) }
The
App component has three
states:
activeProfileId,
title and
username. The
states have default values and they are passed down to the
Dashboard component.
function Dashboard({activeProfileId, title, username}) { return ( <div className="dashboard"> <SideNav {...{activeProfileId}}/> <Main {...{title, username}}/> </div> ) }
The
Dashboard component receives the
props and immediately (without using them) dispatches them to subsequent components
SideNav and
Main down the tree.
function SideNav({activeProfileId}) { return ( <nav className="side-nav"> <h1>ID: {activeProfileId}</h1> </nav> ) } function Main({title, username}) { return ( <div className="main-content"> <TopNav {...{title}}/> <Page {...{username}}/> </div> ) }
SideNav immediately consumes the
activeProfileId prop, and
Main continues to relay the
title and
username props further down the tree.
function TopNav({title}) { return ( <nav className="top-nav"> <h1> {title} </h1> </nav> ) } function Page({username}) { return <Profile {...{username}}/> }
TopNav uses the
title props, and
Page sends
username down, again, to
Profile:
function Profile({username}) { return <h1>{username}</h1> }
Finally,
Profile uses the
username props.
Passing props down in this way isn’t technically wrong and is, in fact, the default way to do it. This pattern is known as Prop-drilling.
A diagram will do justice to better illustrate the component hierarchy.
)
App is the initiating prop-passing component and while
Apps states:
title ,
username and
activeProfileId was passed down as
props, the components that needed those
props were:
SideNav,
TopNav and
Profile but we had to go through intermediary components:
Dashboard,
Main, and
Page that merely relayed the props.
Traversing from
App →
Dashboard to
SideNav is relatively easy compared to
App →
Dashboard →
Main →
Page →
Profile.
Along the chain, anything could go wrong: there could be a typo, refactoring could occur in the intermediary components, possible mutation of these
props could happen. And if we remove just one of the intermediary components, things will fall apart.
Apart from all the de-merits mentioned, there’s also a case of re-rendering. Because of the way React rendering works, those intermediary components will also be forced to re-render which can lead to a performance drain of your app.
To understand how React handles rendering, A (mostly) Complete Guide to React Rendering Behavior by Mark Erikson (Redux Maintainer) is a must read.
To solve for the problems attached with prop-drilling came Context.
Context to the rescue
According to the React docs, context provides a way to pass data through the component tree without having to pass props down manually at every level.
The old Context was tedious to use with class components because you had to use the render prop pattern, and more so, it was marked unstable/experimental all the while.
But with the advent of Hooks and specifically the
useContext Hook, things are relatively simple today.
After you’ve orchestrated a context, using it is as simple as:
const userDetails = useContext(UserContext);
Check out How (and When) to use React’s new Context API to get started.
Creating a context is straightforward, too. Kent has a bevy of articles and pattern on how to use context and using it effectively. I encourage you to read those articles.
One of my use cases for context is storing the user profile and accessing it wherever I need it.
Apart from that, I can also keep a shared-state in sync. Let’s build a dashboard app again.
The component tree will look something like this:
This looks something like the prop-drilling component tree above, except that the
username is the only consideration here.
If you take a look at the diagram, you might notice a few things:
- The receiving components are
TopNavand
Profile
- The state the receiving components need is in
UserProvider
- All child components of
UserProviderhave direct access to the
usernamestate, including
TopNav,
Page, and
Profile
Direct access means that even though
Page is a parent component to
Profile, it doesn’t have to be an intermediary component anymore.
import React, { createContext, useState } from "react"; const UserContext = createContext(undefined); const UserDispatchContext = createContext(undefined); function UserProvider({ children }) { const [userDetails, setUserDetails] = useState({ username: "John Doe" }); return ( <UserContext.Provider value={userDetails}> <UserDispatchContext.Provider value={setUserDetails}> {children} </UserDispatchContext.Provider> </UserContext.Provider> ); } export { UserProvider, UserContext, UserDispatchContext };
The state variables
userDetails and
setUserDetails are exposed through
UserContext and
UserDispatchContext providers with the
value prop.
Wrapping
UserProvider, as in
Main below, will expose the
values of
UserContext and
UserDispatchContext to components down the tree:
function Main() { return ( <div className="dashboardContent"> <UserProvider> <TopNav /> <Page /> </UserProvider> </div> ); }
In
Profile,
username can be used like so:
function Profile() { const userDetails = React.useContext(UserContext); const setUserDetails = useContext(UserDispatchContext); return <h1> {userDetails.username} </h1>; }
setUserDetails is a function as de-structured. When using it to update
userDetails it expects an object with a
username:
const [userDetails, setUserDetails] = useState({ username: "John Doe" });
context-nav-profile-example
context-nav-profile-example by adebiyial using react, react-dom, react-scripts
Global shared state with context
Another use case of context is that it can act as a global state mechanism as we have between
TopNav and
Profile. Updating the
username in
Profile immediately updates the shared state in
UserProvider providing a mechanism for global state management.
As with prop-drilling, there can be some performance drain with context because whenever it renders, its child component(s) also render. One way to minimize the rendering is to keep Context as close to where it’s been used as we’ve done with
UserProvider. There’s no reason why we couldn’t position it anywhere high up the component tree, but it’d be less effective.
What context is and isn’t
We’ve already mentioned the React docs definition of Context: Context provides a way to pass data through the component tree without having to pass props down manually at every level.
By this definition alone, it is safe to say that context helps or is meant to solve the props-drilling problem. However, many have orchestrated a state management mechanism from context because by default it is merely another React component – with the added benefit that it helps with prop-drilling.
There is nothing wrong with using context for state management, but keep in mind that this is an indirect way to use it because it isn’t a dedicated state management tool like Redux, and it doesn’t come with sensible defaults.
Moreover, its simplicity is a virtue that should not be taken for granted.
Now that we’ve mentioned what xontext is (the prop-drilling messiah) and what it isn’t (a state management tool), it becomes fair to initiate the salient conversation about whether to use context or Redux, or even if Redux is dead because of context.
Redux or Context
Does context take away Redux? No. It doesn’t. As we have seen, they are two different tools and comparing them is often an indirect consequence of the misconception of what they are.
Context can be orchestrated (with
useReducers as Robin wrote in his article How to create Redux with React Hooks?) to act as a state management tool, but that wasn’t the intention and you’d have to a little bit of work to match your taste.
While you’re at that, remember there are already a lot of state management tools out there that work well and will ease your troubles.
In my experience with Redux, it was relatively complex for something that is easier to solve today with context. But keep in mind, this is just where their paths cross: prop-drilling and global state management. Redux is much more than this.
As Dan pointed out, you might not need Redux and even if you do, you’d know when you need it. And not knowing when to add another context is one of the pitfall of using context.
In a just and fair world, Redux and context shouldn’t be two words/concepts stringed together with “vs”, and instead should be considered things that work with each other.
I’d say use Redux for your complex global state management and context for prop-drilling. If you think about what the world is today, I bet we can use some co-existence.
Conclusion
The takeaway here is that:
- Context is meant for prop-drilling
- If you’d use Context for some global state management, be prudent with it
- If you fear you can’t be prudent with Context, reach out for Redux
- Redux can be used independent of React
- Redux is not the only state management tool out there
Resources
React’s new Context API
Prop Drilling
How to use React Context effectively
How to optimize your context value
React State Hooks: useReducer, useState, useContext
That React Component Right Under Your Context Provider Should Probably Use React.memo
Fix the slow render before you fix the re-render
React, Redux, and Context Behavior. | https://blog.logrocket.com/a-deep-dive-into-react-context-api/ | CC-MAIN-2020-40 | refinedweb | 1,790 | 51.58 |
Think about it: the day before the newsletter comes out, you get an e-mail that says, "Please write an article, I need it last week." There's only one solution—write about what I'm currently doing. OK, I exaggerate. Michelle isn't the slave driver I've depicted her as, and I'm actually happy to write an article. Also, the article isn't about what I'm doing right now, but about something I did last week.
There's a small detail in the application kit that's a useful feature but also something that you often have to work around—the "single launch" launch mode.
When you try to launch a second copy of a
B_SINGLE_LAUNCH application
that's already running, constructing the
BApplication object for the
second copy fails, and the first copy gets notified (see your favorite
BeBook for details on that notification mechanism). The problem is that
the second copy you try to launch gets terminated instantly, which can be
annoying if you launched it from a shell script (or, for that matter, any
environment where the termination of an application and/or its return
code has a meaning, such as a makefile or a perforce command (check
perforce at they have a BeOS client).
There's a reasonably easy solution that doesn't involve using a separate binary (Hi, Pavel!), but detects that another copy is already running, sends this other copy a message, and waits for a synchronous reply. Here's a code snippet that shows how to do it:
#include <Application.h> #include <stdio.h> #include <string.h> #include <stdlib.h> class
App:public
BApplication{ public:
App(status_t*); void
ArgvReceived(int32,char**); void
MessageReceived(
BMessage*); };
App::
App(status_t*
r) :
BApplication("application/x-vnd.be.mul2",
r) {} int32
DoSomething(const char*
c) { return 2*strtol(
c,
NULL,0); } void
App::
ArgvReceived(int32
argc,char**
argv) { if (
IsLaunching()) { printf("%ld\n",
DoSomething(
argv[1]));
Quit(); } } void
App::
MessageReceived(
BMessage*
m) { switch(
m->
what) { case ' mul' : {
BMessage
r;
r.
AddInt32("result",
DoSomething(
m->
FindString("data")));
m->
SendReply(&
r); } default : {
BApplication::
MessageReceived(
m); break; } } } int main(int
argc, char**
argv) { status_t
ret;
App
app(&
ret); if (
ret==
B_ALREADY_RUNNING) { if (
argc>1) {
BMessenger
msgr("application/x-vnd.be.mul2");
BMessage
m(' mul');
BMessage
r;
m.
AddString("data",
argv[1]);
msgr.
SendMessage(&
m,&
r); printf("%ld\n",
r.
FindInt32("result")); } } else {
app.
Run(); } exit(0); }
The core of this technique is to check whether there's already another
app with the same signature. The best way is to try to create a
BApplication, and check whether it fails. That avoids a number of race
conditions. When it fails, get a
BMessenger to the existing application
and use it to communicate with the application that's already running.
Here's a quick little sample code ditty about bending a
BFilePanel to
suit your (I hope not evil) needs. We've covered this subject in past
articles, but never in combination with (drum roll, please) The Game Kit!
Get the thrilling sample code for this article at <>.
I've tried to comment the source extensively, but feel free to e-mail me if you have any questions.
Submitted for your approval is the
SndFilePanel class, which lets you
peruse your file system for sound files as well as preview them, using
the super-easy
BFileGameSound class.
BFileGameSound is the ticket if you
need to play a sound file quickly and painlessly. I've also provided a
simple
BApplication-based test harness to let you try out
SndFilePanel.
Class
SndFilePanel is mostly a standard
derivation of
BFilePanel. I've
mixed in
BHandler via multiple inheritance so I can implement
MessageReceived(). In
MessageReceived,
I handle events generated by the
BButton added to the file panel to allow playing and stopping the
BFileGameSound. For more info on fiddling with
BFilePanel derivatives,
consult Developers' Workshop: Translation Kit Part 1: File Panel Fun.
Using
BFileGameSound is easy, as I hope you can see from the source. A
BFileGameSound instance is created in
SndFilePanel::SelectionChanged(),
upon finding a suitable file to preview. Playing and stopping the sound
is handled in response to the appropriate message in
SndFilePanel::MessageReceived(). For more info on using
BFileGameSound,
consult Be Engineering Insights: Farewell BSound and BSoundFile (All Hail
BGameSound and BMediaFile)
This is the column I wanted to write before we went to Palm Springs for Demo 2000. Demo is an industry conference with the theme of "more demo, less talk." This could be a reaction to the talking heads and PowerPoint slides of other venues, or it may be just marketing 101: distinguish yourself from the pack. In any event, we were allotted eight minutes of fame to demonstrate four appliances. Two of them, the Clipper and the WebPad, are in imminent danger of shipping in the short term. The other two, the music center and the touch pad kitchen appliance, represent the more distant future. Our eight minutes stretched to ten, as the producers must have foreseen, but the audience didn't object to the overtime and rewarded us with warm applause. I should mention that a major theme of the conference was the emergence of appliances, evidence that the Internet is no longer viewed solely through the lens of the PC.
That was last week. This week, I'll sketch out a home entertainment application developed by Steve Sakoman, one of our founders, for his family's use. It begins with a DSL connection and a wireless home network based on Proxim devices. Using a 2.4 GHz carrier, one gets a wireless Ethernet at 1.6 Mbits/s. One PC on the network acts as a dedicated device, taking tracks from CDs to make a compilation of 5,000 songs stored as MP3 files. Then, any client on the network, wireless in this case, can stream songs from the server, anywhere in the house. This sounds fairly simple and in fact it is. The reward is music on demand -- no more fiddling with CDs or losing them.
One interesting point is that you can do this with PCs and only PCs on the network, or you can do it without any PC at all. You could do it with WebPads and Clippers, or a mixture of both, and be able to browse the Web to your heart's content, do your e-mail, while playing your favorite songs or downloading new ones. In other words, this isn't an either/or situation.
I won't play the "peaceful coexistence" song again but the question of whether a PC or an appliance better suits your needs has only one clear, unambiguous answer: it depends. It depends who's using it and for what. The PC offers the charm of "everything on it" generality, with the attending burdens of complexity and fragility. The appliance does fewer things, but in a better, simpler, more agile, and often less expensive way. These days, when I see a receiver on the shelves at Fry's, I imagine the next generation model, with an Ethernet connector in the back and a small touch screen in front. | https://www.haiku-os.org/legacy-docs/benewsletter/Issue5-7.html | CC-MAIN-2017-47 | refinedweb | 1,186 | 62.38 |
Been a long time, I've got several articles under constructions for quite some times … This one wasn't planified, I just think I can share some basic but nice C++.
C++ is huge language, it's probably impossible to explore all the features in a lifetime, and trying to apprehend what theses features can bring you is probably out of reach for a normal human being. But, we can sometimes grasp some interesting ideas.
My approach of C++ is not traditional, in the sense that I'm not using C++ as an object oriented language, more like a higher-level C, objects and classes are just one of the interesting aspects. Anyway, I'll use some object here, but without inheritance and all the buzz around object design.
Power to the destructor
As in any sane language, when closing a scope, variables local to that scope dies. But, in C++ some of these local variables can be direct objects (not pointers to object like in Java) and thus, when a variable dies, the object must be destroy. This happen transparently and can easily be coded:
# include <iostream> struct S { int id; S(int i) : id(i) { std::cout << "Building S(" << id << ")" << std::endl; } ~S() { std::cout << "Destroying S(" << id << ")" << std::endl; } }; int main(void) { // Building in main std::cout << ">> main <<" << std::endl; S s1(1); { // Sub context std::cout << ">>> Sub context <<<" << std::endl; S s2(2); std::cout << ">>> Sub context last statement <<<" << std::endl; } std::cout << ">> main last statement <<" << std::endl; return 0; }
Running this piece of code shows when destructors are implicitly called.
>> main << Building S(1) >>> Sub context <<< Building S(2) >>> Sub context last statement <<< Destroying S(2) >> main last statement << Destroying S(1)
It's a classic C++ example, and if you're not familiar with this, you should start over your learning of C++ …
The real question is: what can we do with that ? Things, a lot of things …
RAIIC++ programmers should be familiar with a concept called RAII: Resource Acquisition Is Initialisation. cppreference describes RAII:
Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource (allocated memory, thread of execution, open socket, open file, locked mutex, database connection—anything that exists in limited supply) to the lifetime of an object.
You can find classical examples of RAII in STL, one of the most interesting is the std::lock_guard class. In short, at creation it locks a mutex and unlocks it when destroyed.
struct counter { unsigned c; std::mutex m; void incr() { // guard lock m when constructed std::lock_guard<std::mutex> guard(m);
c += 1; // guard get destroyed and unlock m } };
Using lock-guards greatly improves and simplifies algorithm using lock. It also provides a strong guarantee that mutexes are always unlocked when leaving a function or code block, even in the presence of exceptions. This example demonstrate how lock-guards can simplify code using mutexes, using lock-guards avoid the need of adding an unlock statement whenever you want to leave your code.
template<typename T> struct list { struct node { T data; node *next; node(): next(nullptr) {} node(T x, node *n) : data(x), next(n) {} }; node *head; std::mutex mutex; list() : head(new node()) {} /* using lock_guard */ bool member(T x) { std::lock_guard<std::mutex> guard(mutex); for (auto cur = head; cur->next; cur = cur->next) { if (cur->next->data == x) return true; } return false; } /* using explicit lock/unlock */ bool member_old(T x) { mutex.lock(); for (auto cur = head; cur->next; cur = cur->next) { if (cur->next->data == x) { mutex.unlock(); return true; } } mutex.unlock(); return false; } /* using lock_guard */ bool insert(T x) { std::lock_guard<std::mutex> guard(mutex); auto cur = head; for (; cur->next && cur->next->data < x; cur = cur->next) continue; if (cur->next && cur->next->data == x) return false; cur->next = new node(x, cur->next); return true; } /* using explicit lock/unlock */ bool insert_old(T x) { mutex.lock(); auto cur = head; for (; cur->next && cur->next->data < x; cur = cur->next) continue; if (cur->next && cur->next->data == x) { mutex.unlock(); return false; } cur->next = new node(x, cur->next); mutex.unlock(); return true; } };
Lock-guards provide coding comfort similar to synchronized blocks in Java or try-finally constructions.
The next example demonstrates another use case. The idea is to provide a simple almost non-intrusive benchmarking object. Here is the class definition:
#include <chrono> using std::chrono::duration_cast; using std::chrono::nanoseconds; using std::chrono::steady_clock; struct scoped_timer { scoped_timer(double& s) : seconds(s), t0(steady_clock::now()) {} ~scoped_timer() { steady_clock::time_point t1 = steady_clock::now(); std::chrono::duration<double> diff = t1 - t0; seconds = diff.count(); } double& seconds; steady_clock::time_point t0; };
Here is simple code usage:
double seconds; { scoped_timer clock(seconds); std::cout << "benched code blocks" << std::endl; } std::cout << "elapsed time: " << seconds << "s" << std::endl;
Once again the trick is to take advantage of the pair constructor/destructor of the object. The scoped_timer get a reference on a double and when destroyed push the time difference in this reference when destroyed.
More ?
C++ coding exercise: we want a something that behaves like the assert construction with the ability to emit a message. The use case looks like this:
log_assert(x > 0) << "hello " << x;
If the condition is true (in our case x is positive) nothings happen, but if it's false, the message gets be printed and the program exits.
Looks easy ? If you write log_assert as a function, you'll get exactly what you don't want: the message get printed only if you don't leave the program …
The expression log_assert(b) can be a call to a constructor, you see the idea now ?
As a hint, let's see what happen with our first class example if you just call the constructor without naming the resulting object:
As a hint, let's see what happen with our first class example if you just call the constructor without naming the resulting object:
int main(void) { std::cout << ">> main <<" << std::endl; S(1); std::cout << ">> main last statement <<" << std::endl; return 0; }
The output:
>> main << Building S(1) Destroying S(1) >> main last statement <<
Yes, we build the object and it get destroyed directly ! In fact, the object is created for the statement only, and thus get destroyed on the semi-colon.
So, all we need is to handle the leave on assertion in the destructor and add some overloading on the operator <<. Here is a possible implementation:
struct log_assert { bool cond; log_assert(bool c) : cond(c) {} ~log_assert() { if (cond) return; std::clog << std::endl; abort(); } template<typename T> log_assert& operator<< (const T& x) { if (!cond) std::clog << x; return *this; } };
There's probably better way to do that, but it will be enough for now …
And this why …There's a classical trap related to this pattern when using RAII resources. A good example can be found with the std::async construction. std::async provides a lazy parallel evaluation of a function. The common mistake arises when you use it to launch a computation and don't need to wait for completion explicitly, like in the following code sample:
void run(unsigned int x, unsigned int len) { for (unsigned int i = 0; i < len; ++i) printf(">> %u - %u <<\n", x, i); } int main(void) { std::async(run, 1, 100); std::async(run, 2, 100); }
The two std::async statements are not run in parallel, if you want parallelism, you need to write it that way:
int main(void) { auto w1 = std::async(run, 1, 100); auto w2 = std::async(run, 2, 100); }
On destruction the object returned by std::async wait for the completion of the submitted task, so if you don't keep alive the returned object, the execution is not parallel since it waits for the completion of the first task before passing to the second statement.
Once again, it's all about understanding when things get destroyed …
ConclusionI've just played with very basic C++ notions, but there's a lot of applications. Understanding the dependencies and order of destruction of objects is important in C++.
RAII is almost behind smart pointers, an important concept in modern C++ programming. Even if the concrete implementation of a smart pointer class is a little bit tricky, the basic concept (releasing memory when the smart pointer dies) is easy to get once you understand RAII. Among all C++ features, the automatic invocation of destructors when objects go out of scope is probably one of the most useful. | http://pragmatic-programming.blogspot.com/2016/10/ | CC-MAIN-2018-05 | refinedweb | 1,415 | 51.11 |
With the availability of .Net Core RC2 and ASP.NET Core RC2 we are pleased to announce an update to the WCF Connected Service Preview for ASP.NET 5 Visual Studio extension tool for generating SOAP service references for clients built on top of WCF for .NET Core RC2. This update brings some improvements to the user experience when navigating through the Connected Service wizard UI and the ability to reuse types defined in the project to which a service reference is being added to and from the project’s references, in addition to several bug fixes.
How to Install the extension
The WCF Connected Service extension can be installed on Visual Studio 2015 and it has the following prerequisites. Please make sure you have prerequisites installed before installing the extension.
Notice that the previous version of the WCF Connected Service extension is not compatible with .NET Core RC2 and once you upgrade it cannot be reinstalled since it is being replaced with this new version of the tool. We strongly encourage you to upgrade to .NET Core RC2 as shown below by searching for “WCF Connected Service” for instance.
How to use the extension
The WCF Connected Service extension is applicable to any projects created with project templates under Visual C# -> .Net Core. This includes Console Application (.Net Core), Class Library (.Net Core) and ASP.NET Core Web Application (.Net Core) as shown in the image below.
Using the ASP.NET Core Web Application project template as an example, I will walk you through the steps to add a reference to a WCF service to the project:
1. In Solution Explorer, right-click on the References item of the project and then click Add Connected Service. The Add Connected Service dialog box appears as shown below.
2. In this dialog, click Microsoft on the left column, then click WCF Service – Preview in the middle column, you might need to scroll down a bit, and finally click on the Configure button. This will bring up Configure WCF Service Reference dialog box. that you want to use for the reference in the Namespace box.
Once a service has been selected you can click Next to visit the Data Type Options and the Client Options pages; alternatively you can click Finish to use default parameter values.
One of the novelties for this release is the ability to reuse types defined in the project and types from assembly and project references. This is a very popular feature in the Visual Studio Add Service Reference tool for traditional .NET Framework projects that was missing in previous releases. This is useful when types used for creating the service you are adding a reference to are available to your project, some of these types might be defined in .NET Core framework assemblies for instance, and in order to avoid type clashing it is necessary to reuse the existing types.
4. Click Finish when you are done.
This will download metadata from the WCF service, generate a reference.cs file for the WCF client proxy, bring in more features in the future. In the meanwhile, we would love to hear about your experience using this tool and any feedback you can provide, including issues you may find, as well as features you would like to see implemented in the tool.
Thank you and happy coding!
Join the conversationAdd Comment
It is good to know that Add Service Reference feature is available in .NET Core. Is it like we also have support for svcutil.exe/ xsd.exe in .NET Core?
Hi Purna!
It is likely we will have a version of svcutil in the future that you can use separately from the connected service. As per xsd.exe I haven’t heard of any plans.
thanks for your feedback,
Hi,
Please! Implement WCF Services in .NET Core, not only the WCF Client Library.
Thanks!
Thanks Francisco. We are looking into this. We are very interested to understand more about what WCF service features you are using, what are your user scenarios and what is your plan of moving to .NET Core. Do you mind to share these with us at?
Great news for me to get the update version, because we had a lot of issues with rc1 in our environment.
Unfortunately now we can’t use a service we depend on anymore.
While trying to add the service an error is thrown while scaffolding code:
Error: An error occurred in the tool. Binding element of type ‘System.ServiceModel.Channels.TransportSecurityBindingElement’ is not supported.
Do you have any advice how to proceed here?
regards
J.
Hi Jorg!
We have identified that the error message you are seeing is incorrect and are preparing an update that will fix it. However, it is likely that the service you are trying to access contains a binding that implements some security features not currently supported in .Net Core. Please stay tuned for the update so you can double check.
thank you!
Where can we provide feedback?
Thanks Kori Francis. We are monitoring the comments of this blog, so you can share your feedback here. Alternatively, you can also share your feedback by opening a new issue at.
when try to add a reference with server uses client certificate authentication: (403) Forbidden.)
The remote server returned an error: (403) Forbidden.
An error occurred in the tool.
Failed to generate service reference.
Hi Andre!
Yes, the service requires authentication in order to download metadata, unfortunately this is a requirement not supported by the connected service.
thank you for your feedback,
Are you tracking this issue? and will it be supported?
Have the following error. In The old add Reference Dialog it Works well.: (401) Unauthorized.)
The remote server returned an error: (401) Unauthorized.
An error occurred in the tool.
Failed to generate service reference.
Hi Helfenstein!
The problem here is that the service requires authentication in order to access the MEX end point. As with the ‘Add Service Reference’ tool for traditional C# projects in Visual Studio, this is a feature not supported by the WCF connected service either. The MEX endpoint must be support anonymous client authentication scheme.
thank you for your input.
When attempting to add a connected service to a 2005 WCF service the Finish button is disabled.
The service is Discovered and appears to have loaded properly.
This in Visual Studio 2015 with the latest .NET Core SDK Preview installed and a fresh ASP.NET Core MVC app. Below is the discoverable URL for the WCF. Name/ReportServer/ReportExecution2005.asmx
Hi Paul!
One of the reasons the Finish button is disabled is because the project cannot compile (project.json dependencies cannot be resolved for instance or contains errors). Can you check whether this is the problem you are seeing?
thanks,
can I add a net.tcp endpoint through this?
Hi Konrad Omeltschenko, if your WCF service has a net.tcp endpoint, yes, this tool will add NetTcpBinding proxy code for you.
When trying to add net.tcp://localhost:8002/ASR/ASRService.svc I get “The service Uri is not valid”. but when I add a http endpoint I get no error
I see what you mean now. You will need to expose mex endpoint of your net.tcp service through http.
I keep getting this when I try to generate the service:
Scaffolding Code …
Attempting to download metadata from ‘’ using WS-Metadata Exchange and HttpGet.
Generating files…
C:\Users\USER\AppData\Local\Temp\WCFConnectedService\2016_Jun_07_17_15_41\Reference.cs
Updating project.json file …
Error:Error: Unable to check out the current file. The file may be read-only or locked, or you may need to check the file out manually.
Hi Nick!
Can you please provide some details about your project? what could be locking the project.json file?
thanks,
The .Net WCF utility allows me to turn off task based generation. Is there a way to turn off task based generation for the Core version?
Hi Mark!
Just to make sure we are all in the same page, you are referring to asynchronous method generation, right? the answer is no, it doesn’t. The generated code follows the async pattern for .Net Core client code. Do you have a compelling scenario where this model is inconvenient?
thanks,
Yes. I am referring to the async method generation. I can make the async method work. The synchronous method is just simpler to implement.
How can i use a local .WSDL file?
Hi Szacsa!
The WCF Connected Service does not allow for generating service proxy code from WSDL files in disk, traditionally this is done using svcutil.exe. As you might know, the underlying engine for the WCF Connected Service is a version of svcutil built for .net core; however, this tool has not been fully tested in isolation so using it directly is not yet supported. You can find the tool somewhere under the Visual Studio extensions folder: %VSINSTALLDIR%\Common\IDE\Extensions\**\svcutil\dotnet-svcutil.exe
Hi Miguell,
I’m running into an issue adding a service using the new dialog
Error: Warning: Unsupported text message encoding version: ‘Soap12 () AddressingNone ()’. It must be ‘Soap11 () AddressingNone ()’ or ‘Soap12 () Addressing10 ()’.
Warning: Endpoint ‘CoreSoapPort220’ at address ‘’ contains one or more bindings not compatible with .Net Core apps, skipping…
Error: No endpoints compatible with .Net Core apps were found.
An error occurred in the tool.
I was able to add a service reference using the service reference wizard in older version of .Net. Is there any plan to add support for this configuration? If not is there a decent work around for this or am I dead in the water? We are excited to use the new framework but this is a show stopper for us.
Thanks
Hi Ian!
I responded to your request on the VS Gallery but will post it here too for others that might be interested:
We are gathering feedback and will certainly consider your request. To provide a workaround we need to do some investigation and will do it as soon as we have a chance, we are currently busy working on the immediate releases coming soon…
thanks again for your feedback
BTW: to make sure we address this issue I have entered a work item in our bug tracking database.
Is there any way to get the plugin to ignore certificate errors? I’m trying to import a service from an embedded device on my LAN, and it has no valid certificate. Or am I forced to use svcutil?
Hi Troels Larsen!
Unfortunately this cannot be done on .net core since configuration files are not supported. We keep a list of feature requests for future improvements and this seems to be a good candidate.
thank you for your feedback.
Hi, I installed and followed the steps above. tried adding the service endpoint below there were errors. Used to work fine.
Error in Data Type Options:
An error occurred while processing project references, recompiling the project might resolve this reference. Not able to click the finish button. Any advise?
Hi Yas80!
We have seen this problem when the project references cannot be loaded because the project has compilation errors or it does not target a .net core framework. I encourage you to upgrade to the new version of the tool which provides a better user experience in particular for this case – – please keep your feedback coming.
thanks,
Hi Miguell, yes, my project is actually created on .net framework 4.6.1 but on Visual Studio 2015 Update 2. So how do I fix this if I am not using .net core project? I use the same add connected service.
currently the only option is to add a .net core target framework to your project (no need to remove the existing target framework). We will address this problem in a future product update.
thanks
Hi,
this tool stop to work for me after project migration from RC1 to RC2. Now I am getting this exception:
Project MyApplication is not compatible with dnxcore50 (DNXCore,Version=v5.0). Project MyApplication supports:
– net452 (.NETFramework,Version=v4.5.2)
– netcoreapp1.0 (.NETCoreApp,Version=v1.0)
I would expect that this tool is compatible with netcoreapp1.0 (RC2)?
I am using Visual Studio 2015 Update 3.
Thank you for your response,
F.
Hi Frantisek Danek!
This seems to be a compile-time issue, did you try building the project? BTW: We just released a new version of the tool that works for .Net Core 1.0 in Visual Studio 2015 Update 3, please give it a try. If you are using a Web application project you might also need to recreate it since the project templates have changed.
thanks,
Hi all!
In case you haven’t noticed, we have a new version of the WCF Connected Service for .Net Core 1.0, please give it a try and provide your feedback in this blog post:
thank you!
The WCF Connected Service for .NET Core is only available (AFAICT) for VS. If I’m reading correctly, we just can’t get svcutil.exe for the command line. However, that doesn’t seem like a limitation to actually using it. Can we have either an installer for the utility or a binary that we can just download and use?
I’m on VS Code, and I have no plans to go back to VS until the dust settles with upgrades. If I could just lay my hands on the svcutil.exe and supporting files (whatever you’re installing in %VSINSTALLDIR%\Common\IDE\Extensions\**\svcutil), then I should be able to use it from the command line to build service contracts in order to consume simple web services out there following Shayne Boyer’s blog at .
Nevermind – I just found out that you can change the .vsix extension of the installer to .zip, extract, and dotnet-svcutil.exe is right there in the svcutil folder. I’m good now.
Hi Purna,
I am migrating dot net middle ware component which is built in .net3.5 and 4.5 into .Net core .
Facing lot of challenges to resolve System.Configuration ,
Attribute Not found and Namespaces not found.
Serializable
ConfigurationProperty
SerializationInfo
System.SerializableAttribute()
System.ComponentModel.DesignerCategoryAttribute
[System.SerializableAttribute()]
using System.IdentityModel.Claims;
using System.Web.Services.Protocols;
using System.Configuration
Appreciate your help and suggestion please.
Abhay
Hello!
Is it possible to provide credentials information when consuming a SOAP service using WCF Connected Services? I referenced my service and the objects were scaffolded, but I need to inform username and password when I call a method via my client object. In a full-framework project, these credentials are configured on my app.config, but in .Net Core I just can’t figure out where I put this.
Thanks!
I need to add a service what has basic authentication. It tasks twice username and password for the wsdl that I want to import and after I receive the following error when it comes to create service client.
Metadata contains a reference that cannot be resolved. One or more errors occurred. (The remote server returned an error: (401) Unauthorized.) An error occurred in the tool.
However, there is no problem if the provided SOAP doesn’t use basic authentication.
No support for basic authentication??
I followed the instructions, but the wizard has added only async calls to all the methods from my service. Is it possible to add synchronous methods too?
It only allows async methods. I ran into the same issue.
I guess the explained scenario is with physical .svc file where in we can add service reference and discover the stuffs. How about for virtual scenarios. Consider below case.
Here service is getting activated via factory method which in turn making use Unity IOC to walk through the registrations and enable the same. So, my question is for this kind of enterprise scenario, do we have any working sample on github.
Thanks,
Rahul
I really need to be able to right click->refresh a service reference. Regenerating the reference right now is very inconvenient. Otherwise it is a decent enough tool to get by with.
Alternately, I need to be able to run the tool manually via a script. I’ve found the utility here, for anyone else looking:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\WCF Metadata Connected Service v0.5\svcutil\netcoreapp1.0 | https://blogs.msdn.microsoft.com/webdev/2016/05/25/announcing-wcf-connected-service-for-net-core-rc2-and-asp-net-core-rc2/ | CC-MAIN-2018-51 | refinedweb | 2,728 | 67.96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.