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
On 5/27/2013 9:30 AM, Chris Angelico wrote: On Mon, May 27, 2013 at 9:01 PM, Joao S. O. Bueno jsbueno@python.org.br wrote: I have a blog post with such a toy - nevertheless, it is just a toy. (If ther ewas soem small problem that could be elegantly approached in this fashion but not interactively, it could be used in production though) What can tail recursion do that can't be done by reassigning to the function parameters and 'goto' back to the top? Or, in the absence of an actual goto, a construct like this: def tail_recursive_function(some_arg): while True: # ... code if call_self: # return tail_recursive_function(some_other_arg) some_arg = some_other_arg continue # ... more code # falling off the end: break which basically amounts to a goto but using extra keywords to avoid the one that people hate. Is there any fundamental difference? I've never understood there to be any, but I'm only one, and possibly I'm wrong.. --Ned. ChrisA _______________________________________________ Python-ideas mailing list Python-ideas@python.org
https://mail.python.org/archives/list/python-ideas@python.org/message/JFKPBVIWCS7DMJTJFCHKQJDSCEIHPME3/
CC-MAIN-2021-21
refinedweb
173
62.38
This Technial Note covers different aspects of accessing bits, when using IAR Embedded Workbench for AVR. Many Special Function Registers (SFRs) contain single bits that one want to set, clear or test. This technical note gives some examples how it can be done. If you are used to compilers for the 8051 for example, you may be familiar with the dot-bit-number syntax (for example P3.2) which is an extension to the ISO/ANSI C langauge. That syntax is not supported by IAR C/C++ Compiler for AVR. Instead, in ISO/ANSI C you can access a bit using ordinary C expressions: P3 &= ~(1 << 2); /* clear a bit */ P3 |= (1 << 2); /* set a bit */ The compiler is smart enough to understand what you are doing and will use bit instructions when possible. If you need to access bits that have symbolic names, you can use the bit names that can be found in the io<chip>.h header file. As an example, the 8535 has a GIMSK register that has a bit called INT1 which can set in the following way: GIMSK |= (1 << INT1); You need to define the symbol ENABLE_BIT_DEFINITIONS to enable the bit name definitions at the end of the io8535.h header file. This can be done in the following way: #define ENABLE_BIT_DEFINITIONS #include <io8535.h> You can also avoid the define in the code and do it from the build environment instead. The SFR_?() macro used for defining the SFR symbols in the I/O header file also defines bit symbols, which allow you to write: GIMSK_Bit2 = 0; The following comment has been added in the header files starting with the 2.28A release of IAR C/C++ Compiler for AVR to clearify this: /***************************************************** * An example how the macro's below expand to. * SFR_B(AVR, 0x1F) Expands to: * __io union { * unsigned char AVR;//The sfrb as 1 byte * struct { //The sfrb as 8 bits * unsigned char AVR_Bit0:1, * AVR_Bit1:1, * AVR_Bit2:1, * AVR_Bit3:1, * AVR_Bit4:1, * AVR_Bit5:1, * AVR_Bit6:1, * AVR_Bit7:1; * }; * } @ 0x1F; * To set bit 5 of AVR you can do like this: * AVR |= (1<<5); * or like this: * AVR_Bit5 = 1; ****************************************************/ The symbol GIMSK_Bit2 is really a anonymous one bit bitfield. The anonymous part is a language extension, bitfields are part of the ISO/ANSI C language. All product names are trademarks or registered trademarks of their respective owners
https://www.iar.com/support/tech-notes/compiler/bit-access/
CC-MAIN-2017-04
refinedweb
396
67.49
The Om Programming Language :) The Om Programming Language :) Rather a long journal entry today. I hope that someone sticks with it as I'm really getting quite excited about how my scripting langauge is starting to develop now. I started trying to write a general overview of Om last night as I've been posting about my scripting language here for a while and never really provided such a thing, but I was quickly overwhelmed. It's really hard to write a concise overview, partly because the language has developed far more features than I realised until I took a step back but also because it is generally hard to know where to start and what order to discuss things in, given the interlated nature of language features. Om is designed to be a lightweight scripting language that is easy to integrate into existing C++ projects, implemented entirely in standard C++ itself and provide a reasonable level of efficiency of code execution in terms of speed and resource usage. It is not trying to compete with Google V8 and similar. I wouldn't be that foolish. But while the syntax of Om is quite similar to Javascript, there are a number of differences that have motivated the developent of the language in the first place. Firstly, there is no garbage collection in Om and it offers completely deterministic destruction of objects to enable RAII style coding - something I personally find hard to live without. Complex objects are carefully tracked by reference count and are released at the exact point their reference count reaches zero and, in the case of an Om::Type::Object, an Om::Type::Function can be set up to be called at this point. Secondly, the syntax for using objects is slightly simpler than Javascript in that there is no need for a new keyword. The closest we come to constructors in Om are free functions that return an instance of an Om::Type::Object. Finally, extending the language by the provision of native-side code is designed to be extremely simple. There is one Om::Function typedef, defined as: Om::Value someFunction(Om::Engine &engine, const Om::Value &object, const Om::ValueList ¶meters); This single type of function can be used to provide rich modules of shared native code to be accessed from the script as well as allowing the script to pass pretty much anything back to the host application. I'm going to focus on Om::Type::Object in this post and gloss over the other details which I hope will be fairly obvious from the example code. The only thing to bear in mind is that Om is entirely dynamically typed, with variables inferring their type from what is assigned to them, carrying their type around along with their value. Also bear in mind that Om::Type::Functions are entirely first-class entities in Om and can be assigned to variables or passed as parameters as simply as one would pass an Om::Type::Int or any other type. So to pick a random example, here's a simple example, entirely in script for now, of how one might implement a Person class. Om::Type::Objects are declared with the syntax { }, and are essentially a string-value mapping with some special properties discussed later on. Unlike Javascript, Om::Type::List, declared with [ ] syntax, is a completely separate type from Om::Type::Object and functions as a resizable, heterogenus array of values. import print;var makePerson = func(name, age){ return { name = name; age = age; };};var people = [ makePerson("Paul", 42), makePerson("Eddie", 23), makePerson("Jill", 78) ];for(var p: people){ print(p.name, " is ", p.age, " years old");}Okay, so let's now think in a more OO way and make the description a method on a person instead. import print;var makePerson = func(name, age){ return { name = name; age = age; describe = func { print(this.name, " is ", this.age, " years old."); }; };};var people = [ makePerson("Paul", 42), makePerson("Eddie", 23), makePerson("Jill", 78) ];for(var p: people){ p.describe();}Om supports prototype-based inheritence in a very simple fashion.";for(var p: people){ p.describe();}Note that all instances of the person object now share the "brown" value when we are reading, but when we write the "blonde" value to Eddie before the output loop, Eddie then has his own "hair" property which overrides the one in the prototype. This is a very simple system to implement but extremely flexible. Note the this.value syntax has to be explicit in Om. The reason is that the function has no idea it is a member function as it is being compiled. Indeed it is quite possible to call the same function once as a method on an object and then again as a free function.");}This outputs:oLastly for now, if we assign an Om::Type::Function taking no parameters to an objects destructor property, this will be called when the object is destroyed. import print;var proto ={ hair = "brown"; destructor = func { print("goodbye from the prototype"); };};var makePerson = func(name, age){ return { prototype = proto; name = name; age = age; describe = func { print(this.name, " is ", this.age, " years old and has ", this.hair, " coloured hair."); }; destructor = func { print("goodbye from ", this.name); }; };}");}people[2] = null;print("end of program");The above program will output the following:oOm: goodbye from JillOm: end of programOm: goodbye from PaulOm: goodbye from EddieOm: goodbye from the prototypeNote how assigning null to people[2] destroys Jill at that point, since that causes Jill's refernece count to drop to zero. Om::Type::Object has a built in members property that returns an Om::Type::List of the names of its members. Om::Type::Object supports lookup by both the dot operator and via dynamic text and the subscript operator so you can use these together to implement a form of reflection. import print;var o ={ name = "Paul"; age = 41; car = "Rover";};for(var m: o.members){ print(m, " = ", o[m]);}Using the subscript operator is far less efficient than the dot operator so should only be employed when the name of the property is not known. Using the dot operator in the VM equates to doing a binary search for an unsigned integer in a sorted array whereas using the subscript operator requires actual text comparisons at runtime. Final note on Om::Type::Object is that, like Om::Type::List and Om::Type::String, default copy is by reference. import print;var o = { name = "Paul"; };var c = o;o.name = "Eddie";print(c.name);This will output "Eddie", not "Paul". However, all types support the clone() method so we can explicitly perform a deep copy here instead. import print;var o = { name = "Paul"; };var c = o.clone();o.name = "Eddie";print(c.name);This will output "Paul" as expected. clone() is supported by every type although does nothing in the case of the value types. Evem constants can use the dot operator in Om and the following is all perfectly legal and well-defined: import print;print(10.type); // prints "int"var n = 10.clone(); // equivalent to var n = 10 :)var s = "hello".length; /// s = 5print({ name = "Paul"; age = 42; }.members.length); // prints 2print({ name = "Eddie"; age = 23; }.members.length.type); // prints "int"Now we have a bit of an overview of the langauge itself, let's take a look at how the C++ API is used to integrate Om scripting into an existing C++ application. The two key classes exposed by the API are Om::Engine and Om::Value. #incude "om/OmEngine.h"int main(){ Om::Engine engine; Om::Value v = engine.evaluate("return (1 + 2) * 3;", Om::Engine::EvaluateType::String); if(v.type() == Om::Type::Error) { std::cerr << "Error: " << v.toError().text << "\n"; return -1; } std::cout << "v is " << v.toInt() << "\n"; // will print "v is 9"}When reference types like Om::Type::String or Om::Type::Object are stored in Om::Values, the Om::Value takes care of keeping track of reference counts and so on, seamlessly from the user's point of view. Om::Value can directly construct value types, but the constructors are marked explicit to avoid accidental conversions. void f(){ Om::Value i(123); // Om::Type::Int Om::Value f(12.34f); // Om::Type::Float Om::Value b(true); // Om::Type::Bool}Reference types have to be generated from the Om::Engine. void f(Om::Engine &engine){ Om::Value s = engine.makeString("hello"); Om::Value o = engine,makeObject(); o.setProperty("name", engine.makeString("Paul")); o.setProperty("age", Om::Value(42));}If we construct an Om::Value with an Om::Type::Function, it is compiled and stored, but not executed until we choose to later on. int main(){ Om::Engine engine; Om::Value f = engine.evaluate("return func(a, b){ return a + b; };", Om::Engine::EvaluateType::String); if(f != Om::Type::Error) { Om::Value r = engine.execute(f, Om::Value(), { Om::Value(2), Om::Value(3) }); std::cout << "result " << r.toInt() << "\n"; // prints "result 5" }}In more detail, the execute method is Om::Value Om::Engine::execute(const Om::Value &function, const Om::Value &object, const Om::ValueList ¶meters), allowing you to pass in an optional this-object and a parameter list to the function. Om provides a simple but flexible mechanism for writing and reusing modular code. There is no preprocessing or file inclusion in Om. The compiler is only ever looking at exactly one source file (or string) at a time. Om::Engine provides the addModule(const Om::String &id, const Om::Value &value) method. Any type of Om::Value can be added to the modules list and then imported into another script. For example, all the previous examples begin with import print; As Om is entirely unaware of the context in which it is running, I have set up a simple native-side function to print values to std::cout in the test bed. C++-side, this looks like this: void out(std::ostream &os, const Om::Value &value){ if(value.type() == Om::Type::List) { os << "["; for(int i = 0; i < value.count(); ++i) { os << " "; out(os, value.property(i)); } os << " ] "; } else if(value.type() == Om::Type::Data) { os << value.toData(); } else { os << value.toString(); // toString() provides a text representation of most types }}Om::Value printFunc(Om::Engine &engine, const Om::Value &object, const Om::ValueList ¶ms){ std::cout << "Om: "; for(auto p: params) { out(std::cout, p); } std::cout << "\n"; return Om::Value();}int main(){ Om::Engine engine; Om::Engine::OutputFlags flags(Om::Engine::OutputFlag::HideDefinedStrings); engine.addModule("print", engine.makeFunction(printFunc)); engine.evaluate("sample.txt", Om::Engine::EvaluateType::File);}The import keyword is scope aware and only introduces the symbol into the import's scope. var n = 20;if(n > 10){ import print; print(n);}print("end"); // compile error - print symbol not foundThe actual module lookup is peformed at runtime so it is quite possible to compile a function that references modules that habe not yet been added to the engine, as long as they are added before the function is executed. As a result it is possible to create two-way relationships between modules without issues with circular dependancy. In the print example, the module is simply an Om::Type::Function. Let's look at a slightly more complex example using the script to define a module instead - a modular reworking of the Person examples above. Firstly we define the Person module in a normal script file: import print;return{ base = { hair = "brown"; }; make = func(name, age) { return { prototype = this.base; name = name; age = age; describe = func { print(this.name, " is ", this.age, " years old and has ", this.hair, " coloured hair."); }; destructor = func { print("goodbye from ", this.name); }; }; };};Note we are returning an Om::Type::Object here, which gives as a place to store our prototype instance as well as the make function. The make function is the Om equivalent of a constructor here. In the C++ setup, we can simply do: int main(){ Om::Engine engine; Om::Engine::OutputFlags flags(Om::Engine::OutputFlag::HideDefinedStrings); engine.addModule("print", engine.makeFunction(printFunc)); engine.addModule("person", engine.evaluate("person.txt", Om::Engine::EvaluateType::File)); engine.evaluate("sample.txt", Om::Engine::EvaluateType::File);}Note in the real world, one would evaluate person.txt into an Om::Value so one could check for compiler errors. The evaluate method will return an Om::Type::Error rather than the object if errors are thrown up by the compiler. We can now use this module in sample.txt as follows: import person;var people = [ person.make("Paul", 42), person.make("Eddie", 23), person.make("Jill", 78) ];people[1].hair = "blonde";for(var p: people){ p.describe();}Note that there is no need to import print; into sample.txt now as it is not used directly. It is also possible to extend Om with types implemented in native code. For example, because Om::Type::Strings are immutable, it is not optimal to concatenate lots of strings together in the script as it produces a great deal of temporary values. Much as in other langauges, what we really need is a stringBuilder that can do this kind of concatenation more efficiently. I'll now describe how to create such a facility in native C++ to make available to the scripts. A special Om::Type provided for use in the C++ API is Om::Type::Data. This allows the user to store a void* pointer in an Om::Value. We can then access this data from the object instance in the usual way and use it to implement custom object types that interface with C++ code. Our string builder is going to be based on std::ostringstream, so first of all we can define a representation in C++. class Rep{public: Rep(){ } Rep(const std::string &s){ os << s; } std::ostringstream os;};Next, we need to provide a function that the script can call to create an instance of the string builder. In this function, we assign the properties of the string builder, using other native functions. I didn't want to provide a void* constructor for Om::Value as that could potentially lead to some dangerous conversions, even with an explicit constructor, so instead there is a static fromData() method instead to make this even more explicit. Om::Value makeObject(Om::Engine &engine, const std::string &init){ Om::Value o = engine.makeObject(); o.setProperty("data", Om::Value::fromData(new Rep(init))); return o;}Now we can add the methods the script needs to be able to call on the string builder, specifically add() and value(). Om::Value provides a convenience template function, toUserType> Om::Value add(Om::Engine &engine, const Om::Value &object, const Om::ValueList ¶ms){ if(params.count() != 1 || params[0].type() != Om::Type::String) return engine.makeError("incorrect parameters"); Rep *rep = object.property("data").toUserTypeFor the final step, we need to define a destructor for the object so we can clean up the allocated memory. Note we are really just using existing features of the language here rather than having to implement any special functionality. Om::Value destroy(Om::Engine &engine, const Om::Value &object, const Om::ValueList ¶ms){ delete object.property("data").toUserTypeCaution needs to be taken here though. Much like C++'s rule of three (or five), if you are providing a custom destructor and using the Om::Type::Data type, you almost certainly also need to overload clone() or terrible things will happen. The built-in clone() will do a by-value copy of the "data" property, meaning you end up with a double-delete if you clone the object in the script. Since Om::Type::Objects can override any of the built-in methods with their own properties, we can simply add: Om::Value clone(Om::Engine &engine, const Om::Value &object, const Om::ValueList ¶ms){ Rep *rep = object.property("data").toUserTypeNow we are safe to clone() the object inside the script. We can define all of the above in a cpp file and provide a simple interface function in the header. Om::Value omStringBuilder(Om::Engine &engine, const Om::Value &object, const Om::ValueList ¶ms){ return makeObject(engine, "");}Then business as usual setting up the module in main(). int main(){ Om::Engine engine; engine.addModule("print", engine.makeFunction(printFunc)); engine.addModule("stringBuilder", engine.makeFunction(omStringBuilder)); engine.evaluate("sample.txt", Om::Engine::EvaluateType::File);}Now off we can go into the script and use our custom type: import print;import stringBuilder;var s = stringBuilder();s.add("one, ");s.add("two ");s.add("and three.");print(s.value()); // prints "one, two and three."For types that should not be cloned, for eaxmple a wrapper around a file stream or similar, one can instead provide a clone implementation in C++ like this: Om::Value clone(Om::Engine &engine, const Om::Value &object, const Om::ValueList ¶ms){ return engine.makeError("unable to clone object");}Then, in the script, if an attempt is made to clone the object, a runtime error will be generated and the script will exit. The destructors will still be called though so the memory clean up will still take place. A couple of other snippets to mention. Script functions can be defined to take a variable number of parameters using the following syntax: var f = func(a, b, c...){};The ellipses must be attached to the right-most parameter and when calling the function, you must provide values for the normal parameters. Any additional parameters (more than two in this example) are then accessible using the 'c' symbol which will be of Om::Type::List, containing the additinoal parameters. Better explained with exmaple code here. import print;var f = func(a, b, c...){ print(a); print(b); print(c);}f(1, 2); // prints 1, 2, [ ] (an empty list)f(1, 2, 3, 4); // prints 1, 2, [ 3, 4 ]var x = func(p...){ for(var i: p) print(i);};x(); // prints nothingx(1, 2, 3, 4); // prints 1 2 3 4The C++ style ternary operator is supported in Om, as well as short-circuit evalution of and and or. These are of particular use in a dynamically typed language as they can be used to concisely avoid evaluating expressions that would generate a runtime error. var f = func(a);{ print(a.type == "object" ? a.name : "no name"); if(a.type == "object" and a.name == "Paul") doStuff();}In both cases the dot operator would throw a runtime error if the variable was not an object, so avoiding evaluating these is useful. I think that is enough information for now. If anyone has made it through, thank you for your perserverence and I'm keen to answer any queries anyone may have. [EDIT] I've just finished implementing Om's version of the switch statement, and also more general break statements for early-exiting out of loops, both of which work much as you would expect. Unlike C an C++, Om's switch is never turned into a jump table so while it isn't quite the efficient beast we know and love, it also doesn't have the C++ switch limitations - the switch expression and even the case expressions can be of absolutely any expression type. Fallthrough works the same as in C++ though. Next Time: If anyone is interested, I'll maybe start to lift the lid on how all of this is actually implemented. Here, as a sneak peak, is the current complete OpCode set for the virtual machine, upon which everything above is based. A surprisingly small set of codes I think. namespace OpCode{enum class Type{ Call, Ret, Push, Pop, PopN, Peek, Jmp, JmpT, JmpF, GetLc, PutLc, GetMb, PutMb, GetSc, PutSc, GetNl, PutNl, GetMd, Math, Cmp, Una, Bool, MkEnt, AddCh, FeChk, FeGet, Inc, Dec, Invalid};const char *toString(Type type);const char *parameters(Type type);enum class Math{ Add, Sub, Mul, Div, Invalid};const char *toString(Math type);enum class Cmp{ Eq, Neq, Lt, LtEq, Gt, GtEq, Invalid};const char *toString(Cmp type);enum class Una{ Neg, Not, Invalid};const char *toString(Una type);template 4 Comments Recommended Comments You need to be a member in order to leave a comment Sign up for a new account in our community. It's easy!Register a new account Already have an account? Sign in here.Sign In Now
https://www.gamedev.net/blogs/entry/2262517-the-om-programming-language/
CC-MAIN-2018-47
refinedweb
3,377
54.63
The Console object has a readPassword() method that disables echoing and allows a user to enter a password blindly. The password is returned as a character array. Here is an example of how to use the Console class to request a password from the user. import java.io.Console fun main(args : Array<String>){ //Best to declare Console as a nullable type since System.console() may return null val console : Console? = System.console() when (console){ //In this case, the JVM is not connected to the console so we need to exit null -> { println("Not connected to console. Exiting") System.exit(-1) } //Otherwise we can proceed normally else -> { val userName = console.readLine("Enter your user name => ") val pw = console.readPassword("Enter your password => ") println("Access Granted for $userName") //This is important! We don't know when the character array //will get garbage collected and we don't want it to sit around //in memory holding the password. We can't control when the array //gets garbage collected, but we can overwrite the password with //blank spaces so that it doesn't hold the password. for (i in 0 until pw.size){ pw[i] = ' ' } } } } We begin by getting a reference to the console. Since there is a possibility that System.console() can return null, it’s a best practice to declare console as a nullable type so that we have Kotlin compiler safety. After getting a reference to the console, we can use the when() function to react to the null case or continue with the program. The call to readPassword (line 16) isn’t very dramatic. The program uses the overloaded version to prompt the user for a password and return the password as a character array. In terms of security, it’s important to never hold a password as a String. That’s why the readPassword() method returns a character array. Strings are immutable. That means we can never change the value of the String. Furthermore, we never know when the JVM will garbage collect an object. Those two facts make for dangerous circumstances because a String holding a password can sit in memory for an unknown amount of time. Should someone break past the security constraints of the JVM and gain access to the program’s memory, there is the potential they could steal a password. Character arrays also get garbage collected at unknown times. The difference between the character array and a String is that we can overwrite each element in the array. The example program demonstrates this on lines 25-27 by overwriting each element of the pw array with a blank space. Should someone break into the program’s memory, all they will see is a character array of empty spaces. The operation of converting a password character array to empty spaces should be completed as soon as password validation is finished. One thought on “Kotlin Console Password”
https://stonesoupprogramming.com/2017/11/20/kotlin-console-password/
CC-MAIN-2022-05
refinedweb
482
65.12
perlquestion bobf <p> Is there a way to fully qualify a subroutine with the package name in a variable but <i>without</i> using [doc://eval]? </p> <p> This is possible with OO programming, where a long class name can be replaced with a variable: <code> my $class = 'Very::Long::Class::Name'; $class->method; </code> </p> <p> I want to do a similar thing for non-OO subroutines, so I can add clarity to the program by fully qualifying the sub name but still keep the call to a manageable length (and without sprinkling [doc://eval] everywhere). Doing this: <code> my $pkg = 'Very::Long::Package::Name'; $pkg::sub; </code> obviously doesn't work, since <c>$pkg::sub</c> refers to the global variable <c>$sub</c> in the <c>pkg</c> namespace. </p> <p> I've considered the following options (example code below): <ul> <li><strong>Fully qualify the sub call, forget about the variable</strong><br> This is the standard, I guess. </li> <li><strong>Call the sub as a method (even though it isn't one)</strong><br> This seems like a Bad Idea. Also, the contents of <c>@_</c> will change depending on whether it is called as a sub or as a method (in which case the class name will be the first parameter). </li> <li><strong>Assemble the call into a string, then use [doc://eval]</strong><br> Eww. This may achieve the primary goal, but it really clutters things up. </li> <li><strong>Create a reference to the sub itself (not the package)</strong><br> I don't mind doing it this way, but it requires a separate ref for every sub from the same package. I'd rather create a ref (or something) to the package so I only have one variable, then append the appropriate sub name as required. </li> <li><strong>Import the subs into the caller's namespace, forget about fully qualifying it</strong><br> This is how I'm doing it now, but the more subs I import the harder it becomes to keep track of where they are all from (hence the desire to use fully qualified names). </li> </ul> </p> <p> <code>] } </code> </p> <p> Are there other ways of doing this that are not listed above? Comments regarding best practices are also appreciated. </p> <p> Thanks! </p>
http://www.perlmonks.org/index.pl?displaytype=xml;node_id=527987
CC-MAIN-2016-40
refinedweb
392
55.17
Apr 12, 2012 4:11 PM by 801926 Java Card convert the class file into an .exp.file - one problem 923272 Apr 12, 2012 2:52 PM Hi, I have a problem concerning the conversion of my class files into an .exp file. Indeed, I have created a project (project A) containing some classes and among them an abstract class, an shareable interface and class implementing the interface Shareable of Java Card. My problem is that, for the needs of my project, I would like to import some of this classes in another applet (applet B) of another package, that I do without problem except one. The problem is due to my *.exp file. This one, instead of containing the declaration of my public class and method, contains ONLY the declaration of my shareable interface and its methods... I can not compile the applet B because the reference to the classes I import are not found... For my compilation and the conversion of my class file into *.exp file, I use the ant tools supplied with the Java Card Development Kit 2.2.2. To realize my applet, I use eclipse and the plugin eclipse JCDE (for java card). I have found more precisely where is my problem but I really need some help from you. I have read in the Java Card Virtual Machine specification that the flag ACC_LIBRARY in the CONSTANT_Package _info (§ 5.5 Export File) must be set so as to have all the entries of public classes and interface. But, where I can change it , I do not know what is the Constant Package Info. Is someone have already have this problem? How can I change it? Thanks very much in advance for you help. Eglantine I have the same question Show 0 Likes (0) This content has been marked as final. Show 1 reply 1. Re: Java Card convert the class file into an .exp.file - one problem 801926 Apr 12, 2012 4:11 PM ( in response to 923272 ) Provide source, logs, command line input, .. Actions
https://community.oracle.com/thread/2376756?tstart=255
CC-MAIN-2017-22
refinedweb
341
72.26
If. One thing Rails users are sure to be familiar with is using rake for various project automation tasks. However, if you haven't written your own custom tasks before, you might not be familiar with how to create a Rakefile from scratch. You can learn a whole lot by taking a peek at the Rakefile that is generated by Rails, but one of the most simple needs you'll have that's easy to handle with Rake is creating a test runner. The following code shows what I'm using in EarGTD. require "rubygems" require "rake" require "rake/testtask" task :default => [:test] Rake::TestTask.new do |test| test.libs << "test" test.test_files = Dir[ "test/test_*.rb" ] test.verbose = true end This should be fairly intuitive just by reading it. This uses libraries built into Rake to set up a test task that will run anything in the test/ dir that has a file name like test_something.rb The code above sets the test task as default, so running rake anywhere within your project will run your test suite. Though this is all fairly pedestrian stuff, I'd like to mention that the Dir class rocks. It's part of core ruby and lets you treat file pattern matches as Enumerable objects. Below is a quick irb session that shows why this is interesting. >> Dir["EarGTD/*"] => ["EarGTD/data", "EarGTD/earGTD", "EarGTD/lib", "EarGTD/Rakefile", "EarGTD/test"] >> Dir["EarGTD/*"].map { |f| f.reverse } => ["atad/DTGraE", "DTGrae/DTGraE", "bil/DTGraE", "elifekaR/DTGraE", "tset/DTGraE"] >> Dir["EarGTD/*"][0] => "EarGTD/data" It's really tempting to build little console apps in a way similar to how you'd write a shell script: as a procedural series of commands that form a ball o' code. Though this works fine in a pinch, it makes the code difficult to test and prevents it from playing well with others. Still, how much is too much? You probably don't want a massive class heirarchy for a simple tool like EarGTD. Usually in cases like this, I find myself leaning towards a simple structure that borrows some ideas from functional programming. You may have seen modules in Ruby used as mix-ins. This is when you define some functionality in a module and then include it in a class for use. The following example will add the instance method b to the class C. module A def b puts "this is b" end end class C include A end d = C.new d.b #=> "this is b" Still, if you aren't really dealing with maintaining any state, why bother with classes? By using module_function, the following code could be simplified so that the method may be called directly on the module. module A module_function def b puts "this is b" end end A.b #=> "this is b" Since all the state for EarGTD is stored in the database, this is the approach we use. The result is a very clean modular interface. In fact, the EarGTD script itself becomes quite minimal in part because of this. #!/usr/bin/env ruby require "lib/ear_gtd" EarGTD.connect EarGTD.process_command(ARGV) You can see that all of the heavy lifting is essentially being done by a single method, process_command. An approach that helps keep things clean when building console apps in Ruby is to build some simple command processing. This could either be a method or a class that manipulates the data that is passed in from the command line. In the case of EarGTD, all that needs to be handled are the arguments passed to the script. In Ruby, this is stored in a special variable called ARGV. Above, you saw it used like this: EarGTD.process_command(ARGV) To set up my command processor, I simply peel off the first argument and store the rest of the arguments in an array, as Example 3 shows. def process_command(cmd) args = Array(cmd) command = args.shift case(command) when "+" add_task(args[0]) when "@" t = tasks puts t.empty? ? "Looks like you have nothing to do.\n" : t # ... other commands omitted else puts "Que?" end end Above is a simplified version of EarGTD's command processor. You can see that it's just using a case statement to figure out what command is being called and then delegating to some functions to do the actual tasks. This allows you to treat the rest of your coding task as if you were writing a small function library, and cleanly separates that code from the user interface. Any interface that manipulates the input into something the command processor understands will work fine.. Return to Ruby.
http://archive.oreilly.com/lpt/a/7051
CC-MAIN-2016-40
refinedweb
771
73.27
(For more resources on MySQL, see here.) An idea of the HTML engine Ever thought about what your tables might look like? Why not represent a table as a <TABLE>? You would be able to see it, visually, in any browser. Sounds cool. But how could we make it work? We want a simple engine, not an all-purpose Swiss Army Knife HTML-to-SQL converter, which means we will not need any existing universal HTML or XML parsers, but can rely on a fixed file format. For example, something like this: <html><head><title>t1</title></head><body><table border=1> <tr><th>col1</th><th>other col</th><th>more cols</th></tr> <tr><td>data</td><td>more data</td><td>more data</td></tr> <!-- this row was deleted ... --> <tr><td>data</td><td>more data</td><td>more data</td></tr> ... and so on ... </table></body></html> But even then this engine is way more complex than the previous example, and it makes sense to split the code. The engine could stay, as usual, in the ha_html.cc file, the declarations in ha_html.h, and if we need any utility functions to work with HTML we can put them in the htmlutils.cc file. Flashback A storage engine needs to declare a plugin and an initialization function that fills a handlerton structure. Again, the only handlerton method that we need here is a create() method. #include "ha_html.h" static handler* html_create_handler(handlerton *hton, TABLE_SHARE *table, MEM_ROOT *mem_root) { return new (mem_root) ha_html(hton, table); } static int html_init(void *p) { handlerton *html_hton = (handlerton *)p; html_hton->create = html_create_handler; return 0; } struct st_mysql_storage_engine html_storage_engine = { MYSQL_HANDLERTON_INTERFACE_VERSION }; mysql_declare_plugin(html) { MYSQL_STORAGE_ENGINE_PLUGIN, &html_storage_engine, "HTML", "Sergei Golubchik", "An example HTML storage engine", PLUGIN_LICENSE_GPL, html_init, NULL, 0x0001, NULL, NULL, NULL } mysql_declare_plugin_end; Now we need to implement all of the required handler class methods. Let's start with simple ones: const char *ha_html::table_type() const { return "HTML"; } const char **ha_html::bas_ext() const { static const char *exts[] = { ".html", 0 }; return exts; } ulong ha_html::index_flags(uint inx, uint part, bool all_parts) const { return 0; } ulonglong ha_html::table_flags() const { return HA_NO_TRANSACTIONS | HA_REC_NOT_IN_SEQ | HA_NO_BLOBS; } THR_LOCK_DATA **ha_html::store_lock(THD *thd, THR_LOCK_DATA **to, enum thr_lock_type lock_type) { if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK) lock.type = lock_type; *to ++= &lock; return to; } These methods are familiar to us. They say that the engine is called "HTML", it stores the table data in files with the .html extension, the tables are not transactional, the position for ha_html::rnd_pos() is obtained by calling ha_html::position(), and that it does not support BLOBs. Also, we need a function to create and initialize an HTML_SHARE structure: static HTML_SHARE *find_or_create_share( const char *table_name, TABLE *table) { HTML_SHARE *share; for (share = (HTML_SHARE*)table->s->ha_data; share; share = share->next) if (my_strcasecmp(table_alias_charset, table_name, share->name) == 0) return share; share = (HTML_SHARE*)alloc_root(&table->s->mem_root, sizeof(*share)); bzero(share, sizeof(*share)); share->name = strdup_root(&table->s->mem_root, table_name); share->next = (HTML_SHARE*)table->s->ha_data; table->s->ha_data = share; return share; } It is exactly the same function, only the structure is now called HTML_SHARE, not STATIC_SHARE. Creating, opening, and closing the table Having done the basics, we can start working with the tables. The first operation, of course, is the table creation. To be able to read, update, or even open the table we need to create it first, right? Now, the table is just an HTML file and to create a table we only need to create an HTML file with our header and footer, but with no data between them. We do not need to create any TABLE or Field objects, or anything else—MySQL does it automatically. To avoid repeating the same HTML tags over and over we will define the header and the footer in the ha_html.h file as follows: #define HEADER1 "<html><head><title>" #define HEADER2 "</title></head><body><table border=1>\n" #define FOOTER "</table></body></html>" #define FOOTER_LEN ((int)(sizeof(FOOTER)-1)) As we want a header to include a table name we have split it in two parts. Now, we can create our table: int ha_html::create(const char *name, TABLE *table_arg, HA_CREATE_INFO *create_info) { char buf[FN_REFLEN+10]; strcpy(buf, name); strcat(buf, *bas_ext()); We start by generating a filename. The "table name" that the storage engine gets is not the original table name, it is converted to be a safe filename. All "troublesome" characters are encoded, and the database name is included and separated from the table name with a slash. It means we can safely use name as the filename and all we need to do is to append an extension. Having the filename, we open it and write our data: FILE *f = fopen(buf, "w"); if (f == 0) return errno; fprintf(f, HEADER1); write_html(f, table_arg->s->table_name.str); fprintf(f, HEADER2 "<tr>"); First, we write the header and the table name. Note that we did not write the value of the name argument into the header, but took the table name from the TABLE_SHARE structure (as table_arg->s->table_name.str), because name is mangled to be a safe filename, and we would like to see the original table name in the HTML page title. Also, we did not just write it into the file, we used a write_html() function—this is our utility method that performs the necessary entity encoding to get a well-formed HTML. But let's not think about it too much now, just remember that we need to write it, it can be done later. Now, we iterate over all fields and write their names wrapped in <th>...</th> tags. Again, we rely on our write_html() function here: for (uint i = 0; i < table_arg->s->fields; i++) { fprintf(f, "<th>"); write_html(f, table_arg->field[i]->field_name); fprintf(f, "</th>"); } fprintf(f, "</tr>"); fprintf(f, FOOTER); fclose(f); return 0; } Done, an empty table is created. Opening it is easy too. We generate the filename and open the file just as in the create() method. The only difference is that we need to remember the FILE pointer to be able to read the data later, and we store it in fhtml, which has to be a member of the ha_html object: int ha_html::open(const char *name, int mode, uint test_if_locked) { char buf[FN_REFLEN+10]; strcpy(buf, name); strcat(buf, *bas_ext()); fhtml = fopen(buf, "r+"); if (fhtml == 0) return errno; When parsing an HTML file we will often need to skip over known patterns in the text. Instead of using a special library or a custom pattern parser for that, let's try to use scanf()—it exists everywhere, has a built-in pattern matching language, and it is powerful enough for our purposes. For convenience, we will wrap it in a skip_html() function that takes a scanf() format and returns the number of bytes skipped. Assuming we have such a function, we can finish opening the table: skip_html(fhtml, HEADER1 "%*[^<]" HEADER2 "<tr>"); for (uint i = 0; i < table->s->fields; i++) { skip_html(fhtml, "<th>%*[^<]</th>"); } skip_html(fhtml, "</tr>"); data_start = ftell(fhtml); We skip the first part of the header, then "everything up to the opening angle bracket", which eats up the table name, and the second part of the header. Then we skip individual row headers in a loop and the end of row </tr> tag. In order not to repeat this parsing again we remember the offset where the row data starts. At the end we allocate an HTML_SHARE and initialize lock objects: share = find_or_create_share(name, table); if (share->use_count++ == 0) thr_lock_init(&share->lock); thr_lock_data_init(&share->lock,&lock,NULL); return 0; } Closing the table is simple, and should not come as a surprise to us: int ha_html::close(void) { fclose(fhtml); if (--share->use_count == 0) thr_lock_delete(&share->lock); return 0; } Read more about this book (For more resources on MySQL, see here.) Reading data An indexless table can be read using two access patterns—either sequential, with rnd_init() and rnd_next() methods, or a random one with position() and rnd_pos() methods. Let's start with the former: int ha_html::rnd_next(unsigned char *buf) { fseek(fhtml, current_row_end, SEEK_SET); for (;;) { This is one of the most complex methods in our storage engine. Let's analyze it line by line. We started by positioning the stream at the end of the last read row, and will be looking for the first non-deleted row (remember that a row starts with a <tr> tag, while a deleted row starts with <!--). But first we save the offset of the row that we will read, as it may be needed for position(), and check it against the end of data offset: current_row_start= ftell(fhtml); if (current_row_start >= data_end) return HA_ERR_END_OF_FILE; This check allows us to skip any processing and return an error at once if we have read all of the rows. It is a minor optimization for a read-only table, but for an updatable table it is of paramount importance. Imagine that we are doing a table scan and the same SQL statement adds new data at the end of the table (which can easily happen in an UPDATE statement). Our table scan should ignore all of the rows that were added in the same statement, and if we remember where the row data ends in the file, we can stop reading at that offset. For this to work, data_end needs to be recalculated at the beginning of every statement. Indeed, as the table may be growing, it is not enough to do it in the open() method. We will talk about statement boundaries later. On the other hand, data_start can never change, we can determine it only once. if (skip_html(fhtml, "<tr>") == 4) break; Now, we can start reading the data. First, we read and skip over the <tr> tag. If it was successful, and we have skipped over four characters, we have found our row, and can break out of the loop. if (skip_html(fhtml, "!--%*[^-]-->\n") >=7) continue; Otherwise we try to match a deleted row. As the opening angle bracket was already matched and consumed by the previous skip_html() we omit it from the pattern. If there was a match, we restart the loop. return HA_ERR_CRASHED; } Otherwise we return an error, complaining that the table is corrupted. my_bitmap_map *old_map = dbug_tmp_use_all_columns(table, table->write_set); my_ptrdiff_t offset = (my_ptrdiff_t)(buf-table->record[0]); for (uint i = 0; i < table->s->fields; i++) { Field *field = table->field[i]; field->move_field_offset(offset); This loop over all fields and the two assignments before it are the same. if (skip_html(fhtml, "<%*[td/]>") == 5) field->set_null(); else { Here we skip "an angle bracket, any sequence of characters t, d, /, and a closing angle bracket". If we have skipped five characters, it was a <td/> tag, which stands for a NULL value, otherwise it was an opening <td> tag, and we need to read the value of the field: char *buf = (char*) malloc(field->max_display_length() + 1); int buf_len = read_html(fhtml, buf); field->set_notnull(); field->store(buf, buf_len, &my_charset_bin); skip_html(fhtml, "</td>"); free(buf); To read the value we allocate a buffer, big enough to hold the string representation of the field value, and read the value using our read_html() function—a counterpart of write_html() that converts HTML entities back into characters. Then we mark the field as holding a NOT NULL value, and store the string value in the field. The field—an object of the Field class—automatically performs all of the necessary conversion from a string to a number, a date, or whatever the field type is. Then we skip the closing <\td> tag and free the buffer. An inquisitive reader may have noticed that calling malloc() and free() for every field in every row during a table scan does not indicate performance-conscious programming. He would be right—it would be better to allocate the buffer once, big enough to hold a value of any field. It could have been done in the ha_html::open() method, because field lengths cannot change after a table is opened. } field->move_field_offset(-offset); } skip_html(fhtml, "</tr>\n"); dbug_tmp_restore_column_map(table->write_set, old_map); current_row_end = ftell(fhtml); return 0; } We finish reading a row by restoring field offsets and a write_set bitmap, skipping the closing </tr> tag, and remembering the offset where the row ended. int ha_html::rnd_init(bool scan) { current_row_start = 0; current_row_end = data_start; return 0; } In this function, we need to prepare for a sequential table scan. All we need to do is to initialize current_row_start and current_row_end. As we start reading a new row from the current_row_end offset, we should set it here to the data_start offset, that is to the beginning of the very first row. Additionally, we reset current_row_start to indicate that no row has been read yet. void ha_html::position(const uchar *record) { *(ulong*)ref = current_row_start; } This method is very simple. A unique row identifier, in our case, is the file offset to the row data. That is, all we need to do here is to store the offset of the current row at the ref pointer. int ha_html::rnd_pos(uchar * buf, uchar *pos) { memcpy(¤t_row_end, pos, sizeof(current_row_end)); return rnd_next(buf); } Reading a row at the given position is easy too. We only restore the position into current_row_end and let our rnd_next() method to do the rest of the job. Updating the table There are three primary methods that modify the table data. They are write_row(), delete_row(), and update_row(), which are used by the INSERT, DELETE, and UPDATE statements accordingly. In our engine, write_row() is the most complex one. int ha_html::write_row(uchar *buf) { if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT) table->timestamp_field->set_time(); if (table->next_number_field && buf == table->record[0]) { int error; if ((error= update_auto_increment())) return error; } Almost every engine's write_row() method starts with these lines. They update the values of the TIMESTAMP and AUTO_INCREMENT fields, if necessary. Strictly speaking, the second—AUTO_INCREMENT—block is not needed here. Our engine does not support indexes, that is, it can never have an AUTO_INCREMENT field. fseek(fhtml, -FOOTER_LEN, SEEK_END); fprintf(fhtml, "<tr>"); We write a new row at the end of the file. That is, we position the stream at the end, just before the footer, and start a new row with an opening <tr> tag. my_bitmap_map *old_map = dbug_tmp_use_all_columns(table, table->read_set); my_ptrdiff_t offset = (my_ptrdiff_t)(buf-table->record[0]); for (uint i = 0; i < table->s->fields; i++) { Field *field = table->field[i]; field->move_field_offset(offset); Now we iterate over the fields in a loop very similar to the one in rnd_next(), only it modifies the read_set bitmap, not the write_set. if (field->is_null()) fprintf(fhtml, "<td/>"); If the field value is NULL we write it down as <td/> to be able to distinguish it from the empty string (which is written as <td><td/>), otherwise we take the field value and write it to the file: else { char tmp_buf[1024]; String tmp(tmp_buf, sizeof(tmp_buf), &my_charset_bin); String *val = field->val_str(&tmp, &tmp); The val_* family of Field methods—val_str(), val_int(), val_real(), and val_decimal() return the value of the Field, converted to a corresponding type. To store it in the HTML file, obviously, we want the value converted to a string, that is, we need to use val_str(). This method takes two arguments, pointers to String objects. The Field::val_str() method may use either the first or a second, depending on whether it needs a memory buffer or not. However, as a caller we can simply pass the same String in both arguments. The class String is a utility class for working, well, with strings. An object of the String class represents a string as a pointer, string length in bytes, and string character set. It knows whether the string was allocated or not. It can reallocate it as the string grows and as expected, it will free the allocated memory on destruction. What is important for us is that it can start off from a fixed buffer and allocate the memory automatically if the string value does not fit. It means that if we create a buffer on the stack we can hope to avoid memory allocations in most cases. Indeed, the above declarations with tmp_buf and String tmp show a typical String usage pattern that can be seen everywhere in the MySQL code. fprintf(fhtml, "<td>"); write_html(fhtml, val->c_ptr()); fprintf(fhtml, "</td>"); Here we have used the String::c_ptr() method. It returns the string value as a zero terminated string, appropriate for passing to the fprintf() function. } field->move_field_offset(-offset); } dbug_tmp_restore_column_map(table->read_set, old_map); if (fprintf(fhtml, "</tr>\n" FOOTER) < 6 + FOOTER_LEN) return errno; else return 0; } Having written all of the fields, we restore field offsets and read_set, write the closing </tr> tag and the file footer, and return. Just in case the disk was full we verify that the footer was written in whole. int ha_html::delete_row(const uchar *buf) { assert(current_row_start); fseek(fhtml, current_row_start, SEEK_SET); fprintf(fhtml, "<!--"); fseek(fhtml, current_row_end-4, SEEK_SET); fprintf(fhtml, "-->\n"); return 0; } Compared to write_row(), our delete_row() method is much simpler. MySQL can only call delete_row() for the current row. And because we know where it starts—at the current_row_start offset, we can even assert this fact—and we know where it ends, we can easily comment the complete row out, "deleting" it from the HTML table. int ha_html::update_row(const uchar *old_data, uchar *new_data) { assert(current_row_start); if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE) table->timestamp_field->set_time(); delete_row(old_data); table->timestamp_field_type = (timestamp_auto_set_type) (table->timestamp_field_type & ~TIMESTAMP_AUTO_SET_ON_INSERT); return write_row(new_data); } The update_row() method is simple too. Just like write_row() it starts by updating the TIMESTAMP field, but after that we can simply delete the old row and insert the new one at the end of the table. We just need to remember to remove the TIMESTAMP_AUTO_SET_ON_INSERT bit to avoid unnecessary TIMESTAMP updates; MySQL will restore it for the next statement automatically. Because we have remembered the original "end of table" offset at the beginning of the statement, we do not need to worry that our table scan will read newly inserted data. Summary In this article, we have learned the methods needed to create a storage engine with a full read/write support. Further resources on this subject:
https://www.packtpub.com/books/content/mysql-51-plugin-html-storage-engine%E2%80%94reads-and-writes
CC-MAIN-2015-35
refinedweb
3,024
57.91
Integration with Game Engines¶ Unity¶ Integration with Unity can be done only using C# binding. We tested it only on Windows, but it may work on Linux and MacOS too. Android and IOS are not supported. You can build C# binding from source or download compiled package directly from Nuget. Here we will use Nuget to download and install BrainFlow. Open OUTPUTDIR, in our example it is D:\BrainFlowNuget. At the moment of writing this tutorial latest BrainFlow version is 4.0.1, it is ok if you download newer version from Nuget, it does not affect the process of integration with Unity. For BrainFlow there are Managed(C#) and Unmanaged(C++) libraries. C++ libraries are located inside folder D:\BrainFlowNuget\brainflow.4.0.1\lib, C# libraries are located inside folder D:\BrainFlowNuget\brainflow.4.0.1\lib\net45. Open your Unity project and copy Managed(C#) libraries to the Assets folder, after that copy Unmanaged(C++) libraries to the root folder of your project. Now, you are able to use BrainFlow API in your Unity project. For demo we will create a simple script to read data. Add a game object to the Scene and attach script below. using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using brainflow; using brainflow.math; public class SimpleGetData : MonoBehaviour { private BoardShim board_shim = null; private int sampling_rate = 0; // Start is called before the first frame update void Start() { try { BoardShim.set_log_file("brainflow_log.txt"); BoardShim.enable_dev_board_logger(); BrainFlowInputParams input_params = new BrainFlowInputParams(); int board_id = (int)BoardIds.SYNTHETIC_BOARD; board_shim = new BoardShim(board_id, input_params); board_shim.prepare_session(); board_shim.start_stream(450000, ""); sampling_rate = BoardShim.get_sampling_rate(board_id); Debug.Log("Brainflow streaming was started"); } catch (BrainFlowException e) { Debug.Log(e); } } // Update is called once per frame void Update() { if (board_shim == null) { return; } int number_of_data_points = sampling_rate * 4; double[,] data = board_shim.get_current_board_data(number_of_data_points); // check for api ref and more code samples Debug.Log("Num elements: " + data.GetLength(1)); } // you need to call release_session and ensure that all resources correctly released private void OnDestroy() { if (board_shim != null) { try { board_shim.release_session(); } catch (BrainFlowException e) { Debug.Log(e); } Debug.Log("Brainflow streaming was stopped"); } } } After building your game for production don’t forget to copy Unmanaged(C++) libraries to a folder where executable is located. Unreal Engine¶ We provide Unreal Engine Plugin with instructions how to compile and use it. Check Readme for installtion details. This blog post can help if you want to write your own plugin or extend existing one.
https://brainflow.readthedocs.io/en/stable/GameEngines.html
CC-MAIN-2021-39
refinedweb
407
52.15
About The Author Clayton Anderson is a partner at The BHW Group in Austin, TX. Outside of work, he is a total music nerd, and enjoys reading, Belgian beers, and playing board … More about Clayton… Why. Further Reading on SmashingMag - How To Scale React Applications - Test Automation For Apps, Games And The Mobile Web - Server-Side Rendering With React, Node And Express - Notes On Client-Rendered Accessibility This article will explain why I think you should consider using React Native, by providing an overview of the framework and what I believe to be its best features. React Overview Described by its creators as “A JavaScript library for building user interfaces”, React focuses on the view portion of your application. In more concrete terms, this means that when writing a React Native app, your view code will consist of writing React components, which are small pieces of code that describe how a portion of your app should look based on some set of input data. Let’s look at a small example component which can be used to display a simple button. (I am omitting styles for the sake of clarity.) const Button = React.createClass({ propTypes: { onPress: React.PropTypes.func.isRequired, text: React.PropTypes.string.isRequired, }, render() { return ( <TouchableOpacity onPress={this.props.onPress} style={...}> <Text style={...}>{this.props.text}</Text> </TouchableOpacity> ); } }); This Button component has two pieces of input data: onPress, which is a callback function for when the button is pressed; and text, which is the string to display inside the button. The XML-like structure you see returned by the render function is called JSX, which is syntactic sugar for React function calls. And TouchableOpacity and Text are existing components that are included with React Native. Now that this Button component has been created, it can be used many times throughout the application, with consistent behavior and styling. While this is a simple example, it demonstrates how a React app is built, piece by piece. Continuing in this manner, you can create components that represent increasing layers of abstraction. For example, you might create a ButtonGroup component that contains several connected buttons. And building on top of that, you can write components that represent entire screens. Even as your app gets significantly larger, components remain understandable and manageably sized at each level. Truly Native Most mobile apps built with JavaScript use Cordova, or a framework built on top of it, such as the popular Ionic or Sencha Touch. With Cordova, you have the ability to make calls to native APIs, but the bulk of your app will be HTML and JavaScript inside a WebView. While you can approximate native components – and it is certainly possible to build a great UI with HTML and JS – no Cordova app will match the look and feel of a real native app. The little things - like scrolling acceleration, keyboard behavior, and navigation - all add up and can create frustrating experiences for your customers when they don’t behave as expected. Although you still write JavaScript with React Native, the components you define will end up rendering as native platform widgets. If you are familiar with React for the web, you’ll feel right at home. And if you have written apps in Java or Objective-C, you’ll immediately recognize many of React Native’s components. React’s best feature when it originally launched for the web was making your app’s view layer a pure output of state. As a developer, this means that instead of imperatively making changes to view components (for example, programmatically altering the text or color of a button by calling a function on it), you simply define what your view should look like based on input data, and React intelligently makes the changes for you when the state changes. This shift in thinking can drastically simplify building UIs. We’ve all used apps where the UI enters a weird unintended state after taking a path the developer didn’t expect. With React, bugs like this are much easier to track down. You don’t have to think as much about the user’s path through the system, instead focusing on making sure your view declarations can handle all possible shapes for your app’s state. This is a much easier problem to solve - and to test for. It is also more easily understood by the computer, so improvements to static analysis and type systems will only make these bugs easier to find. React Native component definitions look and behave pretty much just like React for web components, but target native UI widgets instead of HTML. So instead of using a <div>, you would use a <View> (which on iOS gets rendered to a native UIView, and on Android, android.view). When your components’ data changes, React Native will calculate what in your view needs to be altered, and make the needed calls to whatever native UI widgets are displayed. And it is fast! JavaScript isn’t as fast as native code can be, but for most tasks, JavaScript and React Native are more than capable of keeping your app running at 60 frames per second. Under the hood, your JavaScript code is run on its own thread, separate from the main UI thread. So even when your app is running complex logic, your UI can still be smoothly animating or scrolling at 60fps, so long as the UI isn’t blocked by the JS thread. Many software frameworks promise that they will let you make a great app for Android and iOS, but the product frequently ends up somewhere in the middle without feeling truly native to either. By embracing the native platforms while still letting your app share the majority of its codebase between platforms, React Native enables developers to make awesome native apps their customers will love, without the increase in budget building two separate apps could entail. Ease Of Learning One of React’s greatest strengths is how readable it is, even to those unfamiliar with it. Many frameworks require that you learn a long list of concepts that are only useful within that framework, while ignoring language fundamentals. React does its absolute best to do the opposite. As an example, consider the difference between rendering a portion of a list of friends in React Native vs Ionic (AngularJS). With Ionic, you use the ngRepeat directive. Let us say we have an array of friends, each of which contains the following fields: first_name, last_name and is_online. But we only want to show those friends that are currently online. Here is our controller: function FriendCtrl($scope) { $scope.friends = [ { first_name: 'John', last_name: 'Doe', is_online: true, }, { first_name: 'Jane', last_name: 'Doe', is_online: true, }, { first_name: 'Foo', last_name: 'Bar', is_online: false, } ]; } And here is our view: <div ng- <ul> <li ng- {{friend.last_name}}, {{friend.first_name}} </li> </ul> </div> If you aren’t familiar with Ionic/AngularJS, this code snippet raises some immediate questions. What is $scope? What is the syntax for filter? And how would I add additional behavior, like sorting the list of friends? With React Native, you make use of your existing knowledge of language fundamentals, using the built-in filter and map functions. const DemoComponent = React.createClass({ render() { const friends = [ { first_name: 'John', last_name: 'Doe', is_online: true, }, { first_name: 'Jane', last_name: 'Doe', is_online: true, }, { first_name: 'Foo', last_name: 'Bar', is_online: false, } ]; return ( <View> {friends .filter(f => f.is_online) .map(f => <View>{f.last_name}, {f.first_name}</View>)} </View> ); } }); While the React Native snippet still raises some questions (What does React.createClass do? What is render?), the fact that the bulk of the code here is just regular JavaScript means it will be more understandable and maintainable to newcomers. As an experienced developer, using standard language features you already know will save you time, and make your code more understandable to other developers. But just as importantly, if you are less experienced with JavaScript, React serves as an excellent teaching tool. If you haven’t yet learned how to use map or filter, learning React will teach you those too. Learning ngRepeat only teaches you ngRepeat. And that is before considering multiplatform mobile development. While there will be some pieces of platform-specific code in a React Native project that targets both iOS and Android, the majority will be shared and all of it will be understandable to a JavaScript developer. Vibrant Ecosystem Since the majority of your React Native code is just plain JavaScript, it reaps the benefits of all the advancements in the language and its ecosystem. Instead of waiting on your framework developers to implement all the array manipulation functions you want, why not just use lodash? For manipulating or displaying dates and times, just use Moment.js. And all those amazing new ES6 language features you’ve been waiting to try out? Not only is React a great fit, their use is encouraged! Thanks to its declarative views, certain libraries are particularly suited for use with React Native. One I’d be remiss not to mention is redux. Described as a “predictable state container”, redux is an awesome library for manipulating your application’s state. Redux is highly testable, and encourages writing small functions that are explicit about what data they change. Once your state changes are written this way, your app can take advantage of powerful features, like global undo/redo and hot reloading. Developer Experience Happy developers are productive developers, and React Native has a great development environment. Instead of repeatedly waiting for your code to compile and your app to restart while making tiny edits, changes to a React Native codebase are made to your running app without the need to restart (see a demo of that here). And if you’ve written any JavaScript before, you’re probably already familiar with the Chrome developer tools. When running React Native in development mode, you can attach to your desktop Chrome browser, so you’ll be right at home with its debugger and profiling tools. Attaching to Chrome works either in the simulator or connected to a physical device. For creating your app’s layout, React Native uses flexbox. While every layout engine has its own learning curve, upsides and downsides, React Native’s support for flexbox means you can use the exact same layout code for Android, iOS and web, instead of learning three different engines. And Beyond! React Native apps consist entirely, or close to that, of JavaScript. If you let your mind wander, this opens up a world of opportunities. Code Sharing We’ve already discussed how React Native can share code between Android and iOS, but what about the web? Anything in a React project that doesn’t directly tie to a native platform is already sharable. Think about an app that can render on the server, in a web browser, or on Android or iOS - all driven by one shared codebase. While we aren’t quite there yet, the community is working on it. Keep an eye on the react-native-web project. Live Updates Anyone who has shipped an iOS app has experienced the frustration of waiting for App Store approval. With React Native, it is possible to do live updates to your app without going through the App Store - much like for a web app. Since the bulk of your app will be JavaScript, you can fetch updates on the fly over the network. There are already services to help with this like AppHub, or you could build it yourself. As long as your app is aware of what version it is running and knows how to check the server for a newer version, you can publish updates to your app whenever you like. Long app approval times aren’t a problem on Android, but you can still use live updates as a way of guaranteeing your customers have the latest and greatest version of your app installed. Conclusion Between the ease of development, quality of the apps built with it, and the richness of the platform and ecosystem, I’ve had a lot of fun learning and building with React Native. If you want to learn more, check out the links below! Resources - A Deep Dive into React Native - React Native Tutorial - Removing User Interface Complexity, or Why React is Awesome - React Cheatsheet
https://www.smashingmagazine.com/2016/04/consider-react-native-mobile-app/?utm_source=javascriptweekly&utm_medium=email
CC-MAIN-2019-22
refinedweb
2,045
60.24
Haskell/Control structures Haskell offers several ways of expressing a choice between different values. We explored some of them through the Haskell Basics chapter. This section will bring together what we have seen thus far, discuss some finer points and introduce a new control structure. if and guards revisited [edit]) like in many imperative languages[1]. As a consequence, in Haskell the else is mandatory.. The example above, for instance, does look neater with guards: describeLetter :: Char -> String describeLetter c | c >= 'a' && c <= 'z' = "Lower case" | c >= 'A' && c <= 'Z' = "Upper case" | otherwise = "Not an ASCII letter" Remember that otherwise it is just an alias to True, and thus the last guard is a catch-all, playing the role of the final else of the if expression. Guards are evaluated in the order they appear. Consider a set up similar to. (And of course if neither pattern matches nor any predicate is true for the matching pattern there will be a runtime error. Regardless of the chosen control structure, it is important to ensure all cases are covered.) Embedding if expressions [edit], one-liner if expressions more complicated than the one in this example would be annoying to read, making let and where attractive options in such cases. case expressions [edit]. Of course, you could do that with an if-statement (with a condition of null str to pick the empty string case), but using a case binds variables to the head and tail of our list, which is convenient for what we are doing., though the resulting definition is not very readable. Controlling actions, revisited [edit] On the final part of this chapter we will take advantage of having just introduced case expressions to introduce a few extra points about control structures while revisiting the discussions in the "Simple input and output" chapter. There, on the Controlling actions section, we used this function to show how to execute actions conditionally within a do block using if expressions:!" We can write the same doGuessing function using a case statement. To do this, we first introduce the Prelude function compare, which takes two values of the same type (in the Ord class) and returns a value of type Ordering, namely!" The dos after the ->s are necessary on the first two options, because we are sequencing actions within each case. A note about return [edit] Now, we are going to dispel a possible source of confusion. In a typical imperative language - say, C - an implementation of doGuessing might look like this (if you don't know C, don't worry with the details and, with an if that ... but it won't work! If you guess correctly, the function will first print "You win!," but it will not exit at the return (); following to the if expression instead and checking] , and that return () [edit] - ↑ If you programmed in C or Java, you will recognize Haskell's if/then/else as an equivalent to the ternary conditional operator ?:. - ↑ To see why it is so, consider our discussion of matching and binding in the Pattern matching section - ↑ That makes casestatements one of getLine. Do not worry if that doesn't make sense for now; you will understand what returnreally does when we actually start discussing monads further ahead on the book.
http://en.wikibooks.org/wiki/Haskell/Control_structures
CC-MAIN-2013-20
refinedweb
548
59.03
Proposed features/building entrance Rationale A place to enter a building. This is an important amenity when planning a route that includes the interrior and exterrior of buildings. For example, the fastest way to get from one location to another could be through another building, but in order to go through a building one must first determine where the entrances are. Another important issue is determining what kinds of entrances a building has, because a person with a mobility impairment might not be able to go up/down a set of stairs to go inside or leave a building. Additionally, those entrances might have different access privledges depending on the user's purpose for using the building; for example employees may have a private entrance to a building that is not availible to the general public. Examples Applies to A building_entrance would be part of a Building tag, since it is part of a building. Optional building_entrance:ramp=yes/no building_entrance:steps=yes/no building_entrance:auto_open=yes/no building_entrance:access_button=yes/no All of the above optional tags would be useful in route planning for people with mobility impairments. building_entrance:private_entry=yes/no building_entrance:public_entry=yes/no These two tags would be helpful when doing route planning in areas that have many entrances used by people of differing status. For example, in a shopping area there may be private areas for vendors and custodial workers, but everything else is availible to the general public. building_entrance:loading_dock=yes/no This would be useful in route planning for delivery people so that they can easily figure out where to unload goods. Rendering Each entrance should be rendered differently depending on the accessibility of that entrance. The default should be a break in the outline of the building with two lines sticking out like an open door would. - Micromapping - mapping features that become important at 1:5,000 scale or less - is a relatively unexplored area of OSM but an important future direction and I am glad to see this effort and support it. MikeCollinson 09:20, 12 March 2008 (UTC) - May I suggest using building=building_entrance instead of amenity=building_entrance. This would make macro-level searches for amenities easier and would fit in with the informal but widely used building area tag. MikeCollinson 09:20, 12 March 2008 (UTC) - You might also want to consider extending the tagging to ways and assessing any impact. If folks start working on the level of individual buildings rather than an entire (large?) campus, they may want to represent the actual approx width of entrances using lines rather using single points. MikeCollinson 09:20, 12 March 2008 (UTC) - Also see Relations/Proposed/Buildings for a proposal to connect entrance points to the building they provide access to. --Frederik Ramm 09:50, 12 March 2008 (UTC) - I too like this micro-level scheme, but would prefer building=building_entrance rather than amenity Chillly 10:37, 12 March 2008 (UTC) - This should be IMHO combined with Proposed_features/House_numbers as entrances are often numbered or have other markings (House number 1, with entrances A, B, C, D, (Map example: [1]) --Onion 12:14, 12 March 2008 (UTC) - I would agree with Chilly and MikeCollinson, building=building_entrance sounds better to me. However if you change to building= then building=entrance might be enough. --Ckruetze 22:09, 12 March 2008 (UTC) - Would it make sense to use the "access=private" that is currently being proposed at Proposed_features/access:_name_space instead of building_entrance=private_entry. This would also allow someone to specify when a building entrance is accessible as well -- ex. doors locked at night. Having private_entry/public_entry would disallow an entrance from having a access button or a ramp if I understand OSM correctly(sorry if I getting this wrong -- I'm new at this). Also, what if an entrance has a ramp and a access button? How about something like: building=entrance building_entrance:ramp=yes/no building_entrance:steps=yes/no building_entrance:auto_open=yes/no building_entrance:access_button=yes/no building_entrance:loading_dock=yes/no access fields from access namespace --Untoldone 04:37, 2 April 2008 (BST) - Assuming we use the access=* tagset (and we should because building_entrance=public_entry|private_entry does nothing that access=* and friends don't already allow), Wheelchair accessibility should additionally be marked with Proposed_features/wheelchair when it is accepted. Defining with reference to other schemes is good and healthy. I interpret an entrance tagged access=public as meaning not only that access is permitted for the general public, but also that the entrance is for the general public, and that the general public are the intended users. Otherwise, I like the scheme as it stands right now; the only thing I can think of adding is that there's sometimes a hierarchy amongst even public entrances: a confusing hospital complex near here has a "Main Entrance" and an "Old East Entrance" for the main warren. Most people are supposed to use the former. Encouraging and recommending use of name=* for this ought to be sufficient, though. --achadwick 16:38, 31 May 2008 (UTC) - How do we tag entrances to other things like a cemetry? If the building has multiple entrances how to tag the main entrance? --Bollin 19:41, 13 June 2008 (UTC) - These are good points. Maybe entrance=yes would be a better idea for this tag, so that entrances are not only tied to buildings but can also work with parks, cemetaries, playgrounds, pitches or anything else with a fence. Bitplane 15:29, 24 January 2009 (UTC) - I strongly agree that it should not be tagged as an amenity. While I don't believe in avoiding amenity for the sake of it, it should only be used for amenities, which a building entrance isn't really. entrance=yes seems to have the broadest application. Daveemtb 07:15, 17 September 2009 (UTC) - I would strongly recommend a method that is closer to currently used syntax: entrance=yes/no entrance:steps=yes/no entrance:*=yes/no (* is all your ideas) - and as this should work on big buildings too we should tag the real entrancepoint - a node - with that. A big building can have :more than one entrance. See also: Relations/Proposed/Buildings - If we wanted to tag a main-entrance this should IMHO also be done via relations. --NobodysNightmare 07:22, 22 September 2009 (UTC) - Is there not already a pretty recognised way to tag entrances. This should just be an extension of that system, adding access tags, wheelchair etc. See Tag:building=entrance Martin Renvoize 22:41, 9 December 2009 (UTC)
http://wiki.openstreetmap.org/wiki/Proposed_features/building_entrance
crawl-003
refinedweb
1,092
57.4
Simple C# Threading and Thread Safety A few days ago I compared and contrasted Asynchronous and Parallel Programming. Today I would like to walk you through a very simple threading example in C#, and why the concept of “thread safety” is important to know before you start writing parallel applications. Since we already know what exactly parallel programming is, and how it is different from asynchronous calls we can go ahead and drill down to some more aspects of parallel programming. So here is an application that will start a new thread from the main, and both threads will call the same method: using System; using System.Threading; class Threading101 { static bool fire; static void Main() { new Thread(FireMethod).Start(); // Call FireMethod() on new thread FireMethod(); // Call FireMethod() on main thread } static void FireMethod() { if (!fire) { Console.WriteLine("Method Fired"); fire = true; } } } Now at first glance you might say that we will only see “Method Fired” shown on screen, however when we run the program we will see this output: Well we have obviously called the method on both threads, but we got an undesired output! This example shows the clear issues you will encounter when working with threads in C#. This method is defined as thread unsafe and does not work correctly (in its current state) when used in threading applications. So what can we do about this? Well we need some method of preventing a thread from entering a method when another thread is entering a critical part of the method. So we just have to update our code to account for some type of locking functionality and then re-work our application: using System; using System.Threading; class Threading101 { static bool fire; static readonly object locker = new object(); static void Main() { new Thread(FireMethod).Start(); // Call FireMethod() on new thread FireMethod(); // Call FireMethod() on main thread } static void FireMethod() { // Use Monitor.TryEnter to attempt an exclusive lock. // Returns true if lock is gained if (Monitor.TryEnter(locker)) { lock (locker) { if (!fire) { Console.WriteLine("Method Fired"); fire = true; } } } else { Console.WriteLine("Method is in use by another thread!"); } } } Running the code above now produces a better threading result: Now that looks better! We made sure that only a single thread could enter a critical section of the code, and prevent other threads from stepping in. We first use Monitor.TryEnter(locker) to check for a lock, and if there is no lock we step in and run our code. If there is already a lock, we have added the logic to print that result to screen. Pretty simple huh? So this little app spawns an extra thread, and both threads fire the same method. However, the variable is only changed once, and the message from the method is only printed once. The first snippet is a perfect example of a method that is not thread safe, and the second one is a great way to protect that same method.
https://urda.com/blog/2010/10/06/simple-c-threading-thread-safety
CC-MAIN-2022-21
refinedweb
491
71.24
Hi. I would like to learn Ruby on Rails to build my next dynamic website. Firs tof all, tell me please will I regret my choice for any reason? Is there anything related to Ruby on Rails that make it not good choice? I want to know what should I learn first? My background is only HTML and CSS. Should I learn Ruby language then move to Ruby on Rails Framework or what? Regards. In my experience it depends on situation actually. I will choose one of the path below. I would prefer to learn the language and then framework if I have enough time to work on. ( perfect way) else with the decent level of technical information, I will start with good working samples and do a backward approach in learning ( fastest way) With the knowledge level you have, could decide the path. In your case I would suggest 1st path. (if you programming knowledge all that differs between language is the syntax) You will most certainly not regret it I still don't know all the ins and outs of the Ruby language itself and am highly productive with Rails. It's quite a natural and easy language to pick up while learning Rails.Because it's your first programming language there will be a steep learning curve. You need to learn about programming concepts like loops and methods, a bit about databases etc.. Still, check out and start working through from top to bottom and we'll be able to help if something doesn't make sense. -- Normally I would recommend you learn Javascript before a back-end programming language, but I guess I learned PHP before Javascript so it doesn't really matter. Javascript is certainly something you want to know about though, so keep that in mind. Check out this link to learn ruby on rails. , In this site you can get all points step by step. For one, Michael Hartl's site is probably the best gateway into Rails: Then [ makes learning rails into more of a game-like experience. If that works for you, you could also try [URL=""]tryruby.org]() for the ruby language. Both of the latter two sites are linked with an interesting place but costs $25US per month. And you can try for Why's Poignant Guide To Ruby. I can guarantee you it's the most unusual language manual you'll ever find; not often you get cartoon foxes to teach you how a language works. Although I agree with what you've said the lack of any other programming experience on the OPs part could be to their advantage as Ruby is different to other languages in is execution. The syntax is quite unlike most other languages I'm finding. I'm just starting out with it myself and finding some oddities to it but it's just my way of thinking as I've conditioned my self to expect certain things from a language, so it might be good that his/her head hasn't been poisoned by anything else...<cough>php</cough>. I'm working my way through the Michael Hartl book (can recommend it) and I can see how well structured and succinct in code the whole ROR dev processes is but coming from a PHP background I'm finding the concept of not adding ; at the end of a command or {} around statements/loops to be quite odd or defining a method as simply as def my_method do something end just doesn't feel right at the moment. Plus where Rails is concerned, well, it's almost like pixies run the show. Things just work without much effort, length or explanation which is disconcerting starting out but I do like the experience so far. Sand boxing your work in the rails console for experimentation of new code for example is just fantastic. Despite the alien nature of ROR so far I will say this based on my limited exposure thus far. I can appreciate already how beautiful a language Ruby is once understood and how fantastically cleaver and powerful Rails is as a technology and framework, there is so much power available. If you can master them both and the whole process, concepts and other technologies that seem to naturally stick to ROR, then being a dev could be fun and rewarding again. Pick it up now because in a few years time I can see it exploding in popularity once the naysayers realize the errors of their ways in putting it down, many of which I have to say are PHP developers it seems. Although not all, as many going to ROR seem to be disgruntled PHP devs. I'm not exactly an expert in the matter but I've never felt comfortable using PHP in a framework. I've always liked using my own code or doing it my way as I've never liked any of the frame works. Most are just hodge podge and off the shelf applications are a nightmare to use in my view...wordpress, joomla etc, horrible! One area the ROR team needs to fix is installation and set up. It is a pain in the rear to get ROR set up, configured and running at the moment I feel. I guess this is an area that will be improved as the platform matures and grows, it has to if they want more uptake as right now I feel it is definitely a barrier to entry and putting many off particularly in the commercial world. Yes and no. It's unlike languages descending through the C "tree" of languages. It has more in common in that respect with the LISP/Smalltalk branches. Well, you can use them if it makes you feel better, but better is to just remember the begin...end contructs in ruby can be considered synonyms for the {} in PHP. Best practices seem to favor using the {} option when it's all on one line, and begin/end when it spans multiple lines. Don't feel bad. The amount of "magic" encountered in Rails disconcerts (or worse) all of us from time to time. Actually, you'll run into a lot more disgruntled java programmers in ruby, which I find fascinating, considering the effort PHP has been putting in recently to look like java. Ruby, and Rails in particular, I think has reached "the dip" in its popularity curve. It's no longer the "new shiny" on the scene (that's node.js) so the next couple of years will tell whether it can sustain its growth as it matures. It may continue to slide out of sight or, after a brief drop, rise even faster. It may sound heretical to some, but while I'm fairly sure ruby will remain a player, I'm not so sure about Rails. I think we may see some new framework ideas spring up in the next few years following other paradigms than MVC. It'll be interesting. is a great place to start, also you should create anything that came to your mind ROR is more than just a framework. In Ruby, I would consider OOP as a part of basics, because in Ruby, everything is an object. I would like to learn more Ruby on Rails to build my next website in ROR. Go to rubyonrails.org and look at their "Blog in 15 minutes" screencast to get excited.Get a copy of O'Reilly Media's Learning RubyGet a Mac or Linux box.. For me Agile Web Development with Rails was the best starting point. Before that I tried following Michael Hartl's site () but I found the book more easy to follow. You can start with either and pay attention they are using different testing methods (TestUnit vs. Rspec) so you can also start grow a taste on which of the two you prefer. Then, you can either read some ruby book in fast forward or start your app right away. Railscasts is also a great source for novice and advanced users. you must download video tutorials with practice files so that by seeing videos, you may learn RoR easily. You can download it from lynda(dot)com or you can make a search on internet. just Jump Start Rails Jump Start Rails
http://community.sitepoint.com/t/how-can-i-learn-ruby-on-rails/22250
CC-MAIN-2015-27
refinedweb
1,391
70.53
How Haptik generates images on the fly with Python - Part 2 Vinay Jain Updated on ・5 min read (How Haptik generates images on the fly with Python), I recommend you take a glance at it first, to get a better understanding of this post. For now, we know how to draw text, change the font, and position the text on the image. In this post, we’ll discover how to draw multi-line text and also discuss the challenges of doing so.: The idea is to split the long sentences into multiple shorter sentences and draw each of these, one by one at the correct positions thereby making it look like a multi-line text. To split a longer line, we‘ll use a Pillow function to calculate the size of the text passed to it as one of the parameters. Calculate text width For convenience, I’ve created a method text_wrap() to explain the line-split logic: from PIL import Image from PIL import ImageFont from PIL import ImageDraw def text_wrap(text, font, max_width): lines = [] # If the width of the text is smaller than image width # we don't need to split it, just add it to the lines array # and return if font.getsize(text)[0] <= max_width: lines.append(text) else: # split the line by spaces to get words words = text.split(' ') i = 0 # append every word to a line while its width is shorter than image width while i < len(words): line = '' while i < len(words) and font.getsize(line + words[i])[0] <= max_width: line = line + words[i] + " " i += 1 if not line: line = words[i] i += 1 # when the line gets longer than the max width do not append the word, # add the line to the lines array lines.append(line) return lines def draw_text(text): # open the background file img = Image.open('background.png') # size() returns a tuple of (width, height) image_size = img.size # create the ImageFont instance font_file_path = 'fonts/Avenir-Medium.ttf' font = ImageFont.truetype(font_file_path, size=50, encoding="unic") # get shorter lines lines = text_wrap(text, font, image_size[0]) print lines # ['This could be a single line text ', 'but its too long to fit in one. '] if __name__ == __main__: draw_text("This could be a single line text but its too long to fit in one.") -: text = "This could be a single line text but it can't fit in one line." lines = text_wrap(lines, font) for line in lines: print font.getsize(line)[1] # Output # 62 # 51 Finding correct height for characters like g, j, p, q, y which are drawn below the Baseline and b, d, f, h, k, l which are drawn above the Median is a little tedious due to varying heights.. text = "This could be a single line text but it can't fit in one line." lines = text_wrap(lines, font) line_height = font.get_size('hg')[1] print line_height # Output # 62: text = "This could be a single line text but its too long to fit in one." lines = text_wrap(text, font, image_size[0]) line_height = font.getsize('hg')[1] x = 10 y = 20 for line in lines: # draw the line on the image draw.text((x, y), line, fill=color, font=font) # update the y position so that we can use it for next line y = y + line_height # save the image img.save('word2.png', optimize=True) This will output an image like this: I did a good job? Let me know in the comments below. This post was originally written on the Haptik Tech Blog.
https://dev.to/vinayjn/how-haptik-generates-images-on-the-fly-with-python---part-2-2fo9
CC-MAIN-2020-16
refinedweb
584
69.52
Class::Refresh - refresh your classes during runtime version 0.07 use Class::Refresh; use Foo; Class::Refresh->refresh; # edit Foo.pm Class::Refresh->refresh; # changes in Foo.pm are applied During development, it is fairly common to cycle between writing code and testing that code. Generally the testing happens within the test suite, but frequently it is more convenient to test things by hand when tracking down a bug, or when doing some exploratory coding. In many situations, however, this becomes inconvenient - for instance, in a REPL, or in a stateful web application, restarting from the beginning after every code change can get pretty tedious. This module allows you to reload your application classes on the fly, so that the code/test cycle becomes a lot easier. This module takes a hash of import arguments, which can include: use Class::Refresh track_require => 1; If set, a require() hook will be installed to track modules which are loaded. This will make the list of modules to reload when refresh is called more accurate, but may cause issues with other modules which hook into require (since the hook is global). This module has several limitations, due to reloading modules in this way being an inherently fragile operation. Therefore, this module is recommended for use only in development environments - it should not be used for reloading things in production. It makes several assumptions about how code is structured that simplify the logic involved quite a bit, and make it more reliable when those assumptions hold, but do make it inappropriate for use in certain cases. For instance, this module is named Class::Refresh for a reason: it is only intended for refreshing classes, where each file contains a single namespace, and each namespace corresponds to a single file, and all function calls happen through method dispatch. Unlike Module::Refresh, which makes an effort to track the files where subs were defined, this module assumes that refreshing a class means wiping out everything in the class's namespace, and reloading the file corresponding to that class. If your code includes multiple files that all load things into a common namespace, or defines multiple classes in a single file, this will likely not work. The main entry point to the module. The first call to refresh populates a cache of modification times for currently loaded modules, and subsequent calls will refresh any classes which have changed since the previous call. Returns a list of modules which have changed since the last call to refresh. This method calls unload_module and load_module on $mod, as well as on any classes that depend on $mod (for instance, subclasses if $mod is a class, or classes that consume $mod if $mod is a role). This ensures that all of your classes are consistent, even when dealing with things like immutable Moose classes. Unloads $mod, using Class::Unload. Loads $mod, using Class::Load. This is because it's not easily possible to tell if a module has been modified since it was loaded, if we haven't seen it so far. A workaround for this may be to set the track_require option in the import arguments (see above), although this comes with its own set of caveats (since it is global behavior). Perl resolves accesses to global variables and functions in other packages at compile time, so if the package is later reloaded, changes to those will not be noticed. As mentioned above, this module is intended for refreshing classes. If you modify a file and then immediately call refresh and then immediately modify it again, the modification may not be seen on the next call to refresh. Note however that file size and inode number are also compared, so it still may be seen, depending on if either of those two things changed. usea given module isn't possible For instance, modifying a Moose::Exporter module which is used in a class won't cause the class to be refreshed, even if the change to the exporter would cause a change in the class's metaclass. If a class is defined across multiple files, there's no easy guaranteed way to restore the entire state of the class, since there may be load order issues. This includes Moose classes which have make_immutable called on them from outside of the class file itself. Also, files which define multiple classes cause problems since we can't always determine which classes are defined in the file, and so reloading the file may cause class definitions to be run more than once. This module attempts to handle several cases of this sort for Moose classes (modifying a class will refresh all of its subclasses, modifying a role will refresh all classes and roles which consume that role, modifying a metaclass will refresh all classes whose metaclass is an instance of that metaclass), but it's not a problem that's solvable in the general case. This will require modifications to Moose to support properly. Refreshing a class which is its own metaclass will likely break. Please report any bugs to GitHub Issues at. You can find this documentation for this module with the perldoc command. perldoc Class::Refresh You can also look for information at: This module was based in large part on Module::Refresh by Jesse Vincent..
http://search.cpan.org/~doy/Class-Refresh-0.07/lib/Class/Refresh.pm
CC-MAIN-2016-26
refinedweb
885
57
This article was originally published on my website. In this article we will go over the basics of Keras. We will discuss what Keras is, why we should use it as well as the steps we can take to build an simple image classifier. What is Keras? Keras is an open-source high-level neural network library written in Python. It is capable of running on top of TensorFlow, CNTK and Theano. Why use Keras? Keras is an excellent tool for deep learning especially for beginners. It’s main focus is enabling fast experimentation using easy to understand and clear syntax. Because it runs on top of Tensorflow or Theano you can train on both CPU and GPU without problems. Installing Keras For installation you can use the Python Package Manager(pip) or you can clone the github repsitory and install that way. pip install: pip install keras install using git git clone cd keras sudo python setup.py install Load in dataset The Keras libary has a few datasets which you only need to import like the mnist or cifar100 dataset. We can load them in using the keras.datasets module. from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() Create a model In Keras we can use to different methods for creating a model. The Sequential model API is the easier method but it doesn’t include as much possibilities as the Model API. For this article we will create a simple feed forward neural network using the sequential api. Importing Sequential api and layers. from keras.models import Sequential from keras.layers import Dense In Keras you create a model by adding one layer after the other. model = Sequential() model.add(Dense(256, activation='relu')) model.add(Dense(10, activation='softmax')) Compile model Now that we have defined our model we can compile it. When compiling we must specify a few import parameters. Mainly the loss function and the optimizer. We can also specify metrics which we can then see in the training process. When we compile the backend libary we are using (Tensorflow or Theano) is choosing the best way to train our model on the given hardware. model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) Fit model on training data We have defined our model and compiled it so now we are ready to fit our model on the training dataset. To fit our model we use the fit() method. We need to pass it our X and Y data as well as the number of epochs and the batch size. Epochs are the number of times we train over the whole dataset and the batch size specifies how many training examples we will load into memory at once. We can also pass it an validation_dataset so we can see the performance on both training and testing set. Preprocessing data: from keras.utils import to_categorical y_train = to_categorical(y_train, num_classes=10) y_test = to_categorical(y_test, num_classes=10) x_train = x_train.reshape(len(x_train), 28*28) x_test = x_test.reshape(len(x_test), 28*28) print(x_train.shape) print(x_test.shape) Now that we have preprocessed our data we can fit our model. We will save the results so we can visualize them in the next step. history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test)) As you can see we are getting pretty bad results and that is because of two main reasons. First of we aren’t training a lot of epochs and secondly the model structure is really basic. You can get better result by implementing a convolutional neural network(CNN). If you are interested you can check out my video on CNNs in Keras here. Visualizing the training process. We can visualize our training and testing accuracy and loss for each epoch so we can get intuition about if our model is overfitting or underfitting. We can get the accuracy and loss data from the history variable. We will use Matplotlib to graph it. import matplotlib.pyplot as plt plt.plot(history.history['acc'], label='training accuracy') plt.plot(history.history['val_acc'], label='testing accuracy') plt.title('Accuracy') plt.xlabel('epochs') plt.ylabel('accuracy') plt.legend() plt.plot(history.history['loss'], label='training loss') plt.plot(history.history['val_loss'], label='testing loss') plt.title('Loss') plt.xlabel('epochs') plt.ylabel('loss') plt.legend() In the graphs above we can see that our model isn’t overfitting as well as that we could train more epochs because the validation loss is still decreasing. Summary In this article, we went over what Keras is. How to install it as well as a step by step guide on how to use it including: - Creating a model - Compiling the model - Training the model - Visualizing the training process If you liked this article consider subscribing on my Youtube Channel and following me on social media. If you have any questions fell free to dm me on Twitter or leave a comment. Source: Deep Learning on Medium
http://mc.ai/keras-introduction/
CC-MAIN-2019-09
refinedweb
829
58.18
Im a newbie to the c, c++ enviroment, but im actually coming along pretty well. I d/led borland 5.5 free compiler, and i also have djgpp! I was able to make a simple prog using this code: #include <stdio.h> int main(void) { printf("Hello World!\n"); return 0; } 'and it works. Now i went to a lot of websites with beginning tutorials that did this same prog but in a different way: #include <iostream.h> int main() { cout << "Hello World!"; return 0; } 'This doesn't work for me!! And a lot of tutorials use this method, i want to learn more , but i can't follow any tutorials since they use this method. If n e 1 can hlp, its much appreciated. If this is the wrong forum, plz forgive me! lata'
http://cboard.cprogramming.com/cplusplus-programming/9770-iostream-h-help.html
CC-MAIN-2015-18
refinedweb
135
77.74
Agenda See also: IRC log NM: Regrets from TBL ... F2F in a bit over a month ... Local arrangements page is up ... JAR has published the Call for Change proposals: ... Traffic has started to build NM: Approving minutes of 2012-02-16. . . RESOLUTION: approved as minutes for 2012-02-16 NM: this is a minor procedural change ... as signalled in email <noah> close ACTION-598 <trackbot> ACTION-598 Publish as a note what had been the FPWD (Raman's draft) on client side state closed <noah> close ACTION-655 <trackbot> ACTION-655 Check Norm Walsh draft of W3C Note with the TAG, draft cover letter to include with Note, and review that with the TAG closed <Larry> +1 to closing <Larry> do we have follow up actions on XML/HTML task force report? I thought we did <noah> Larry, we have, e.g. ACTION-656 on XML processing, though I think that's substantially addressed with the formation of the XML-ER community group <noah> (repeating for the record) Larry, more to the point I have ACTION-657 Schedule telcon discussion of possible XML/HTML Unification next steps <noah> close ACTION-660 <trackbot> ACTION-660 Integrate input from DKA and Yves for note to Jeff, and draft section on CA Due: 2012-10-17 closed <noah> close ACTION-671 <trackbot> ACTION-671 Respond to Jeff Jaffe, on the public list, using the text agreed on the telcon of 16 Feb 2012 closed NM: Goal today is to commit to a plan for work in this area AM: I've drafted some email, but haven't distributed it pending feedback from RB RB: I think it's a good starting point for discussion, yes AM: What this email will suggest is: ... 1) We have requirements for offline storage ... For example, to be able to run webapps either connected or disconnected, switching ... seamlessly ... And if you run disconnected, any updates you make will get synchronised ... when you connect again, need coherence checks, etc. ... 2) I have private data: medical history, preferences for hotels etc. ... Private, and kept locally, but should be available to apps AM: and should be able to move it to another device ... 3) All of the above should be possible w/o commitment to any particular browser ... So then two directions to go: what are the architectural issues, and what is the state of play wrt various existing implementations <noah> Glad to hear focus on architectural issues, as I think that's where the TAG's focus needs to be. In particular, I'd like to see this get back around to how to use Web mechanisms like URIs, how local storage relates to http-identified resources, etc. (I know, I say this every time we have this discussion) AM: So that's ONE ... Now, TWO: If you have items in local storage, do they have URIs? ... If the do, are they the same as their URIs 'on the web', or are they different? <noah> Right. Those are key architectural points. <darobin> "I suspect that the finding we want is something along the lines of stating that using URIs to identify resources is just as good an idea when a Web application runs on local data (and possibly completely locally) as it is in the more traditional case." <darobin> ("Assign distinct URIs to distinct resources.") <Larry> there is really a question for me about how U a URI for local storage would be <Larry> How does it work to make a URI for local storage? <Larry> A URI for remote storage which is served by a local cache is one thing <darobin> Larry, it's just as U as a URI for a resource that's completely personalised <Larry> do you use "http:" URIs? or some other scheme? NM: There's not just connected vs. disconnected, but also the case where an app switches back and forth, in which case the pressure to use the same URI is greater. . . AM: When looking at for example AppCache, the question comes up: how is it managed? Same as any other cache? <Larry> are there separate URIs for "dropbox" storage? <darobin> Larry, yes, everything works the same—you're just getting data from a local DB <Larry> robin: I don't understand 'works the same', what URI scheme do you use to identify stuff in local storage? <noah> BTW, the tradition in systems that face this connected/disconnected duality is to wind up with two part identifiers: part1 is location independent, and part 2, if available, tends to be a hint as to where to find a local copy. Lotus Notes does this, and I think CloudDB. Hard to do with URIs, I think. <Larry> noah: yes, i think that's the question though, what is the nature of the identifiers we're recommended? How does the generic advice actually get implemented in practice? AM: MNot has suggested things be expired on the basis of the app that cached them, rather than individually JT: In connection with local storage of private data, and non-browser specific functionality JT: What about remote storage, but managed a bit similarly AM: So non-local local storage? JT: Yes <darobin> Larry, this is all fuzzy terminology—you're not identifying things in local storage, you're identifying a resource generated from data in local storage <noah> Larry, I have no idea whether this is up-to-date, but a quick google search for dropbox and URI yields this 2 year old forum entry, suggesting that Dropbox was not at the time using URIs at all <noah> q, say in the Cloud? <Zakim> JeniT, you wanted to ask about 'unhosted' apps, 'web intents' <Larry> robin: ok, fine, but give a use case? <Ashok> Well, perhaps local storage on a Cloud RB: I think 'web intents' are slightly different - - partly because they're not well-defined yet RB: but mostly because they're about accessing specific URIs which have a remote existence LM: I understand the goal, I think, but I'm not coming up with a use case ... E.g. I do understand the case of a URI for a remote object that also works locally, via a cache LM: But I don't have an example in mind for a local-but-reusable URI <Larry> if you have a URI for remote storage but you're accessing a local cache, i understand you can still use http: URIs for that, but I am not sure what URI scheme you would use to talk to local storage which isn't a cache of remote storage. <Larry> do we need new schemes? NM: Agree that we have well-described use cases <darobin> this application uses strictly local data: <darobin> it could have identifiers for individual entries <darobin> (it doesn't because it's supposed to be demonstrating bad practice) <Larry> Robin, what would the URI be for an individual entry? <darobin> Larry, whatever you want, e.g. <Larry> i'd use things like instance ID URIs, personally <Larry> and link to the resource using a GUID <Larry> but i don't know whether the TAG would recommend that architecture <darobin> I'd use the same URIs that I'd use if the data were stored on the server—where things are stored should be a black box <JeniT> darobin, so what -- you'd have code that tests whether the content is available in the local storage and if not resolve the URI? <darobin> JeniT, I'd make use of the History API and some routing mechanism, and then get the data wherever the application dictates that I get it <JeniT> darobin, I'd like to see that :) <darobin> Larry, JeniT, it's like this app It doesn't currently use local data but it's something that it could do—and it would get nice URIs and all <darobin> Larry, JeniT, if you look at the source, you'll see that for any URI it's the same HTML document that gets served (and in app.js there's a router and all you need). If api.js used local storage it would be transparent <Larry> Robin, you see why I'm asking for a worked out use case? I wonder if we'd like the details as much as the general principle NM: So there's a question: can we do everything we need with more-or-less vanilla HTTP caches NM: Possible counterexample: new document creation during disconnection NM: Does this push the boundaries of our understanding of HTTP caching beyond where the RFCs are today? ... Or is it really something quite new/different? NM: Where are we on the Product Page? NM: Close to the above described email draft? AM: Could be used for it, yes <darobin> +1 to Ashok NM: Sounds like from this discussion you should do that AM: OK, I will have a try, get agreement from RB <noah> <noah> NM: That's our baseline ... Please move it forward in the obvious way <noah> ACTION-647? <trackbot> ACTION-647 -- Ashok Malhotra to draft product page on client-side storage focusing on specific goals and success criteria Due: 2012-01-17 -- due 2012-02-14 -- PENDINGREVIEW <trackbot> <noah> ACTION-647? <trackbot> ACTION-647 -- Ashok Malhotra to draft product page on client-side storage focusing on specific goals and success criteria Due: 2012-01-17 -- due 2012-03-06 -- OPEN <trackbot> <noah> ACTION-647? <trackbot> ACTION-647 -- Ashok Malhotra to draft product page on client-side storage focusing on specific goals and success criteria -- due 2012-03-06 -- OPEN <trackbot> <noah> ACTION-572? <trackbot> ACTION-572 -- Yves Lafon to look at appcache in HTML5 -- due 2011-11-29 -- OPEN <trackbot> NM: Correctly carried along with Web Storage YL: AppCache is different from local storage <darobin> I agree with Yves YL: Similar mechanisms, but not the same AM: They collide at the requirement for offline apps ... which is what AppCache does AM: You are perhaps assuming AppCache works in one particular way NM: They appear different because AppCache was seen as being about your code (HTML, JS) ... But going offline means taking your code and your data with you ... So I think they go together YL: Pursue at the same time, sure, but they are not the same subject <HT:> So I think that means we need two clear use cases that illustrate both the differences and the overlap NM: Will we have technical work ready to work with for the F2F? AM: If we can get the Product Page ready quickly, then yes, I hope to have something HT: I think the discussion we had just before this is very important. If you could give us two clear use cases in which both the differences between AppCache and client-side storage and the parallels are clear ACTION-572 Due 2012-03-06 <trackbot> ACTION-572 Look at appcache in HTML5 due date now 2012-03-06 <JeniT> NM: We agreed in September in Edinburgh that we would help with this ... JT has been the first to do so <noah> ACTION-610? <trackbot> ACTION-610 -- Jeni Tennison to draft initial cut at -- due 2012-02-14 -- PENDINGREVIEW <trackbot> NM: Any readers? <Larry> yes <Larry> there's IETF RFC for JSON <Larry> <JeniT> ok, I can swap that in <darobin> +1 to it being good and ready to ship <Larry> should W3C put JSON into webarch? <noah> Mostly, I think it's great. Minor objection: I don't like equating vocabularies with languages. Also, should provide hyperlink for SGML I think. <Larry> should we talk about XML vs. JSON for data communication, tradeoffs? <darobin> JSON is the glue that holds the web together—it should definitely be in WebArch! <noah> Also, I think for novices, the phrase "RDF is a metaformat, actually a metamodel, ..." will be scary rather than helpful <Larry> i'd put XML and JSON together, and RDF as example of how metaformats layer HT: The historical trajectory of the numbers is anybody's guess, but I'm pretty confident that it's still the case that most XML on the Web is produced by machines and is not "documents", it's "data" ... To suggest that XML is primarily more significantly for documents is misleading. <NM:> Hmmm...there's a lot of open office and OOXML on the Web <Larry> "XML is a metaformat based on SGML" is kind of scary and confusing if you don't know what SGML is, and also if you do know what SGML is. JT: I was trying to focus on the differences -- what is special about each of them <jar> +1 "unique strength" <Zakim> noah, you wanted to make a few comments <darobin> I agree that XML is uniquely good at documents <Larry> i wonder how this relates to Wikipedia entries for those terms :) NM: I think it conflates the term vocabulary with the term language <Larry> TIFF is a language NM: The TAG fought about those words for years, and there are strongly held positions that these are different <noah> "creating their own languages, often called vocabularies" <Larry> a vocabulary is a range of values in a protocol element NM: Vocabularies are useful in creating languages <Larry> the words are blurry i admit NM: Would rather say "creating their own languages, or vocabularies for use in those languages" <noah> "creating their own languages, or vocabularies for use in markup as part of those languages" <jar> I think "language" is OK as Jeni has it JT: I can try to unmix them ... There's no deep disagreement here <noah> Also: suggest a hyperlink for SGML <Larry> people use these frameworks to create application-specific "languages" without having to reinvent syntax JT: Give me a URI for SGML and I'll use it :-) <Zakim> Larry, you wanted to give a take <darobin> I'm told that is "SGML on the Web", if you need a link LM: I used to say that XML was the best things since bits [?] ... Syntactic properties independent of the vocabulary ... scope, extensibility, unicode <noah> I think the crucial sentence Jeni has is: "Metaformats offer advantages over creating a custom syntax for a language because they can be processed by generic tools, and languages that use them can be understood by people who have learned about the metaformat." <noah> I think that's great. Don't change it. LM: Language is the way you populate a framework <darobin> I wonder if EXI counts as a metaformat <Larry> EXI is a serialization of XML <noah> I feel like Jeni's already offered to take a cut at changing the 'vocab" bit. I'd just be curious to see what she comes up with. <darobin> Larry, no, EXI is defined as a serialisation of the XDM LM: Specifically, change "often called vocabularies" into a sentence on its own, along the lines NM and I have suggested. <noah> "Populate a syntax" seems a bit clumsy to me. <Larry> noah, I agree it's clumsy <darobin> you could serialise JSON to EXI <darobin> (and soon you will!) <Larry> I'd also take "based on SGML" and turn it into a separate <JeniT> Metaformats are generic syntaxes that people can adopt when creating their own application-specific languages without having to reinvent syntax. The terms that people use within that syntax are often called vocabularies. Examples of metaformats are XML [1], RDF [2] and JSON [3]. Metaformats offer advantages over creating a custom syntax for a language because they can be processed by generic... <JeniT> ...tools, and languages that use them can be understood by people who have learned about the metaformat. JR: Wrt the RDF part, there's no way to describe it that's not harmful ... I don't think the word 'metamodel' is helpful <Larry> <noah> How about, "The semantic web uses a graph-based model for information on the Web. RDF is a metalanguage for encoding and communicating parts of that graph" JR: RDF has too much history/is too varied in its historical trajectory <Larry> meta-data structure <noah> How about, "The semantic web uses a graph-based model for information on the Web. RDF/XML is a metalanguage for encoding and communicating parts of that graph" <Larry> data structures & serialization <noah> N3 is a very different looking metalanguage, also used for communicating RDF graphs." JT: It is still a meta-something, which you can plug your own vocabulary into <darobin> you could argue that BSON is also a metaformat, as an encoding of JSON... if we really want to make the metamodel/metaserialisation thing even more complicated <Zakim> noah, you wanted to point to my proposal JAR: RDF is a lot like the DOM <darobin> Yves: I don't know, but it would be useful yes NM: [reads the above] JT: I don't want to mention RDF/XML or N3, people don't use them NM: So use whatever does get used <Larry> remembering "is Lisp the surface syntax with parentheses, or is it S-expressions?" <jar> RDF is a family of compatible languages with superficially different surface syntaxes <darobin> I wonder if all the distinctions that we're making here matter all that much to the target audience... <Larry> JAR: There's a family of expressions for the RDF HT: Maybe the metalanguage term is unhelpful. NM: Um, well, it's the topic of this page HT: Well, still, maybe we should change it. NM: I think it's serving us well, except that RDF is confusing. <Larry> off topic JAR: I'll try to suggest something for the RDF bit ... But I've never found a good way to explain it NM: Narrowly, we have a draft, with some offers of help with further work ... and that's good <Larry> i don't think these pages need to be perfect, just need to be better-than-blank <noah> ACTION-610? <trackbot> ACTION-610 -- Jeni Tennison to draft initial cut at -- due 2012-02-14 -- PENDINGREVIEW <trackbot> NM: There are other pages we are on the hook for, but I'm happy to allow them to come up when the come <Larry> I'm willing to accept wahtever Jeni does and sends off to Ian <darobin> +1 <ht> -1 <jar> I don't think "metamodel" is useful... <Larry> I'm willing to accept whatever Henry wants to do with what Jeni has written so far <jar> RDF is "useful for describing graph structures" in the same way that HTML is "useful for describing a DOM tree"—that's not what HTML is for <jar> I can't say how to improve on it right now, don't want to just criticize JT: I'll do what I can based on today's minutes, and see what HST and JAR come up with <noah> ACTION-610? <trackbot> ACTION-610 -- Jeni Tennison to draft initial cut at -- due 2012-03-13 -- OPEN <trackbot> NM: OK, that's a plan <Larry> and main thing is that Henry & Jonathan are on hook to provide acceptable updates <noah> ACTION-642? <trackbot> ACTION-642 -- Jeni Tennison to with help from Larry to propose plan to liaise with PLH to register HTML media type -- due 2012-01-17 -- PENDINGREVIEW <trackbot> <JeniT> <noah> <Larry> this action is independent of HTML5, in that the motivation was follow-your-nose for RDFa <noah>. <Larry> quote: There is currently no direct path, following definitional specifications, from an HTML document to the specs for extensions such as microdata or RDFa. The goal is to ensure there is such a path to "applicable specifications". NM: If people are happy with the email, we just need someone to do the work NM: We would close this action and open another to do the work. HT: I notice that Mark Nottingham has crafted a document suggesting how IETF can help IANA make registries more effective, and how registries should work. Relates to "happiana" work in IETF. <Larry> this is the result of the "happiana" work, which was motivated in a significant way by the MIME work NM: Not just about media types? HT: No, about registries in general, that's what we're working on, right? NM: This action was scoped to HTML media type HST: Well, the proposal is that the W3C create a registry of 'applicable extensions' HT: The e-mail proposes we create a registry. Mark's document says things about how to do registries well, so it's pertinent in that sense. HT: My 2nd point is that any registries that anyone creates for short names needs a way to give us URIs that can be used to probe the registry. <Larry> the registry of HTML applicable specifications called for in this action item doesn't assign short names JT: Don't think this one is creating short names for things. JAR: This already exists for XHTML. We're just cloning that, right? HT: It does? <jar> This registry already exists, for XHTML - it's the XHTML namespace document <jar> <jar> we're just talking about cloning this for HTML, right? LM: I think this action isn't clear. We're calling it a registry. It's really a list of known extensions. There are no options for them. Every one is allowed. We're just trying to collect them. <ht> LM: We're just trying to collect a definite list of them, and make it part of the media type registration HST: I'm done <ht> OK, interesting, JAR, thanks Who are we sending this to? NM: So is an acceptable path forward? HT: I am happy with what it says <noah> +1, I think <JeniT> ht, this is the plan for what we do <Larry> perhaps just note the discussion today <Larry> +1 to this plan forward <ht> +1 <noah> OK, we seem to be agreed on this direction forward. NM: Who will actually now work with PLH? JT: I will NM: Many thanks! <noah> . ACTION: Jeni to work with PLH to create W3C-sponsored registry of HTML extensions, and get that referenced from HTML media type registration, per <Larry> "W3C Staff" (most likely PLH) NM: Chair will help if help is needed <noah> ACTION: Jeni to work with PLH to create W3C-sponsored registry of HTML extensions, and get that referenced from HTML media type registration, per Due: 2012-05-29 [recorded in] <trackbot> Created ACTION-672 - Work with PLH to create W3C-sponsored registry of HTML extensions, and get that referenced from HTML media type registration, per Due: 2012-05-29 [on Jeni Tennison - due 2012-03-08]. <noah> ACTION-672 Due 2012-05-29 <trackbot> ACTION-672 Work with PLH to create W3C-sponsored registry of HTML extensions, and get that referenced from HTML media type registration, per Due: 2012-05-29 due date now 2012-05-29 <noah> close ACTION-642 <trackbot> ACTION-642 With help from Larry to propose plan to liaise with PLH to register HTML media type closed <Zakim> Larry, you wanted to note PhiloWeb discussion <Larry> PhiloWeb at WWW2012 <noah> What's a philoweb? <jar> philosophy of the web <noah> Ah... I knew that. <Larry> NM: Who's going to Web conference? Not me. <Larry> i will be at the web conference Unfortunately. <JeniT> no <jar> probably not, unfunded ACTION-614? <trackbot> ACTION-614 -- Jeni Tennison to report on progress relating to RDFa and Microdata -- due 2012-01-06 -- PENDINGREVIEW <trackbot> I think this should be closed, per (): OLD RESOLUTION: The draft product page at is agreed as the basis on which the TAG closes out it's work on Microdata/RDFa coordination At that time, ACTION-654 was closed, and Noah was assigned: ACTION-664 - Announce completion of TAG work on Microdata/RDFa as recorded in and to finalize the product page and associated links [on Noah Mendelsohn - due 2012-01-26]. <Larry> +1 to closing ACTION-664? <trackbot> ACTION-664 -- Noah Mendelsohn to announce completion of TAG work on Microdata/RDFa as recorded in and to finalize the product page and associated links -- due 2012-01-26 -- OPEN <trackbot> close ACTION-614 <trackbot> ACTION-614 Report on progress relating to RDFa and Microdata closed ACTION-641? <trackbot> ACTION-641 -- Noah Mendelsohn to try and find list of review issues relating to HTML5 from earlier discussions -- due 2012-03-01 -- PENDINGREVIEW <trackbot> <noah> In dec I sent this:. I sent e-mail with link to pertinent TAG status report and also detailed table of issues: <noah> Marking this action PENDING REVIEW. <Larry> or maybe F2F informal discussion? <Larry> don't know, what do other people think? <noah> Prefer to start w/ call, assuming F2F time valuable <Larry> i'll go along with whatever others want to do ACTION-648? <trackbot> ACTION-648 -- Jonathan Rees to post call for change proposals to amend the resolution to httpRange-14 per 4 January 2012 TAG Resolution -- due 2012-02-18 -- PENDINGREVIEW <trackbot> NM: What and when do we followup. JAR: Probably at F2F. Could close this, and give me a new one to prep for F2F. close ACTION-648 <trackbot> ACTION-648 Post call for change proposals to amend the resolution to httpRange-14 per 4 January 2012 TAG Resolution closed <scribe> ACTION: Jonathan to prepare for F2F discussion of httpRange-14 change proposals Due 2012-03-13 [recorded in] <trackbot> Created ACTION-673 - Prepare for F2F discussion of httpRange-14 change proposals Due 2012-03-13 [on Jonathan Rees - due 2012-03-08]. ACTION-673 Due 2012-03-13 <trackbot> ACTION-673 Prepare for F2F discussion of httpRange-14 change proposals Due 2012-03-13 due date now 2012-03-13 ACTION-662? <trackbot> ACTION-662 -- Robin Berjon to redraft proposed product page on API Minimization () -- due 2012-01-31 -- PENDINGREVIEW <trackbot> ACTION-665? <trackbot> ACTION-665 -- Noah Mendelsohn to follow up with Harry Halpin on 19 January 2012 telcon discussion of CAs -- due 2012-01-26 -- PENDINGREVIEW <trackbot> close ACTION-665 <trackbot> ACTION-665 Follow up with Harry Halpin on 19 January 2012 telcon discussion of CAs closed
http://www.w3.org/2001/tag/2012/03/01-minutes.html
CC-MAIN-2015-48
refinedweb
4,335
62.61
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. how can set permission for a button in a form of a module? I want set a permission for a button in a form of a module. this button defined in xml file of module view with this code: <button name="tender_validate_special_access" groups="internal_services.group_internal_services_special_access_validator" states="manager_approve" string="Validate Special Access" type="object" icon="gtk-jump-to" /> --------------------------------------------------------------------------- but I want say when form state is != darft and department_second_id.manager_id.user_id = user.id , this button for example show "readonly" or "invisible" format. I type a attr for button in this case: attrs="{'readonly': ['&',('state','!=','draft'),('department_second_id.manager_id.user_id','!=',user.id)]}" -------------------------------------------------------- ( department_second_idis a many2one field in this module from hr module and use in this form. user.id is current user(login user)) but does not work! I dont know what is problem? ------------------------------------------------------- if I type this code: attrs="{'readonly': [('state','!=',' draft ')]}" it is work well. Hello, I think I it wn't work, because in some cases you can't access filed with dot notation in the domain the simple workaround you can make a functional [computed] "invisible" field with type boolean then then you can make the calculations if the 'department_second_id.manager_id.user_id','!=',user.id it will return true otherwise false then change your domain to: attrs="{'readonly': ['&',('state','!=','draft'),('new_computed_fields','!=',True)]}" Hope this could helps ... thank for your help I read this page for user your solution: but in my code when I use : @api.one @api.depends() -------------------------- this error display: @api.one NameError: name 'api' is not defined -------------------------------------- I serach and understand that I have write "from openerp import api" in my .py file. but again I see this error: from openerp import api ImportError: cannot import name api --------------------------------------- my openerp version is 6.1 you think in this version I shoud use other code? thanks so much Hi, Yes you can't use api in v6.1 you can just use old API pattern in v6.1 Thanks. but how? :( ------------------------------------- now my code is this: _columns = { 'check_button': fields.boolean(compute='_get_value'), --------------------------------------- def _get_value(self): if self.department_second_id.manager_id.user_id == user.id: self.check_button = True else: self.check_button = False ------------------------------------------------------------------------------ but the field "check_button" is alwayse :False It seems that any time 'if self.department_second_id.manager_id.user_id == user.id:' does not work or not called. I don not know what is problem! so sorry! ... :( About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-can-set-permission-for-a-button-in-a-form-of-a-module-104867
CC-MAIN-2018-17
refinedweb
440
59.4
Introduction. It assumes a beginner skill level and that you are running the Raspberry Pi without a screen (referred to as a headless setup). It is broken into three main parts, with an optional fourth: - Part 1: Setting up the Raspberry Pi 2 - Part 2: Configuring the Adafruit DHT22 Sensor - Part 3: Getting Started with ThingSpeak - Part 4: Running an Email Notification Script (Optional) Part 1: Setting up the Raspberry Pi 2 The instructions provided below are for Mac OSX. Instructions for other operating systems can be found in the official documentation for the Raspberry Pi (RPi): Step 1. Download Operating System Image Download the latest Raspbian "lite" image from: After downloading the .zip file, unzip it to get the image file (.img) that will be written to the micro SD card. Step 2. Write Image to SD Card In order to locate the disk identifier of your SD card (e.g. disk4), open a terminal and run: diskutil list Using this disk identifier, unmount the SD card to prepare for copying data to it: diskutil unmountDisk /dev/disk<disk# from diskutil> Copy the data to your SD card: sudo dd bs=1m if=image.img of=/dev/rdisk<disk# from diskutil> Where image.img is the filename of the latest Raspian image, e.g.: sudo dd bs=1m if=2016-09-23-raspbian-jessie-lite.img of=/dev/rdisk<disk# from diskutil> Insert the SD card to the Raspberry Pi, and provide power using either a micro USB cable or DC adapter. Update September, 2017: A much simpler method of writing the image to an SD card is to use the program Etcher. It can be downloaded from: Once the program is opened, all you need to do is select the image, confirm the SD card drive, and hit Flash! Voila! You're all done. Step 3: Enabling SSH The most recent Raspbian releases (Dec 2016 onwards) have SSH disabled by default. To enable SSH, you must create a new file called "ssh" on the SD card. It is important to make sure your file doesn't have an extension like .txt, etc. In macOS you can easily create this file by opening up a Terminal window and typing: touch ssh Next, drag and drop this extensionless file into the root directory of your SD card and you're done! When the Raspberry Pi boots up, it will detect the SSH file and enable access. Step 4: Configure the Raspberry Pi On a headless setup, the command line of the Raspberry Pi can be accessed remotely from another computer or device on the same network using SSH (Secure Shell). In this case, the RPi is connected to the local network via ethernet, and Internet Sharing is enabled. Instructions on how to enable Internet Sharing are listed below: - Open Sharing preferences (choose Apple menu > System Preferences, then click Sharing). - Select the Internet Sharing checkbox. - Click the “Share your connection from” pop-up menu, then choose Wi-Fi as the Internet connection you want to share. - Select how you want to share your Internet connection to the Raspberry Pi in the “To computers using” list. In this case, the Internet connection will be shared over Ethernet. Once connected via ethernet, the RPi will typically bind to an IP address in the 192.168.2.* range. You can find its IP by using Nmap to scan the local network. An active IP address with an open port 22 (SSH connects via this port) is your likely target. nmap 192.168.2.* - Note: If required, install Nmap using Homebrew: /usr/bin/ruby -e "$(curl -fsSL)" brew install nmap Once the local IP address of the RPi has been found, open terminal and establish an SSH connection using the default username/password combination of "pi" and "raspberry": ssh pi@192.168.2.# - Note: If you encounter the warning: "WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!", you simply need to clear out the known_hosts file. Run the following code and remove the line of code pertaining to the IP address associated with the RPi. sudo nano /Users/<username>/.ssh/known_hosts Step 5: Update the Raspberry Pi Upon first login to SSH, it is suggested to update/upgrade the Raspberry Pi using the following commands: sudo apt-get update sudo apt-get dist-upgrade df -h #to check space sudo apt-get clean #to removed archived .deb files If you would like to change default password for pi user, you can access the Raspberry Pi Software Configuration Tool by running the command below and selecting option 2: sudo raspi-config Step 6: Setting up Wifi Official guide: If you intend to have the RPi connect to the Internet using a wireless USB dongle, you must enter the details of your wifi connection in the wpa_supplicant.conf file. To do so, run: sudo nano /etc/wpa_supplicant/wpa_supplicant.conf Then enter the details in the following format: network={ ssid="ESSID" psk="Your_wifi_password" } If you' like your Raspberry Pi to roam and connect to open networks, append the following to your wpa_supplicant.conf: network={ key_mgmt=NONE priority=-999 } Finally, reboot your Raspberry Pi and discover its new IP address using Nmap, or by logging into your router and searching for the IP address associated with the "raspberrypi" hostname. Over a Wi-Fi connection, the RPI will usually bind to an address within the 192.168.1.* range. sudo reboot ssh pi@192.168.1.* Part 2: Configuring the Adafruit DHT22 Sensor The DHT22 is a basic, low-cost digital temperature and humidity sensor, which uses a capacitive humidity sensor and a thermistor to measure the surrounding air and output a digital signal on the data pin. Step 1: Wiring Diagram As shown in the diagram below, the DHT22 requires Pin 1 to be connected to a 3.3V source, Pin 2 to the desired General-purpose input/output (GPIO) pin on the RPi, and Pin 4 to ground (GND). A 10kΩ resistor is placed between Pin 1 and Pin 2. Pin 3 in not used. By examining the GPIO header in the figure below, we are able to determine that the corresponding connections on the Raspberry Pi are as follows: - Pin 1: 3.3 V - Pin 6: GND - Pin 16: GPIO 23 (other GPIO pins can be selected) With the correct pins identified, the circuit can be physically built and may end up looking similar to the diagram below: Step 2: Download the Adafruit DHT Library With the wiring complete, the next step is to download Adafruit’s DHT library to the RPi, which is required to read the temperature values from the sensor. This also requires that we first download some Python and git packages: sudo apt-get install python-dev sudo apt-get install python-pip sudo apt-get install git git clone cd Adafruit_Python_DHT sudo python setup.py install Once the DHT library is installed, the next step is to write the script to gather the data from the sensors and upload it to the Internet. To accomplish this, we will utilize the ThingSpeak Internet of Things platform. Part 3: Getting Started with ThingSpeak Official guide: ThingSpeak is an Internet of Things (IoT) platform enabling the collection, storage, analysis, and visualization of data gathered from sensors such as the Arduino and Raspberry Pi. ThingSpeak stores data in Channels, each of which can have up to 8 data fields, as well as location and status fields. Data can be sent to ThingSpeak at a rate of at every 15 seconds or longer. ThingSpeak Configuration Step 1. Sign up for new User Account Step 2. Create a new Channel - Select "Channels", "My Channels", and then "New Channel". Step 3: Enter Channel Information - Name: Raspberry Pi + DHT22 Temperature & Humidity Sensor - Description: DHT22 temperature & humidity sensor driven by a Raspberry Pi 2 running a Python script. - Field 1: Humidity (%) - Field 2: Temperature (°C) Step 4: Record Write API Key - Once the Channel is created, click on "API Keys" and note down the "Write API Key". We will use this value later in our script. Step 5: Script Creation Create a folder in the /home/pi directory on the Raspberry Pi, then an empty Python script file by running: mkdir ThingSpeak cd ThingSpeak sudo nano dht22.py Next, copy the code listed below (or from the attached dht22.py at the end of this tutorial). Enter your API code to the "myAPI" variable. Press Ctrl+X to exit the editor, and select "Y" to save the file when prompted. """ dht22.py Temperature/Humidity monitor using Raspberry Pi and DHT22. Data is displayed at thingspeak.com Original author: Mahesh Venkitachalam at electronut.in Modified by Adam Garbo on December 1, 2016 """ import sys import RPi.GPIO as GPIO from time import sleep import Adafruit_DHT import urllib2 myAPI = "<your API code here>" def getSensorData(): RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 23) return (str(RH), str(T)) def main(): print 'starting...' baseURL = '' % myAPI while True: try: RH, T = getSensorData() f = urllib2.urlopen(baseURL + "&field1=%s&field2=%s" % (RH, T)) print f.read() f.close() sleep(300) #uploads DHT22 sensor values every 5 minutes except: print 'exiting.' break # call main if __name__ == '__main__': main() Next, to test whether the script runs properly, you can use the following code: sudo python dht22.py If successful, you should see two lines as shown below: pi@raspberrypi:~/ThingSpeak $ python dht22.py starting... 5 In this case, the number "5" represents the entry made in the ThingSpeak channel. This will increment each time the script uploads data. Step 6: Running the Script at Startup If you plan on having your Raspberry Pi run automatically, a good idea is to have it start when the RPi is powered on. One method of doing so is to add a cron job. The command below will start the script and make the status outputs be directed to “null” (i.e. ignored), which ensures it runs in the background. It will also check every 5 minutes to see if the script is running, and restart it if necessary. crontab -e */5 * * * * pgrep -f dht22.py || nohup python /home/pi/ThingSpeak/dht22.py > test.out Another method of ensuring that the script is always running is to take the command from above, enter it into its own script add a cron job that will periodically check and restart the script if necessary. This can be accomplished by adding the following cronjob task and using the check_script.sh file attached to this project: crontab -e */5 * * * * sh /home/pi/ThingSpeak/script_check.sh &>/dev/null More discussion on restarting a script can be found here: - Note: If you are using Sublime Text to edit your code, make sure to not re-indent using tabs, as it may break Python's structure and render the script inoperable. Step 7: Verify ThingSpeak Channel Data Uploads If your script is working as intended, you should be able to see data uploading in real time. You can increase the frequency at which the script uploads data to verify it is working properly, rather than waiting the default 5 minutes. ThingSpeak has a number of customizable features for the way the data is displayed, which you can read more about here: Part 4: Running an Email Notification Script (Optional) A problematic aspect of running a headless Raspberry Pi setup is the lack of information regarding its current IP address, which may change if an Internet or power outages occurs. A helpful solution is to have the Raspberry Pi send out a notification email each time it reboots, or when the wireless adapter is assigned a new IP address. To add this functionality to your RPi, we will utilize a mail utility program and a Gmail email address to notify the user of any changes to the IP address. Step 1: Required Packages Installation The first step is to update your package list and install the mailutils and ssmtp packages: sudo apt-get update sudo apt-get install mailutils ssmtp Step 2: Edit Configuration Files Next, to add the information specific to the Gmail account in the sstmp.conf file, run: sudo nano /etc/ssmtp/ssmtp.conf We are interested in changing/adding the information for the following four lines of code: mailhub=smtp.gmail.com:587 AuthUser=<emailaddress>@gmail.com AuthPass=<password> UseSTARTTLS=YES Warning: Your password is not protected when entered into the ssmtp.conf file. It is highly suggested to create an email address specifically for this purpose, where security vulnerability is not a concern. Note: It is also necessary to allow less secure apps to access your Gmail account. This can be accomplished using the following guide: Save your changes when exiting, then open the revaliases file by running: sudo nano /etc/ssmtp/revaliases Add the last line of code shown below with your email address. # sSMTP aliases # # Format: local_account:outgoing_address:mailhub # # Example: root:your_login@your.domain:mailhub.your.domain[:port] # where [:port] is an optional port number that defaults to 25. root:<email address>@gmail.com:smtp.gmail.com:587 Step 3: IP Address Checking Scripts We will create two different IP checking scripts. One will be intended to run every 15 minutes to verify the IP address of the RPi hasn't changes, and one will be run only when the RPi reboots. Please note: Scripts are currently only meant to monitor changes to wlan0. First, create a folder in the /home/pi directory to house your scripts: mkdir ipcheck Enter the folder, create the two script files and make them both executable: sudo nano ipcheck.sh sudo nano ipcheck2.sh sudo chmod +x ipcheck.sh sudo chmod +x ipcheck2.sh Finally, copy the code to each script from the section below (or the scripts attached to this tutorial), while remembering to specify the email address you would like the notifications sent to. Code for: ipcheck.sh #! /bin/sh sleep 20 /home/pi/ipcheck/ip.txt; echo "New IP Address was assigned to your Raspberry Pi: $ip2" | mail -s "$SUBJ" $EMAIL; exit; fi Code for ipcheck2.sh #! /bin/sh /home/pi/ipcheck/ip.txt; echo "New IP Address was assigned to your Raspberry Pi: $ip2" | mail -s "$SUBJ" $EMAIL; exit fi Step 4: Add Scripts to Cronjob The following cronjob entries will ensure the script will email a change in IP address upon reboot, and at 15 minute intervals Run: crontab -e Add: @reboot /home/pi/ipcheck.sh 0,15,30,45 * * * * sh /home/pi/ipcheck2.sh &>/dev/null Conclusion If everything has gone according to plan, you should be now have your Raspberry Pi uploading data to the ThingSpeak website! This project was my first foray into the world of IoT devices, which, once everything eventually started working, I found to be quite rewarding. There were many bumps along the way, but it's only made me more keen to create bigger and more complicated IoT devices. If you've made it all the way through this project, I hope that this documentation has proven useful in some shape, way or form. Cheers Credits This project drew from a large number tutorials and forum posts, which I'd like to acknowledge and include for reference below: -
https://www.hackster.io/adamgarbo/raspberry-pi-2-iot-thingspeak-dht22-sensor-b208f4
CC-MAIN-2019-13
refinedweb
2,530
60.35
public class BSTIterator { Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<TreeNode>(); addLeftNodes(root); } void addLeftNodes(TreeNode node) { while (node != null) { stack.push(node); node = node.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode next = stack.pop(); // Add its right node's left nodes onto stack addLeftNodes(next.right); return next.val; } } Yes. Your next() runs in average O(1) time. The *next()*it is called n times, while in all the runtime of next(), each of the n nodes enters the stack at most 1 time (some nodes enter during construction) and leaves the stack exactly 1 time. And the space cost is O(h) time. The stack size grows only in addLeftNodes(). Each time addLeftNodes() finishes, the node at top of the stack is a leaf. At the same time, right below each node is its parent or the parent of its parent. Thus, after addLeftNodes(), the node sequence in stack forms a (sometimes incompleted) path from root to a leaf. Such a path always has a length less than the height of the tree.
https://discuss.leetcode.com/topic/12034/can-anyone-verify-if-this-is-o-1-time-o-h-space-solution
CC-MAIN-2017-51
refinedweb
195
75.5
There are some open questions remaining. db_timeout_t lease_timeout;NOTE: By sending the lease refresh during DB operations, we are forcing/assuming that the operation's process has a replication transport function set. That is obviously the case for write operations, but would it be a burden for read processes (on a master)? I think mostly not, but if we need leases for DB->stat then we need to document it as it is certainly possible for an application to have a separate or dedicated stat application or attempt to use db_stat (which will not work if leases must be checked). db_timespec lease_duration; dbenv->rep_set_lease(DB_ENV *dbenv, u_int32_t clock_scale_factor, u_int32_t flags)The clock_scale_factor parameter is interpreted as a percentage, greater than 100 (to transmit a floating point number as an integer to the API) that represents the maximum shkew between any two sites' clocks. That is, a clock_scale_factor of 150 suggests that the greatest discrepancy between clocks is that one runs 50% faster than the others. Both the master and client sides compensate for possible clock skew. The master uses the value to compensate in case the replica has a slow clock and replicas compensate in case they have a fast clock. This scaling factor will need to be divided by 100 on all sites to truly represent the percentage for adjustments made to time values. #define REP_F_START_CALLED <some bit value>In __rep_start, at the end: if (ret == 0 ) {In __rep_env_refresh, if we are the last reference closing the env (we already check for that): REP_SYSTEM_LOCK F_SET(rep, REP_F_START_CALLED) REP_SYSTEM_UNLOCK } F_CLR(rep, REP_F_START_CALLED);[Please review the logic here carefully.] In order to avoid run-time floating point operations on db_timespec structures, when a site is declared as a client or master in rep_start we will pre-compute the lease duration based on the integer-based clock skew and the integer-based lease timeout. A master should set a replica's lease expiration to the start time of the sent message + (lease_timeout / clock_scale_factor) in case the replica has a slow clock. Replicas extend their leases to received message time + (lease_timeout * clock_scale_factor) in case this replica has a fast clock. Therefore, the computation will be as follows if the site is becoming a master: db_timeout_t tmp;Similarly, on a client the computation is: tmp = (db_timeout_t)((double)rep->lease_timeout / ((double)rep->clock_skew / (double)100)); rep->lease_duration = DB_TIMEOUT_TO_TIMESPEC(&tmp); tmp = (db_timeout_t)((double)rep->lease_timeout * ((double)rep->clock_skew / (double)100));When a site changes state, its lease duration will change based on whether it is becoming a master or client and it will be recomputed from the original values. Note that these computations, coupled with the fact that the lease on the master is computed based on the master's time that it sent the message means that leases on the master are more conservatively computed than on the clients. if (IS_REP_CLIENT(dbenv)) {On the master, the new code to abide by leases is more complex. After the call to perform the operation we will check the lease. In that checking code, the master will see if it has a valid lease. If so, then all is well. If not, it will try to refresh the leases. If that refresh attempt results in leases, all is well. If the refresh attempt does not get leases, then the master cannot respond to the read as an authority and we return an error. The new error is called DB_REP_LEASE_EXPIRED. The location of the master lease check is down after the internal call to read the data is successful: [get to rep structure] if (FLD_ISSET(rep->config, REP_C_LEASE) && !LF_ISSET(DB_IGNORE_LEASE)) { db_err("Read operations must ignore leases or go to master"); ret = EINVAL; goto err; } } if (IS_REP_MASTER(dbenv) && !LF_ISSET(DB_IGNORE_LEASE)) {See below for the details of __rep_lease_check. [get to rep structure] if (FLD_ISSET(rep->config, REP_C_LEASE) && (ret = __rep_lease_check(dbenv)) != 0) { /* * We don't hold the lease. */ goto err; } } struct __rep_lease_grant {In the REP_LEASE_GRANT message, the client is actually giving the master several pieces of information. We only need the echoed msg_time in this structure because everything else is already sent. The client is really sending the master: db_timespec msg_time; #ifdef DIAGNOSTIC db_timespec expire_time; #endif } REP_GRANT_INFO; db_timespec grant_expire;This timestamp already takes into account the clock skew. All new fields must be initialized when the region is created. Whenever we grant our master lease and want to send the REP_LEASE_GRANT message, this value will be updated. It will be used in the following way: db_timespec mytime;This updating of the lease grant will occur in the PERM code path when we have successfully applied the permanent record. DB_LSN perm_lsn; DBT lease_dbt; REP_GRANT_INFO gi; timespecclear(&mytime); timespecclear(&newgrant); memset(&lease_dbt, 0, sizeof(lease_dbt)); memset(&gi, 0, sizeof(gi)); __os_gettime(dbenv, &mytime); timespecadd(&mytime, &rep->lease_duration); MUTEX_LOCK(rep->clientdb_mutex); perm_lsn = lp->max_perm_lsn; MUTEX_UNLOCK(rep->clientdb_mutex); REP_SYSTEM_LOCK(dbenv); if (timespeccmp(mytime, rep->grant_expire, >)) rep->grant_expire = mytime; gi.msg_time = msg->msg_time; #ifdef DIAGNOSTIC gi.expire_time = rep->grant_expire; #endif lease_dbt.data = &gi; lease_dbt.size = sizeof(gi); REP_SYSTEM_UNLOCK(dbenv); __rep_send_message(dbenv, eid, REP_LEASE_GRANT, &perm_lsn, &lease_dbt, 0, 0); struct { int eid; /* EID of client site. */ db_timespec start_time; /* Unique time ID client echoes back on grants. */ db_timespec end_time; /* Master's lease expiration time. */ DB_LSN lease_lsn; /* Durable LSN this lease applies to. */ u_int32_t flags; /* Unused for now?? */ } REP_LEASE_ENTRY; /* * Use lp->max_perm_lsn on the master (currently not used on the master) * to keep track of the last PERM record written through the logging system. * need to initialize lp->max_perm_lsn in rep_start on role_chg. */ call __rep_send_message on the last PERM record the master wrote, with DB_REP_PERMANENT if failure expire leases return lease expired error to caller else /* success */ recheck lease table /* * We need to recheck the lease table because the client * lease grant messages may not be processed yet, or got * lost, or racing with the application's ACK messages or * whatever. */ if we have a majority of valid leases return success else return lease expired error to caller REP_SYSTEM_LOCK msg_timestamp = cntrl->timestamp; client_lease = __rep_lease_entry(dbenv, client eid) if (client_lease == NULL) initial lease for this site, DB_ASSERT there is space in the table add this to the table if there is space } else compare msg_timestamp with client_lease->start_time if (msg_timestamp is more recent && msg_lsn >= lease LSN) update entry in table REP_SYSTEM_UNLOCK REP_SYSTEM_LOCKIs there a potential race or problem with prematurely expiring leases? Consider an application that enforces an ALL acknowledgement policy for PERM records in its transport callback. There are four clients and three send the PERM ack to the application. The callback returns an error to the master DB code. The DB code will now prematurely expire its leases. However, at approximately the same time the three clients are also sending their REP_LEASE_GRANT messages to the master. There is a race between the master processing those messages and the thread handling the callback failure expiring the table. This is only an issue if the messages arrive after the table has been expired. for each entry in the lease table entry->end_time = entry->start_time; REP_SYSTEM_UNLOCK #define MAX_REFRESH_TRIES 3If the master has enough valid leases it returns success. If it does not have enough, it attempts to refresh them. This attempt may fail if sending the PERM record does not receive sufficient acks. If we do receive sufficient acknowledgements we may still find that scheduling of message threads means the master hasn't yet processed the incoming REP_LEASE_GRANT messages yet. We will retry a couple times (possibly parameterized) if the master discovers that situation. DB_LSN lease_lsn; REP_LEASE_ENTRY *entry; u_int32_t min_leases, valid_leases; db_timespec cur_time; int ret, tries; tries = 0; retry: ret = 0; LOG_SYSTEM_LOCK lease_lsn = lp->lsn LOG_SYSTEM_UNLOCK REP_SYSTEM_LOCK min_leases = rep->nsites / 2; __os_gettime(dbenv, &cur_time); for (entry = head of table, valid_leases = 0; entry != NULL && valid_leases < min_leases; entry++) if (timespec_cmp(&entry->end_time, &cur_time) >= 0 && log_compare(&entry->lsn, lease_lsn) == 0) valid_leases++; REP_SYSTEM_UNLOCK if (valid_leases < min_leases) { ret =__rep_lease_refresh(dbenv, ...); /* * If we are successful, we need to recheck the leases because * the lease grant messages may have raced with the PERM * acknowledgement. Give those messages a chance to arrive. */ if (ret == 0) { if (tries <= MAX_REFRESH_TRIES) { /* * If we were successful sending, but not successful in racing the * message thread, yield the processor so that message * threads may have a chance to run. */ if (tries > 0) /* __os_sleep instead?? */ __os_yield() tries++; goto retry; } else ret = DB_RET_LEASE_EXPIRED; } } return (ret); if (leases_configured && (my_grant_still_valid || lease_never_granted) {On the master side, the code handling the REP_MASTER_REQ will do: if (lease_never_granted) wait_time = lease_timeout else wait_time = grant_expiration - current_time F_SET(REP_F_EPHASE0); __rep_send_message(..., REP_MASTER_REQ, ... REPCTL_LEASE); ret = __rep_wait(..., REP_F_EPHASE0); if (we found a master) return } /* if we don't return, fall out and proceed with election */ if (I am master) {Other minor implementation details are that __rep_elect_done must also clear the REP_F_EPHASE0 flag. We also, obviously, need to define REP_F_EPHASE0 in the list of replication flags. Note that the client's call to __rep_wait will return upon receiving the REP_NEWMASTER message. The client will independently refresh its lease when it receives the log record from the master's call to refresh the lease. ... __rep_send_message(REP_NEWMASTER...) if (F_ISSET(rp, REPCTL_LEASE)) __rep_lease_refresh(...) }
https://opensource.apple.com/source/BerkeleyDB/BerkeleyDB-18/db/rep/mlease.html
CC-MAIN-2017-30
refinedweb
1,499
51.68
#include <wx/dcsvg.h> Abstract base class for handling bitmaps inside a wxSVGFileDC. To use it you need to derive a new class from it and override ProcessBitmap() to generate a properly a formed SVG image element (see). Two example bitmap handlers are provided in wx/dcsvg.h. The first (default) handler will create PNG files in the same folder as the SVG file and uses links to them in the SVG. The second handler (wxSVGBitmapEmbedHandler) will embed the PNG image in the SVG file using base 64 encoding. The handler can be changed by calling wxSVGFileDC::SetBitmapHandler(). Writes the bitmap representation as SVG to the given stream. The XML generated by this function will be inserted into the SVG file inline with the XML generated by the main wxSVGFileDC class so it is important that the XML is properly formed. Implemented in wxSVGBitmapFileHandler, and wxSVGBitmapEmbedHandler.
https://docs.wxwidgets.org/3.1.0/classwx_s_v_g_bitmap_handler.html
CC-MAIN-2019-09
refinedweb
146
55.54
Introduction to JOGL OpenGL is a cross-platform, language-independent, industrial standard API for producing 3D (and 2D) computer graphics. Graphics cards that claim OpenGL-compliance make use of the hardware acceleration when possible to speed up the graphics rendering process. OpenGL competes with Direct3D on Microsoft Windows platform. The OpenGL mother site is at. The JOGL (Java Bindings for the OpenGL) allows Java applications to access the OpenGL API for graphics programming. In other words, it is simply a wrapper library for Java application to use OpenGL API. JOGL is open-source and currently maintained by "JogAmp" (Java on Graphics, Audio, Media and Processing) @. JogAMP provides JOGL (3D graphics), JOAL (Java Bindings for OpenAL for 3D Audio) and JOCL (Java Bindings for OpenCL - a Common Language for Graphics Processors). Alternatives to JOGL include open-source LWJGL (Light-Weight Java Game Library) @. This tutorial assumes that you have sufficient knowledge on OpenGL, but new to JOGL. To learn OpenGL, find a good OpenGL book (e.g., the Red book "OpenGL Programming Guide" or Blue Book "OpenGL Superbible"). Nehe production maintains an excellent OpenGL Tutorials (@). You may also read my OpenGL tutorials. JOGL 2 supports OpenGL 1.3 to 4.0 and OpenGL ES 1.x and 2.x. JOGL integrates with the AWT, Swing and SWT. It also provides its own native windowing toolkit called NEWT. This guide is meant for JOGL 2.0 (tested on rc8), which is not compatible with the older (and obsoleted) JOGL 1.x. For JOGL 1.x, read "A Tutorial on JOGL 1.1". Setting Up JOGL 2.0_rc8 Reference: "Downloading and installing JOGL" @. Step 0: Install JDK Install JDK, an IDE such as Eclipse/NetBeans or a programming text editor. You need a working Java programming environment to write JOGL programs. Step 1: Download JOGL Download the latest "stable" release from JogAMP @ (or from JogAMP @ ⇒ Builds/Downloads ⇒ Current ⇒ zip). Select " jogamp-all-platforms.7z", which contains the JOGL and gluegen JAR-files, Java Native Library (JNI) for all the platforms (e.g., Win32, Win64, Linux, Mac OS), and source-files. You are also recommended to download the " javadocs" ( jogl-javadoc.7z and gluegen-javadoc.7z), " demos" ( jogl-demos.7z) and sources. Step 2: Setup JOGL - Unzip " jogamp-all-platforms.7z" (you can unzip " .7z" file using WinRAR, WinZip, or). - The jogl's and gluegen's jar-files are kept in the " jar" sub-directory. - The Java Native JNI Libraries (" .dll" for Windows, " .so" for Linux, or " .jnilib" for MacOS) are kept in the " lib" sub-directories. - Create a JOGL binary directory, says " jogl-2.1" - I shall denote the binary directory as $JOGL_HOME. Create sub-directories " jar", " lib", " src" (optional), " javadoc" (optional) under the $JOGL_HOME. Copy the necessary jar-file, native libraries of your operating platform, and source-files into the appropriate sub-directories. Read "". For example, for Win64, copy " jar\gluegen-rt.jar", " jar\jogl.all.jar", " jar\gluegen-rt-natives-windows-amd64.jar" and " jar\jogl-all-natives-windows-amd64.jar" into " jar"; " lib\windows-amd64\gluegen-rt.dll", " lib\windows-amd64\jogl_desktop.dll", " lib\windows-amd64\nativewindow_awt.dll", " lib\windows-amd64\nativewindow_win32.dll", " lib\windows-amd64\newt.dll" into " lib"; and " gluegen-java-src.zip", " jogl-java-src.zip" into " src". Unzip the javadocsdownloaded into " javadoc". Read the " jogl.README.txt". This step is optional, but it is good to organize the JOGL JAR-files and Java Native Libraries for your operating platform in a single directory. Step 3a: Customize for Eclipse 4.3 - Create a User Library: We shall first create a Eclipse's User Library called " jogl-2.1", which specifies the jar-files, native libraries, javadoc, and source files for the JOGL API. All the JOGL projects can then include this user library in its build path. - From "Window" menu ⇒ Preferences ⇒ Java ⇒ Build Path ⇒ User Libraries ⇒ New ⇒ In "User library name", enter " jogl-2.1". - In "User Library" dialog ⇒ Select " jogl-2.1" ⇒ "Add External JAR..." ⇒ Navigate to " $JOGL_HOME\jar", and select " gluegen-rt.jar" and " jogl.all.jar". - Expand the " jogl.all.jar" node, select "Native library location: (none)" ⇒ "Edit..." ⇒ External Folder... ⇒ select " $JOGL_HOME\lib" to provide the path for the native library code (such as " jogl_desktop.dll" for Windows). Repeat for " gluegen-rt.jar" (for " gluegen-rt.dll"). - (Optional But Recommended) Expand the " jogl.all.jar" node again ⇒ Select "Javadoc location "⇒ "Edit..." - Specify the javadoc's path (either file: or http:) in "Javadoc URL" if you use an unzip version of the javadoc. - Specify the javadoc's archive file (either zip or jar) in "Javadoc in archive" if you use a zip file. index.html" file. This is needed for Eclipse to display javadoc information about classes and methods. - (Optional But Recommended) You may provide the source files by editing "Source attachment" ⇒ "Edit..." ⇒ "External File..." ⇒ Select the source file in zip form. Source is needed only if you are interested to debug into the JOGL source codes. - Include the User Library: For EACH JAVA PROJECT created that uses JOGL, right-click on the project ⇒ "Build Path" ⇒ "Add Libraries" ⇒ Select "User Library" ⇒ Check " jogl-2.1". Read "Java Native Library (JNI) Error" if you encounter error " SEVERE: java.lang.UnsatisfiedLinkError: no xxx in java.library.path". Step 3b: Customize for NetBeans 7.0 (To Check!) There was a so-called "NetBeans OpenGL Pack", but it seems to be out-dated and does not support JOGL 2 (?!). We shall create our own JOGL Library as follows: - Create a JOGL Library: - From "Tool" ⇒ "Library" ⇒ Click "New Libraries..." ⇒ Enter " jogl2.0". - Click "Add JAR/Folder..." ⇒ Select " jogl.all.jar" and " gluegen-rt.jar". - Under the "JavaDoc" tab ⇒ Select the JOGL's javadoc. You could use the zip version for better performance. - Under the "Source" tab ⇒ Select the JOGL's source. You could use the zip version for better performance. - Include the JOGL Library: - For EACH of the JOGL project, include the JOGL library. Right-click on the project ⇒ "Properties" ⇒ "Library" ⇒ Under "Compile" tab ⇒ "Add Libraries..." ⇒ Choose the library " jogl2.0" created earlier. - You also need to include the native library path for each of the project. Right-click the project ⇒ "Set Configuration" ⇒ "Customize..." ⇒ "Run" ⇒ In "VM options", enter " -Djava.library.path=xxx", where xxx is directory path (e.g., d:\bin\jogl2.0\lib), that contains the Java Native JNI Libraries (" *.dll" for Windows, " *.so" for Linux or " *.jnilib" for MacOS). Read "Java Native Library (JNI) Error" if you encounter error " SEVERE: java.lang.UnsatisfiedLinkError: no xxx in java.library.path". Step 3c: Customize for JDK/Editor You need to modify two environment variables - CLASSPATH and PATH. Read "Environment Variables For Java Applications" on how to set these environment variables. Modify the CLASSPATH environment variable to include the full-path filenames of " jogl.all.jar" and " gluegen-rt.jar", for example, shell> set classpath=.;$JOGL_HOME\lib\jogl.all.jar;$JOGL_HOME\lib\gluegen-rt.jar where $JOGL_HOME denotes the JOGL installed directory. Take note that you should include the current working directory '.'. Modified the PATH environment variable to include the full path to the JOGL's " lib" directory for accessing the native libraries (e.g., " jogl_xxx.dll", " gluegen-rt.dll"), for example, shell> set path=$JOGL_HOME\lib;...... Alternatively, you could include the directory path of the native libraries in Java system's property " java.library.path", via the VM command-line option -Djava.library.path=pathname, for example, shell> java -Djava.library.path=d:\bin\jogl2.0\lib myjoglapp Read "Java Native Library (JNI) Error" if you encounter error " SEVERE: java.lang.UnsatisfiedLinkError: no xxx in java.library.path". Getting Started with JOGL 2.1 OpenGL Drawable: GLCanvas and GLJPanel An OpenGL drawable is a surface (or canvas) for graphics rendering. JOGL provides two drawables in package javax.media.opengl.awt: GLCanvas and GLJPanel. GLCanvas: A heavyweight AWT component which is a subclass of java.awt.Canvas. You can create a GLCanvasvia the default constructor GLCanvas(), which construct a new GLCanvascomponent with a default set of OpenGL capabilities, using the default OpenGL capabilities selection mechanism, on the default screen device. For example, GLCanvas canvas = new GLCanvas(); JFrame frame = new JFrame(); // or AWT's Frame frame.getContentPane().add(canvas); // add Component canvas.addGLEventListener(.....); GLJPanel: A lightweight Swing component which is a subclass of javax.swing.JPanel. Again, You can create a GLJPanelvia the default constructor GLJPanel(), which construct a new GLJPanelcomponent with a default set of OpenGL capabilities, using the default OpenGL capabilities selection mechanism. For example, GLJPanel canvas = new GLJPanel(); JFrame frame = new JFrame(); frame.getContentPane().add(canvas); // or frame.setContentPane(canvas); canvas.addGLEventListener(.....); The GLCanvas is a heavyweight AWT component which supports hardware acceleration. It is designed as the primary widget for JOGL applications. On the other hand, GLJPanel is a swing-compatible lightweight component, which supports hardware acceleration but is not as fast as GLCanvas. GLJPanel is intended to provide 100% swing integration when the heavyweight GLCanvas cannot be used. Both the GLCanvas and GLJPanel implement a common interface GLAutoDrawable (which in turn implements the interface GLDrawable). These interfaces define the common behaviors expected on GLCanvas and GLJPanel, so that applications can switch between them with minimal code changes. Beside supporting AWT, Swing and SWT, JOGL 2 also provide its own Native Window Toolkit called NEWT via drawable GLWindow (in package com.jogamp.newt.opengl). I shall discuss NEWT later. GLEventListener and GLAutoDrawable The interface GLEventListener (in package javax.media.opengl) declares the following 4 OpenGL event handlers: init(GLAutoDrawable drawable): called by the drawableimmediately after the OpenGL context is initialized. It can be used to perform one-time initialization tasks such as setting up of lights and display lists. init()runs only once. dispose(GLAutoDrawable drawable): called by the drawablebefore the OpenGL context is destroyed. It can be used to release all OpenGL resources, such as memory buffers. display(GLAutoDrawable drawable): called by the drawableto render OpenGL graphics. It is the most important method. reshape(GLAutoDrawable drawable, int x, int y, int width, int height): called by the drawablewhen it is first set to visible, and during the first repaint after the it has been resized. It is used to set the view port and projection mode, and view volume. All these methods are call-back methods. When an OpenGL event is posted on the event-queue, the graphics sub-system calls back the corresponding handler. An OpenGL renderer shall implement the GLEventListener interface. Recall that GLCanvas and GLJPanel are GLAutoDrawable. The interface GLAutoDrawable defines these abstract methods to add or remove a GLEventListener: public void addGLEventListener(GLEventListener listener) public void removeGLEventListener(GLEventListener listener) For example, GLCanvas canvas = new GLCanvas(); canvas.addGLEventListener(renderer); // add a GLEventListener called renderer // renderer shall provides these handlers // init(GLAutoDrawable drawable) // destroy(GLAutoDrawable drawable) // display(GLAutoDrawable drawable) // reshape(GLAutoDrawable drawable, int x, int y, int width, int height) Whenever an OpenGL event is fired (e.g., init, display), GLCanvas or GLJPanel invokes the corresponding handler of all its registered GLEventListener(s) (such as init() and display()) with itself as the argument for GLAutoDrawable, as illustrated. Animator To perform animation, we need an animator to drive the drawable's display() method in a loop to refresh the display regularly. JOGL provides two animator classes: Animator and FPSAnimator (in package com.jogamp.opengl.util). The commonly-used FPSAnimator can drive the display() of the given drawable at the specified number of frame per seconds (fps). For example, // Construct a drawable GLCanvas canvas = new GLCanvas(); // or GLJPanle // Construct an FPS animator, which drives drawable's display() at the specified frames per second FPSAnimator animator = new FPSAnimator(canvas, 60); animator.start(); // start the animator animator.pause(); // pause the animator if started animator.resume(); // resume the animator if paused animator.stop(); // stop the animator animator.isStarted(); // started? animator.isAnimating(); // started and not pause? animator.isPause(); // started and pause? The commonly-used constructors are: FPSAnimator(GLAutoDrawable drawable, int fps) // Creates an FPSAnimator with a given target frames-per-second value // and an initial drawable to animate. FPSAnimator(GLAutoDrawable drawable, int fps, boolean scheduleAtFixedRate) // Creates an FPSAnimator with a given target frames-per-second value, // an initial drawable to animate, // and a flag indicating whether to use fixed-rate scheduling. Animator(GLAutoDrawable drawable) // Creates a new Animator for a particular drawable. OpenGL Graphics Context In order to perform rendering, an so-called OpenGL rendering context is required. You can retrieve the graphics context from a drawable as follow: javax.media.opengl.GL gl = drawable.getGL(); javax.media.opengl.GL2 gl = drawable.getGL().getGL2(); // up to OpenGL 3.0 javax.media.opengl.GL3 gl = drawable.getGL().getGL3(); // up to OpenGL 3.1 javax.media.opengl.GL4 gl = drawable.getGL().getGL4(); // up to OpenGL 4 ...... // Others: GL2GL3, GL2bc, GL4bc, GLES1, GLES2, GL2ES1, GL2ES2 [TODO] To Revise. JOGL 2.0/2.1 Program Templates GLCanvas Try running the above program, which will show a white triangle on a black screen. In this template: - I follow the design of "Component-based Architecture for Rich Internet Applications (RIA)", where the GUI " Component" ( GLCanvasor GLJPanel) and " Container" ( JFrame, Frame, JApplet, Applet) are clearly separated. The " Component" can be easily plugged into any of the " Container". - The main class extends GLCanvas( Component) to provide the OpenGL graphics rendering canvas. It also implements GLEventListenerand provides handlers for init(), display(), dispose()and reshape(). - The main()method: - Allocates a GLCanvascomponent. - Allocates an Animatorto drive the display()method of the GLCanvasin a loop to refresh the display. - Allocates a top-level container (Swing's JFrameor AWT's Frame), and adds the GLCanvascomponent into the container.. Using AWT's Frame as Top-Level Container The above template uses Swing's JFrame as the top-level container. To use AWT's Frame as the top-level window, modify the main() method as follows: /** The entry main() method to setup the top-level container and animator */ public static void main(String[] args) { GLCanvas canvas = new GLCanvas(); ...... final Frame frame = new Frame(); // instead of Swing's JFrame frame.add(canvas); // instead of Swing's frame.setContentPane() ....... } [TODO] Check whether GLCanvas is better to use with AWT's Frame or Swing's JFrame if there is no other light-weight components. Separating the Component and Container Classes Alternatively, you could separate the renderer Component and the top-level Container into two classes: In this approach, all the graphics rendering codes are kept in the renderer ( Component) class. The main ( Container) class can be left untouched. GLJPanel To use the light-weight GLJPanel instead of the heavy-weight GLCanvas, simply change all reference of GLCanvas to GLJPanel. public class JOGL2Setup_GLJPanel extends GLJPanel implements GLEventListener { ...... /** The entry main() method to setup the top-level container and animator */ public static void main(String[] args) { // Run the GUI codes in the event-dispatching thread for thread safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Create the OpenGL rendering canvas GLJPanel canvas = new JOGL2Setup_GLJPanel(); ...... } } } ...... } GLJPanel canvas = new GLJPanel(); // instead of GLCanvas Running as an Applet As we followed the Component-based Architecture in our class design, we can plug the GLCanvas Component into other top-level Container, such as JApplet or Applet easily. To run the program as an applet, you can simply add an applet launching class (as follow) to launch the main renderer class. Recall that an applet extends javax.swing.JApplet (or java.awt.Frame) and is managed via methods init() (instead of main() of an application), start(), stop() and destroy(). The main() method in the renderer class is ignored by applet. Running in Full-Screen Mode Games are often run in full-screen mode without decoration (title, status, scroll bars). The JOGL 2.0 program template for full screen mode operation is as follows: To operate in full-screen mode, set the frame to: final JFrame frame = new JFrame(); frame.setUndecorated(true); // no decoration such as title and scroll bars frame.setExtendedState(Frame.MAXIMIZED_BOTH); // full screen mode ...... The "window-close" button is no longer available in the full-screen mode. Hence, we use the ESC key to exit the program. The renderer, hence, also implements the KeyListener interface and provide KeyEvent handlers, such as keyPressed() for processing the ESC key.. Note: Read the "Graphics Programming" section on how to switch between full-screen mode and windowed mode, if desired. Example 1: Rotating 2D Shapes Modify the GLEventListener handlers init(), display() and reshape() of the template ( GLCanvas or GLJPanel) as follows: public class JOGL2Ex1Rotate2D extends GLJCanvas implements GLEventListener { ...... ...... private float angle = 0.0f; // rotation angle of the triangle /** Called back by the drawable to render OpenGL graphics */ @Override public void display(GLAutoDrawable drawable) { render(drawable); update(); } // Render a triangle private void render(GLAutoDrawable drawable) { // Get the OpenGL graphics context GL2 gl = drawable.getGL().getGL2(); // Clear the color and the depth buffers gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Reset the view (x, y, z axes back to normal) gl.glLoadIdentity(); // Draw a triangle float sin = (float)Math.sin(angle); float cos = (float)Math.cos(angle); gl.glBegin(GL_TRIANGLES); gl.glColor3f(1.0f, 0.0f, 0.0f); // Red gl.glVertex2d(-cos, -cos); gl.glColor3f(0.0f, 1.0f, 0.0f); // Green gl.glVertex2d(0.0f, cos); gl.glColor3f(0.0f, 0.0f, 1.0f); // Blue gl.glVertex2d(sin, -sin); gl.glEnd(); } // Update the angle of the triangle after each frame private void update() { angle += 0.01f; } @Override public void init(GLAutoDrawable drawable) { } // set to empty @Override public void dispose(GLAutoDrawable drawable) { } // set to empty @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { } // set to empty ...... ...... } TRY: - Using GLJPanelon Swing's JFrame. - Use GLCanvason AWT's Frame. - Use GLCanvason AWT's Applet. - Using GLJPanelon Swing's JApplet. Observe and compare the results. GLEventListener Handlers init(): called by the drawable immediately after the OpenGL graphics context is initialized. It can be used to perform one-time initialization tasks such as setting up of lights and display lists. The init() runs only once. /** Called after context is initialized, for one-time initialization tasks */ @Override public void init(GLAutoDrawable drawable) { // Get the OpenGL graphics context GL2 gl = drawable.getGL().getGL2(); // Get GL Utilities after the GL context created. // glu = GLU.createGLU(); // Enable smooth shading, which blends colors nicely, and smoothes out lighting. gl.glShadeModel(GLLightingFunc.GL_SMOOTH); // Set background color in RGBA. Alpha: 0 (transparent) 1 (opaque) gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Setup the depth buffer and enable the depth testing gl.glClearDepth(1.0f); // clear z-buffer to the farthest gl.glEnable(GL.GL_DEPTH_TEST); // enables depth testing gl.glDepthFunc(GL.GL_LEQUAL); // the type of depth test to do // Do the best perspective correction gl.glHint(GL2ES1.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); // ----- Your OpenGL initialization code here ----- // ...... } reshape(): called by the drawable when the drawable is first set to visible, and during the first repaint after the canvas has been resized. /** Called for the first-time display and after display's size changes. To set up the view port, projection mode and view volume. */ @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { // Get the OpenGL graphics context GL2 gl = drawable.getGL().getGL2(); height = (height == 0) ? 1 : height; // Prevent divide by zero float aspect = (float)width / height; // Compute aspect ratio // Set view port to cover full screen gl.glViewport(0, 0, width, height); // Set up the projection matrix - choose perspective view gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); gl.glLoadIdentity(); // reset // Angle of view (fovy) is 45 degrees (in the up y-direction). Based on this // canvas's aspect ratio. Clipping z-near is 0.1f and z-near is 100.0f. glu.gluPerspective(45.0f, aspect, 0.1f, 100.0f); // fovy, aspect, zNear, zFar // Switch to the model-view transform gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); gl.glLoadIdentity(); // reset } display(): called by the drawable to perform OpenGL graphics rendering. /** Called to render graphics */ @Override public void display(GLAutoDrawable drawable) { // Get the OpenGL graphics context GL2 gl = drawable.getGL().getGL2(); // Clear the color and the depth buffers gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); // Reset the view (x, y, z axes back to normal) gl.glLoadIdentity(); // ----- Your OpenGL rendering code here ----- // ...... } disposed(): called by the drawbale before the OpenGL context is destroyed. It can be used to release all OpenGL resources, such as memory buffers. @Override public void disposed(GLAutoDrawable drawable) { // Hardly used. } Example 2: Rotating 3D Shapes The following example show a color-pyramid and color-cube (Nehe Lesson #5). TRY: - Modify the program to run as an applet. - Modify the program to run in full screen mode. JOGL's NEWT (Native Windowing Toolkit) - GLWindow Besides relying on AWT/Swing, JOGL provides its own windowing toolkit called NEWT. The base class for NEWT is GLWindow. To allocate a GLWindow: // Get the default OpenGL profile, reflecting the best for your running platform GLProfile glp = GLProfile.getDefault(); // Specifies a set of OpenGL capabilities, based on your profile. GLCapabilities caps = new GLCapabilities(glp); // Allocate a GLWindow and add GLEventListener GLWindow window = GLWindow.create(caps); window.addGLEventListener(......); Let's rewrite Example 1 using JOGL's NEWT. OpenGL Profile and Capabilities [TODO] Revised You can create drawables to support different OpenGL profiles and capabilities: - First, construct a GLProfile, which specifies the target profile of your application, e.g., OpenGL2, OpenGL3, OpenGL4, OpenGL|ES1, OpenGL|ES2, etc. The profiles are beyond the scope of this tutorial. Read "JOGL 2 - OpenGL Profiles explained" if you are interested. We shall use the following statement to get the default profile, which best reflects your running platform. // Get the default OpenGL profile, reflecting the best for your running platform GLProfile glp = GLProfile.getDefault(); - Next, construct a GLCapabilities, based on your chosen profile, which maintain a set of OpenGL capabilities. // Specifies a set of OpenGL capabilities, based on your profile. GLCapabilities caps = new GLCapabilities(glp); - Now, you can construct your desired drawing canvas: GLCanvasfor AWT, GLJPanelfor Swing, and GLWindowfor Newt. All these canvas are GLDrawable. // Allocate a GLDrawable, based on your OpenGL capabilities. // Using GLCanvas for AWT GLCanvas canvas = new GLCanvas(caps); this.add(canvas); // "this" is a subclass of AWT's Frame // Using GLJPanel for Swing GLJPanel panel = new GLJPanel(caps); this.setContentPane(panel); // "this" is a subclass of Swing's JFrame // Using GLWindow for Newt GLWindow window = GLWindow.create(caps); window.setVisible(true); Nehe's JOGL 2 Port I have ported some of the Nehe's lessons into JOGL. Refer to Nehe for the problem descriptions. Setting Up Download Source Codes: "JOGL2Nehe01to08.zip". - Nehe's Lesson #1 "Setting Up": - Using GLCanvas: JOGL2Setup_GLCanvas.java. - Using GLJPanel: JOGL2Setup_GLJPanel.java. - Run as an applet with GLCanvas: JOGL2Setup _Applet.java. - Run in full-screen mode: JOGL2Setup_GLCanvasFullScreen. Expected output: blank black screen. OpenGL Basics I consider Lessons #2 - #8 as OpenGL basic lessons, that are extremely important! I use GLCanvas on Swing's JFrame for all these exercises, as GLJPanel does not seem to run properly. Download Source Codes: "JOGL2Nehe01To08.zip". - Nehe's Lesson #2 "Basic Shape": JOGL2Nehe02Basic2D.java. - Nehe's Lesson #3 "Color": J2Nehe03Color.java. - Nehe's Lesson #4 "Rotation": JOGL2Nehe04Rotation.java. - Nehe's Lesson #5 "3D Shape": JOGL2Nehe05Shape3D.java. - Nehe's Lesson #6 "Texture": JOGL2Nehe06Texture.java. - Nehe's Lesson #7 "Texture Filter, Lighting, and key-controlled": JOGL2Nehe07TextureFilterLightKey.java. - Nehe's Lesson #8 "Blending": JOGL2Nehe08Blending.javaand JOGL2Nehe08Blending_FullScreen.java Click imge to run the applet (not working - JNLP not supported under my server?!) OpenGL Intermediates Download Source Code: "JOGL2NeheIntermediate.zip". - Nehe's Lesson #9 "Moving Bitmaps in 3D space": J2NeheEx09Stars.java. - Nehe's Lesson #10: Building and moving in a 3D world J2NeheEx10World3D.java. - Nehe's Lesson #11 "Waving Effect": J2NeheEx11Flag.java. - Nehe's Lesson #12 "Using Display List": J2NeheEx12DisplayList.java. - Nehe's Lesson #13 "2D Texts": J2NeheEx13Text2D.java. - Nehe's Lesson #14 "3D Texts": J2NeheEx14Text3D.java. - Nehe's Lesson #16 "Fog Effect": J2NeheEx16Fog.java. - Nehe's Lesson #18 "Quadrics": J2NeheEx18Quadrics.java. - Nehe's Lesson #19 "Particle Engine": (a) J2NeheEx19Particle.java, (b) J2NeheEx19Firework.java. - Nehe's Lesson #26 "Reflection": J2NeheEx26Reflection.java. More JOGL Ports/Examples JOGL comes with many excellent demos. You can get the latest demo source codes from ⇒ "jogl demos" ⇒ "src" ⇒ "demos". However, many of these demos are not properly explained (?). Gears/JGears You can get the source codes " Gears.java" from JOGL demos; or get the latest code from ⇒ "jogl demos" ⇒ "src" ⇒ "demos" ⇒ "gears" ⇒ " Gears.java". " Gears.java" run the JOGL's NEWT window. [TODO] more. There is a variation called " JGears.java", which included 2 images and texts in the display. [TODO] Photo-Cube [TODO] Bouncing Balls inside a Cube [TODO] JOGL Demos [TODO] Redbook Examples Deploying JOGL Applications, Applets and Web Start Apps Read "Java's Rich Internet Applications (RIA) - Applets & Web Start Apps". Deploying JOGL 2.0 WebStart App Jarring Up JOGL App Jar-up your JOGL application's classes and relevant resources. Preparing JNLP file <?xml version="1.0" encoding="UTF-8"?> <jnlp> <information> <title>My JOGL App</title> <vendor>My Company</vendor> <offline-allowed /> </information> <resources> <j2se version="1.4+" href="" /> <jar href="my_app.jar" main="true" /> <extension name="jogl-all-awt" href="" /> </resources> <application-desc </jnlp> The above <extension> is meant for JOGL application. The necessary JOGL jar-files are provide by the jogamp server. Choose the appropriate JOGL version that you used to compile your application, e.g., " v2.0-rc8". Deploying JOGL 2.0 Applet Reference: - Java Network Launch Protocol (JNLP) Support @ - JNLPAppletLauncher @. - Test page for JOGL Applets @. - JOGL: Applets @. JNLP Applet (JDK 6u10) Starting from JDK 6u10 Standard "JNLP Applets" are supported, in which the Java Plug-In (for web browser) provides support for launching applets directly from JNLP files. To launch an applet from a JNLP file, use the " jnlp_href" parameter in the <applet> tag. For example, the following HTML file contains an applet which references JNLP file " my_applet.jnlp". <applet width="300" height="300" > <param name="jnlp_href" value="my_applet.jnlp"> </applet> The JNLP file " my_applet.jnlp" is as follows: <?xml version="1.0" encoding="UTF-8"?> <jnlp href="my_applet.jnlp"> <information> <title>My Applet</title> <vendor>My Company</vendor> <offline-allowed /> </information> <resources> <j2se version="1.6+" /> <jar href="my_applet.jar" main="true" /> <extension name="jogl-all-awt" href="" /> </resources> <applet-desc </applet-desc> </jnlp> The above extension is meant for JOGL app, where you should choose the appropriate JOGL version that you used to compile your application, e.g., " v2.0-rc8". Applet Launcher (JDK 6u10) JDK 1.6u10 has greatly improved the efficiency of Java applet, and it is now feasible and practical to deploy a huge Java program as an applet, via a so-called "Applet Launcher". JNLP applet is support since JDK 6u14. However, you may need to fall back to the Applet-Launcher to support the older releases. Depolying JOGL Applet as "Standard JNLP Applet" / "JNLPAppletLauncher" We shall deploy JOGL applet as "JNLP Applet" if the web browser JRE Plug-in supports it (above JDK 6u14); otherwise, we fall back to JNLPAppletLauncher, as follow: Prepare a JNLP file as follow: <?xml version="1.0" encoding="utf-8"?> <jnlp> <information> <title>JOGL Test</title> <vendor>SomeOne</vendor> </information> <resources> <j2se version="1.6+"/> <property name="sun.java2d.noddraw" value="true"/> <jar href="YourJoglApp.jar" main="true"/> <extension name="jogl-all-awt" href="" /> </resources> <applet-desc </applet-desc> </jnlp> In the <extension>'s href, set to the appropriate JOGL version that you used to compile your program, e.g., " v2.0-rc8" in my case. Use the following <applet> tag with a reference to the JNLP file in parameter " jnlp_href": <applet code="org.jdesktop.applet.util.JNLPAppletLauncher" width=600 height=400 <param name="codebase_lookup" value="false"> <param name="subapplet.classname" value="YourAppletClass"> <param name="subapplet.displayname" value="JOGL Applet Test"> ="YourJnlpFile.jnlp"> </applet> where: - Attribute " code" is pointing at " JNLPAppletLauncher", which is downloaded from, instead of your local server. - Attribute " archive" includes all the jar files for running JOGL program. Again, they are downloaded from the server. " archive" also include your JOGL JAR file. - Attributes " width" and " height" specify the width and height of your applet's display area inside the browser's window. - The name of your main applet is specified in the parameter " subapplet.classname". - The parameter " codebase_lookup" is set to false, as this applet does not need to fetch other files from your local server's code base path. - The parameter " noddraw.check" is set to true, to check if DirectDraw is enabled and, if so, will prompt the user to disable it for all applets. DirectDraw is incompatible with OpenGL. Disabling it is unlikely to slow down other non-3D applets significantly. REFERENCES & RESOURCES - JOGL mother site @; JOGL tutorial @; JOGL Wiki @. - JOGL Developer and master repository (including source and demos) @. - OpenGL mother site @. - Nehe OpenGL tutorials @. - OpenGL Programming Guide (Red book); OpenGL Superbible (Blue book)
http://www3.ntu.edu.sg/home/ehchua/programming/opengl/JOGL2.0.html
CC-MAIN-2015-22
refinedweb
4,746
52.05
Lab 8: Object Oriented Programming Due at 11:59pm on Friday, 7/26/2019. Starter Files Download lab-3 and submit through Ok. - If you would like to be checked off, make sure you sign yourself up on the queue in a lab. The questions are at the end of this page. - The remaining questions are optional. It is recommended that you complete these problems in your own time. - All starter code for this lab can be found in classes.py. Topics Consult this section if you need a refresher on the material for this lab. It's okay to skip directly to the questions and refer back here should you get stuck. Object-Oriented Programming In this lab we'll be diving into object-oriented programming (OOP), a model of programming that allows you to think of data in terms of "objects" with their own characteristics and actions, just like objects in real life! This is very powerful and allows you to create objects that are specific to your program - you can read up on all the details here. OOP Example: Car Class Tiffany is running late, and needs to get from San Francisco to Berkeley before lecture starts. She'd take BART, but that will take too long. It'd be great if she had a car. A monster truck would be best, but a car will do -- for now... In car.py, you'll find a class called Car. A class is a blueprint for creating objects of that type. In this case, the Car class statement tells us how to create Car objects. Constructor Let's build Tiffany a car! Don't worry, you won't need to do any physical work -- the constructor will do it for you. The constructor of a class is a function that creates an instance, or a single occurrence, of the object outlined by the class. In Python, the constructor method is named __init__. Note that there must be two underscores on each side of init. The Car class' constructor looks like this: def __init__(self, make, model): self.make = make self.model = model self.color = 'No color yet. You need to paint me.' self.wheels = Car.num_wheels self.gas = Car.gas The __init__ method for Car has three parameters. The first one, self, is automatically bound to the newly created Car object. The second and third parameters, make and model, are bound to the arguments passed to the constructor, meaning when we make a Car object, we must provide two arguments. Don't worry about the code inside the body of the constructor for now. Let's make our car. Tiffany would like to drive a Tesla Model S to lecture. We can construct an instance of Car with 'Tesla' as the make and 'Model S' as the model. Rather than calling __init__ explicitly, Python allows us to make an instance of a class by using the name of the class. >>> tiffanys_car = Car('Tesla', 'Model S') Here, 'Tesla' is passed in as the make, and 'Model S' as the model. Note that we don't pass in an argument for self, since its value is always the object being created. An object is an instance of a class. In this case, tiffanys_car is now bound to a Car object or, in other words, an instance of the Car class. Attributes and Dot Notation So how are the make and model of Tiffany's car actually stored? Let's talk about attributes of instances and classes. Here's a snippet of the code in car.py with the instance and class attributes in the Car class:) In the first two lines of the constructor, the name self.make is bound to the first argument passed to the constructor and self.model is bound to the second. These are two examples of instance attributes. An instance attribute is a quality or variable that is specific to an instance, and not the class itself! Instance attributes are accessed using dot notation (separating the instance and attribute with a period) with an instance. In this case, self is bound to our instance, so self.model references our instance's model. Our car has other instance attributes too, like color and wheels. As instance attributes, the make, model, and color of tiffanys_car do not affect the make, model, and color of other cars. On the other hand, a class attribute is a quality that is shared among all instances of the class. For example, the Car class has four class attributes defined at the beginning of a class: num_wheels = 4, gas = 30, headlights = 2 and size = 'Tiny'. The first says that all cars have 4 wheels. You might notice in the __init__ method of the Car class, the instance attribute gas is initialized to the value of Car.gas, the class attribute. Why don't we just use the class attribute, then? The reason is because each Car's gas attribute needs to be able to change independently of each other. If one Car drives for a while, it should use up some gas, and that Car instance should reflect that by having a lower gas value. However, all other Cars shouldn't lose any gas, and changes to a class attribute will affect all instances of the class. Class attributes can also be accessed using dot notation, both on an instance and on the class name itself. For example, we can access the class attribute size of Car like this: >>> Car.size 'Tiny' And in the following line, we access tiffanys_car's color attribute: >>> tiffanys_car.color 'No color yet. You need to paint me.' Looks like we need to paint tiffanys_car! Methods Let's use the paint method from the Car class. Methods are functions that are specific to a class; only an instance of the class can use them. We've already seen one method: __init__! Think of methods as actions or abilities of objects. How do we call methods on an instance? You guessed it, dot notation! >>> tiffanys_car.paint('black') 'Tesla Model S is now black' >>> tiffanys_car.color 'black' Awesome! But if you take a look at the paint method, it takes two parameters. So why don't we need to pass two arguments? Just like we've seen with __init__, all methods of a class have a self parameter to which Python automatically binds the instance that is calling that method. Here, tiffanys_car is bound to self so that the body of paint can access its attributes! You can also call methods using the class name and dot notation; for example, >>> Car.paint(tiffanys_car, 'red') 'Tesla Model S is now red' Notice that unlike when we painted Tiffany's car black, this time we had to pass in two arguments: one for self and one for color. This is because when you call a method using dot notation from an instance, Python knows what instance to automatically bind to self. However, when you call a method using dot notation from the class, Python doesn't know which instance of Car we want to paint, so we have to pass that in as well. Inheritance Tiffany's red Tesla is pretty cool, but he wants a bigger car! How about we create a monster truck for him instead? In car.py, we've defined a MonsterTruck class. Let's look at the code. Let's create a new instance of Tiffany's monster truck: >>> tiffanys_truck = MonsterTruck('Monster Truck', 'XXL') Does it behave as you would expect a Car to? Can you still paint it? Is it even drivable? Well, the class MonsterTruck is defined as class MonsterTruck(Car):, meaning its superclass that you want to be unique from those in the superclass. >>> tiffanys_car.size 'Tiny' >>> tiffanys. Regular Cars cannot rev! Everything else -- the constructor __init__, paint, num_wheels, gas -- are inherited from Car. Required Questions WWPD Q1: Using the Car class Here is the full definition of the Car class from the car example above in car.py: car -u If an error occurs, type Error. If nothing is displayed, type Nothing. >>> tiffanys_car = Car('Tesla', 'Model S') >>> tiffanys_car.model______'Model S'>>> tiffanys_car.gas = 10 >>> tiffanys_car.drive()______'Tesla Model S goes vroom!'>>> tiffanys_car.drive()______'Cannot drive!'>>> tiffanys_car.fill_gas()______'Gas level: 20'>>> tiffanys_car.gas______20>>> Car.gas______30 >>> christophers_car = Car('Tesla', 'Model S') >>> christophers_car.wheels = 2 >>> christophers_car.wheels______2>>> Car.num_wheels______4>>> christophers_car.drive()______'Cannot drive!'>>> Car.drive()______Error (TypeError)>>> Car.drive(christophers_car)______'Cannot drive!' For the following, we reference the MonsterTruck class, also in car.py: class MonsterTruck(Car): size = 'Monster' def rev(self): print('Vroom! This Monster Truck is huge!') def drive(self): self.rev() return Car.drive(self) >>> alexs_car = MonsterTruck('Monster', 'Batmobile') >>> alexs_car.drive()______Vroom! This Monster Truck is huge! 'Monster Batmobile goes vroom!'>>> Car.drive(alexs_car)______'Monster Batmobile goes vroom!'>>> MonsterTruck.drive(alexs_car)______Vroom! This Monster Truck is huge! 'Monster Batmobile goes vroom!'>>> Car.rev(alexs_car)______Error (AttributeError) Magic: The Lambda-ing In the next part of this lab, we will be implementing a card game! card from their deck. If a player's deck is empty when they try to draw, they will automatically lose the game. Cards have a name, an attack stat, and a defense stat. ATK/1000 DEF and Player 2 plays a card with 1500 ATK/3000 DEF. will cause the opponent to discard and re-draw the first 3 cards in their hand. - A TA will swap the opponent card's attack and defense. - An Instructor will add 300 attack and defense to all cards in the player's deck, and then add a copy of the opponent's card to both the player's deck and the player's hand. These are a lot of rules to remember, so refer back here if you need to review them, and let's start making the game! Q(object): ***"self.name = name self.attack = attack self.defense = defensedef power(self, other_card): """ Calculate power as: (player card's attack) - (opponent card's defense)/2 where other_card is the opponent's card. >>> staff_member = Card('staff', 400, 300) >>> other_staff = Card('other', 300, 500) >>> staff_member.power(other_staff) 150.0 >>> other_staff.power(staff_member) 150.0 >>> third_card = Card('third', 200, 400) >>> staff_member.power(third_card) 200.0 >>> third_card.power(staff_member) 50.0 """"*** YOUR CODE HERE ***"return self.attack - other_card.defense / 2 Use Ok to test your code: python3 ok -q Card.__init__ python3 ok -q Card.power Q ***"self.hand = [deck.draw() for _ in range(5) ***"self.hand.append(self.deck.draw() ***"return self.hand.pop(card_index). Optional Questions For the following sections, do not overwrite any lines already provided in the code. Additionally, make sure to uncomment any calls to Q, other_card, player, opponent): """ Discard the first 3 cards in the opponent's hand and have them draw the same number of cards from their deck. >>> from cards import * >>> player1, player2 = Player(player_deck, 'p1'), Player(opponent_deck, 'p2') >>> other_card = Card('other', 500, 500) >>> tutor_test = TutorCard('Tutor', 500, 500) >>> initial_deck_length = len(player2.deck.cards) >>> tutor_test.effect(other_card, player1, player2) p2 discarded and re-drew 3 cards! >>> len(player2.hand) 5 >>> len(player2.deck.cards) == initial_deck_length - 3 True """"*** YOUR CODE HERE ***"opponent.hand = opponent.hand[3:] for _ in range(3): opponent.draw()#Uncomment the line below when you've finished implementing this method! #print('{} discarded and re-drew 3 cards!'.format(opponent.name)) Use Ok to test your code: python3 ok -q TutorCard.effect Q5: TAs: Shift Let's add an effect for TAs now! Implement the effect method for TAs, which swaps the attack and defense of the opponent's card. class TACard(Card): cardtype = 'TA' def effect(self, other_card, player, opponent): """ Swap the attack and defense of an opponent's card. >>> from cards import * >>> player1, player2 = Player(player_deck, 'p1'), Player(opponent_deck, 'p2') >>> other_card = Card('other', 300, 600) >>> ta_test = TACard('TA', 500, 500) >>> ta_test.effect(other_card, player1, player2) >>> other_card.attack 600 >>> other_card.defense 300 """"*** YOUR CODE HERE ***"other_card.attack, other_card.defense = other_card.defense, other_card.attack Use Ok to test your code: python3 ok -q TACard.effect Q6: Instructors: RallyWe now have effects that affect the opponent's card, but what about ones that affect ours? Implement the effectmethod for Instructors, who increase the attack and defense of all cards in the player's deck (but not their hand) by 300 each, and then add a copy of the opponent's card to both the player's deck and their hand! Note that the 2 added cards are distinct copies, and they do not get the +300/300 buff. Note: to access a list of all the cards in a deck, use deck.cards. To make a copy of a card, use card.copy(). class InstructorCard(Card): cardtype = 'Instructor' def effect(self, other_card, player, opponent): """ Increase attack/defense of every card in the player's deck by 300 each, then adds a copy of the opponent's card to both the player's deck and to their hand. >>> test_card = Card('card', 300, 300) >>> instructor_test = InstructorCard('Instructor', 500, 500) >>> opponent_card = test_card.copy() >>> test_deck = Deck([test_card.copy() for _ in range(8)]) >>> player1, player2 = Player(test_deck.copy(), 'p1'), Player(test_deck.copy(), 'p2') >>> instructor_test.effect(opponent_card, player1, player2) p2's card added to p1's hand and deck! >>> [(card.attack, card.defense) for card in player1.deck.cards] [(600, 600), (600, 600), (600, 600), (300, 300)] >>> len(player1.hand) 6 >>> opponent_card.attack 300 >>> opponent_card.defense 300 """"*** YOUR CODE HERE ***"for card in player.deck.cards: card.attack += 300 card.defense += 300 player.deck.cards.append(other_card.copy()) player.hand.append(other_card.copy())#Uncomment the line below when you've finished implementing this method! #print('{}\'s card added to {}\'s hand and deck!'.format(opponent.name, player.name)) Use Ok to test your code: python3 ok -q InstructorCard.effect Q.
https://inst.eecs.berkeley.edu/~cs61a/su19/lab/lab08/
CC-MAIN-2020-29
refinedweb
2,296
68.26
This article will discuss the Microsoft algorithm for generating PE Checksums. Microsoft does not appear to publicly offer the specification, including a lack of documentation in the Microsoft Portable Executable and Common Object File Format Specification. Additionally, Matt Pietrek does not offer the algorithm in his works. Contrary to popular belief, the algorithm used by Microsoft is not a CRC. This is despite the fact that Knowledge Base articles such as 65122 claim a 32 bit CRC is used (shown below). Below is the breakout of four octets used in the checksum. The unused byte is set to 0, effectively creating a 24 bit checksum. It is noteworthy that the algorithm - an Additive Checksum - is a redundancy check; however it is not a CRC. A CRC has additional mathematical properties desireable in the problem domain of error detection. For those interested in Microsoft's Outlook CRC Algorithm, see Frank Sconzo's thread CRC on Unix vs Win32 on comp.lang.perl.misc. Tim Heaney reveals Microsoft's method. Finally, for the reader who is interested in the complete algorithm, Peter Szor presents the high level design in The Art Of Computer Virus Research And Defense. The W32/Kriz virus internally computed the checksum of infected files to mask tampering. Szor documents the algorithm and virus in Section 6.2.8.1.12, 'Checksum Recalculation'. The topics to be covered are as follows. Note that Generating Loop and Generating Loop Setup appear to be out of order. This is by design, and will make sense when visited. This article will examine the main Generating Loop and Generating Loop Setup in detail, while offering no treatment of the final linear transformations. The goal of the omissions is to preserve Microsoft's Security through Obscurity policy. This article uses four tools to examine the algorithm: PEChecksum is used to interrogate an EXE's checksum and write an arbitrary checksum. In addition, the executable depends on ImageHlp.dll. The dependency forces the link-loader to load the Image Help so that a live target analysis can proceed. PEChecksum is available with source code in the download area. WinDbg is used because SoftICE is no longer available from Compuware; and perhaps even better: WinDbg is free. WinDbg is available for download from Microsoft's site. kd, OllyDbg, or SyserDebug should suffice the reader as a replacement if desired. The reader should keep in mind that WinDbg is authored by the Windows Operating System Team. This is in contrast to the Developer Team which produces Visual Studio, or third parties which produce competing products such as OllyDbg or SyserDebug. UltraEdit from IDM software can be used as a hex editor to write values to the executable file. UltraCompare is used to verify differences between the original file and the altered file. It is highly recommended that the reader set up local Symbols on his or her machine. John Robbins covers the subject extensively in Debugging Microsoft .NET 2.0 Applications, Chapters 2 and 6. John also provides an excellent script (OSsyms.js) to automate the symbol retrieval process. For those who do not have access to the text, visit [Debugging] - Symbols by Johnathan [Darka]. Note that a local Symbol Server is not required - simply use the server provided by Microsoft. However, the reader does want the symbols available locally. Imagehlp.dll is a library which exposes many debugging and maintenance routines to the programmer. Noteworthy is that the library is not thread safe. For techniques to reuse code of Imagehlp in a thread safe manner, see Grafting Compiled Code: Unlimited Code Reuse. ImageHlp.dll offers function CheckSumMappedFile(). CheckSumMappedFile() internally calls function ChkSum(), which is the workhorse of checksum computation. The signature of CheckSumMappedFile() is shown below. CheckSumMappedFile() ChkSum() PIMAGE_NT_HEADERS CheckSumMappedFile( PVOID BaseAddress, DWORD FileLength, PDWORD HeaderSum, PDWORD CheckSum ); BaseAddress is returned from MapViewOfFile(), and FileLength can be determined by GetFileSize() or GetFileSizeEx(). The Loader will map a view of the executable during process creation by way of MtMapViewOfSection() (which offers a forward API face of MapViewOfFile()). For a more detailed examination of the Loader's behavior, see Dynamic TEXT Section Image Verification. BaseAddress FileLength MtMapViewOfSection() MapViewOfFile() According to Ken Johnson, Microsoft MVP, past SDKs did in fact have CheckSumMappedFile() in source code, less ChkSum(): imagehlp used to be an SDK sample a long time ago, with the pointed omission of the source code for the "ChkSum" helper function used by CheckSumMappedFile(). From the SDK sample source, it looks like it was intended to be linked in from another library or a .asm file that was never shipped with the sample code. Additionally, the earlier SDK provides the following prototype: USHORT ChkSum( DWORD PartialSum, PUSHORT Source, DWORD Length ); and PartialSum = ChkSum(0, (PUSHORT)BaseAddress, (FileLength + 1) >> 1); A more complete introduction to WinDbg is available on Code Project at Windows Debuggers: Part 1: A WinDbg Tutorial by Saikat Sen. The author prefers three windows to be present in WinDbg: the Command Window, the Disassembly Window, and the Register Window. At any given time, a Memory Window and Call Stack Window may make an appearence as required. Take the time in advance to open and dock the windows. As John Robbins states with regards to the floating windows, "they have a serious z-order problem". Based on how lucky the author is, the Command Window usually docks on top of the lower two windows. To open the various Windows, use the View menu. Below is a typical view of a WinDbg session. Below is list of typical commands used for a session. Users who are familiar with gdb or SoftICE should feel right at home, without the need for CTRL-D to break into SoftICE. db <address|register> .restart .attach pid .detach ? .hh command Once an executable file is loaded in WinDbg, the program will be suspended. To begin execution, press F5 or type g in the Command Window after setting the desired breakpoints. Then, exercise the excutable as one would when using the Visual Studio debugger. For those interested in analizing Windows code using Linux and gdb, see Joe Stewart's Reverse Engineering Hostile Code and Alien Autopsy: Reverse Engineering Win32 Trojans on Linux at the SecurityFocus website. For Unix and Linux, objdump (with it's PERL based wrapper dasm) and gdb are two of the tools of choice. gdb supports debugging of C, C++, Java, Fortran and Assembly among other languages. In addition, gdb is designed to work closely with the GNU Compiler Collection (GCC). objdump and dasm collectively act as full disassembler. Alternately, one can run Windows applications such as IDA on Linux using Wine, which acts as a compatibility layer for running Windows programs on Linux. Analysis will proceed with a presumed ImageHlp.dll load address of 0x76C9000. If the reader does not know what modules are loaded, execute the list modules command in WinDbg (lm) after opening the executable. Below PEChecksum.exe was opened in WinDbg, resulting in the following modules being loaded due to dependencies. deferred is displayed because WinDbg is using a lazy algorithm for resolving symbols. To force the loading of symbols, use the load symbols command (ld). The command can take a module name, or the wildcard (*) to load all symbols. There are four areas of interest in the analysis: Prologue, Loop Setup, Generating Loop, and Epilogue. Prologue is similar to Loop Setup, except Prologue sets up registers and the stack - it is a lower level setup. Loop Setup, as defined in this article, works at a higher level. Epilogue is the area this article will remain vague, since some additional calculations are occurring which will not be revealed. The analysis is left as an exercise to the reader. Note that the analysis will proceed out of order since once one grasps the essence of the main Generating Loop, what is occurring in the Generating Loop Setup will be more apparent. Before the examination can begin, two key pieces of information are required to aide in tracing program flow: The BaseAddress and the FileSize. These values are 0xB7000 and 0x10E00 respectively. This information can be gathered from OutputDebugString() in the executable if the reader has instrumented such. There are other means, such as examining the return value from MapViewOfFile() in WinDbg. FileSize OutputDebugString() To examine Prologue, issue bp imagehlp!ChecksumMappedFile. This line is highlighted in red by WinDbg in the above capture. The blue highlight indicates the next instruction sequence to be executed. From above, a Structured Exception Handler is installed at 0x76C96F03. Then values are pushed onto the stack in preparation for calling ChkSum. ChkSum 76c96f03 68c86fc976 push offset imagehlp!`string'+0x3c (76c96fc8) 76c96f08 e8acc5ffff call imagehlp!_SEH_prolog (76c934b9) 76c96f0d 8b7510 mov esi,dword ptr [ebp+10h] 76c96f10 832600 and dword ptr [esi],0 76c96f13 8b450c mov eax,dword ptr [ebp+0Ch] 76c96f16 d1e8 shr eax,1 76c96f18 50 push eax 76c96f19 ff7508 push dword ptr [ebp+8] 76c96f1c 6a00 push 0 76c96f1e e856d6ffff call imagehlp!ChkSum (76c94579) It is desired to determine what is being moved into ESI at 0x76C96F0D (mov esi, dword ptr [ebp+10h]) in preparation for the call. Issue dd ebp. This will display double word values at the address of the base pointer: 0xB70000 is the file mapping view base address, which is pushed on the stack (from above). 76c96f13 8b450c mov eax,dword ptr [ebp+0Ch] 76c96f16 d1e8 shr eax,1 76c96f18 50 push eax Next, EAX is populated with the file's size 0xE100 (shown above). For an unknown reason, a right shift occurs, effectively pushing 0xE100/2 = 0x7080 onto the stack. It is presumed by the author this is from the original adaptation of RFC 1071, which operated on word size (16 bit) quanities. Many thanks to Peter Bell for bringing to light the signifigance of the shift pertaining to machine word sizes. Stepping into 0x76C96F1E (private function ChkSum()), one can examine the final steps of the prologue (shown below). 76c94579 56 push esi 76c9457a 8b4c2410 mov ecx,dword ptr [esp+10h] 76c9457e 8b74240c mov esi,dword ptr [esp+0Ch] 76c94582 8b442408 mov eax,dword ptr [esp+8] 76c94586 d1e1 shl ecx,1 The following is occuring: Then, the original file size is restored with shl ecx, 1. 76c94586 d1e1 shl ecx,1 Notably missing is push ebp and mov ebp, esp. This sequence is generally emitted by the compiler since it is bad karma to operate directly on the Stack Pointer (ESP). This could also indicate a Frame Pointer Omission (FPO) generated by the compiler. At this point, it is apparent ESI will be used as a pointer to the value being consumed, and ECX will be a counter. The role of EAX will be revealed below. One final note on Prologue. The code below is testing for a 0 file size by way of the je instruction. If the file size is 0, the entire Loop Setup and Generating Loop execution paths are bypassed. This should imply to the reader various return values are being prepared at 0x76C946E7. ... 76c94582 8b442408 mov eax,dword ptr [esp+8] 76c94586 d1e1 shl ecx,1 76c94588 0f8459010000 je imagehlp!ChkSum+0x16e (76c946e7) To set a breakpoint on the main generating loop, issue bp imagehlp!ChkSum+0xE8 (or address 0x76C94661). The main generating loop is shown below. The loop consumes 0x80 bytes (0x20 DWORDS) of program data at a time. When a double word is consumed, it is added to a running total in EAX (adc assembly instruction). By using the adc instruction, the algorithm realizes a 33 bit register rather than a 32 bit register. 76c94661 0306 add eax,dword ptr [esi] 76c94663 134604 adc eax,dword ptr [esi+4] 76c94666 134608 adc eax,dword ptr [esi+8] ... 76c946b7 134674 adc eax,dword ptr [esi+74h] 76c946ba 134678 adc eax,dword ptr [esi+78h] 76c946bd 13467c adc eax,dword ptr [esi+7Ch] 76c946c0 83d000 adc eax,0 The last instruction (adc eax, 0) simply adjusts the flags register. The instructions following the main loop are book keeping (shown below). 76c946c3 81c680000000 add esi,80h 76c946c9 81e980000000 sub ecx,80h 76c946cf 7590 jne imagehlp!ChkSum+0xe8 (76c94661) ESI (the file mapping pointer) is incremented, and ECX (the counter) is decremented. After the sub ecx, 80h is executed, control will either be passed to the top of the loop at 0x76C94661 (if ECX does not equal 0) or fall into other code (ECX = 0). So the reader can infer some of the Epilogue resides at 0x76C946D1. In the case of the PEChecksum.exe, the file size is 0xE100. The loop operates on blocks of 0x80, so the loop will execute 0x1C2 or 450 iterations. This begs the question: What if the file size is not a multiple of 0x80? This question is answered in the Loop Setup. The loop setup code starts at 0x76C9458E, and ends at 0x76c94660 (the byte before the Main Generating Loop). Consider the first test: 76c9458e f7c602000000 test esi,2 if [br=1] (branch = true), jump to the next test. 76c94594 7410 je imagehlp!ChkSum+0x2d (76c945a6) Otherwise some additions are performed as in the main generating loop - but not a complete loop: 76c94596 2bd2 sub edx,edx ; Zero EDX 76c94598 668b16 mov dx,word ptr [esi] ; set up for addition 76c9459b 03c2 add eax,edx ; Add 1 WORD to eax (2 = sizeof(WORD) ) 76c9459d 83d000 adc eax,0 ; adjust EFLAG register 76c945a0 83c602 add esi,2 ; adjust ESI Then into the next test (test esi, 8) at 76c945b3. 76c945b3 f7c108000000 test ecx,8 if [br=1] (branch = true), jump to the next test. Otherwise: 76c945b9 7414 je imagehlp!ChkSum+0x56 (76c945cf) 76c945bb 0306 add eax,dword ptr [esi] 76c945bd 134604 adc eax,dword ptr [esi+4] 76c945c0 83d000 adc eax,0 76c945c3 83c608 add esi,8 76c945c6 83e908 sub ecx,8 Excuting the code results in an add, adjust pointer, and decrement counter. The observation from above is sizeof( 2 DWORDS ) = 8. Next, another test/branch. The code of interest is: sizeof 76c945cf f7c110000000 test ecx,10h 76c945d5 741a je imagehlp!ChkSum+0x78 (76c945f1) 76c945d7 0306 add eax,dword ptr [esi] 76c945d9 134604 adc eax,dword ptr [esi+4] 76c945dc 134608 adc eax,dword ptr [esi+8] 76c945df 13460c adc eax,dword ptr [esi+0Ch] 76c945e2 83d000 adc eax,0 76c945e5 83c60C add esi,0Ch 76c945e8 83e90C sub ecx,0Ch Again, add, adjust pointer, and decrement counter. The observation from above is sizeof( 4 DWORDS ) = 16 = 10h. Following this pattern (before the main loop), up to and including test ecx,40h will cause ECX % 0x80 = 0 (where % is the customary modular reduction). At this point, the main generating loop executes and the remaining files size to be processed is a multiple 0x80. Ken Johnson points out that the loop prologue could be an optimaization by adjusting for alignments. The author also suspected such, but cannot state the reasoning in a definitive manner. Finally, Parch Andri suggested this is similar to Loop Unwinding with a Duff Device. The code may be hand written rather than emitted by the compiler. As stated earlier, the Epilogue will be ommitted. However, one observation is noteworthy to support the author's opinion of an adaptaion of RFC 1071: the folding of the 32 bit value into a 16 bit value. The instruction sequence is a follows. Note the folding occurs twice in case a Carry was generated during the first fold. 76c946e7 8bd0 mov edx,eax ; EDX = EAX 76c946e9 c1ea10 shr edx,10h ; EDX = EDX >> 16 EDX is high order 76c946ec 25ffff0000 and eax,0FFFFh ; EAX = EAX & 0xFFFF EAX is low order 76c946f1 03c2 add eax,edx ; EAX = EAX + EDX High Order Folded into Low Order 76c946f3 8bd0 mov edx,eax ; EDX = EAX 76c946f5 c1ea10 shr edx,10h ; EDX = EDX >> 16 EDX is high order 76c946f8 03c2 add eax,edx ; EAX = EAX + EDX High Order Folded into Low Order 76c946fa 25ffff0000 and eax,0FFFFh ; EAX = EAX & 0xFFFF EAX is low order 16 bits Each time an executable is compiled, a time stamp is embedded in the executable. Should the reader add whitespace to a source file (to force recompilation), the checksum will be different. The effects of time stamping are also present in object files. The author has never been one to shy away from an implementation. To this end, an attack on the checksum is presented. Originally, the author desired to demonstrate the weakness of a CRC as an integrity verification tool, arguing that software authors should embrace Assembly Code Signing. The article was originally going to perform the following: Interestingly, the W32/Kriz virus performed the same operation to mask it's tampering of infected files in 1999. The described seige is clearly overkill based on Microsoft's scheme. Instead, an attack which is easier to understand will be demonstrated which shows altering of bytes on DWORD boundaries goes undetected. DWORD The assault will begin on the innocuous string, "This program cannot be run in DOS mode." The string is '$' terminated since it is an assembly language string (as opposed to NULL termination for a C string). After the '$', a string of NULLs is encountered as noise bytes for padding the remainder of the stub program. NULL So, it is desired to swap one DWORD with another. If we envisioned the tail of the string ("This program ...") as a character representation in an array, it would look as follows: ..., '$', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ... Performing the DWORD swap, the executable would be modified as follows: ..., 0x00, 0x00, 0x00, 0x00, '$', 0x00, 0x00, 0x00, ... Viewing the difference in the files using IDM's UltraCompare reveals the following binary difference at 0x78. The difference at 0x7C is not in view: And finally, the resulting Checksum of the altered notepad.exe. It too has a checksum of 0x00014F7F. Both the original and altered notepad programs are available for download. For those who question whether the file has been truly altered, one only needs to look at the different MD5 hashes of the files (recall that both files have the same checksum): Since the CRC-32 is of interest, the output of CRC32.exe: The authors of RFC 1071 offer a 32 bit implementation of the Computing the Internet Checksum as follows (taken from Section 4.1): /*; It is left to the reader to conclude how similar the Microsoft PE Checksum algorithm is to the Internet Checksum Algorithm. To the author, it is readily apparent. In the author's humble opinion, Microsoft misapplied the Additive Checksum. Microsoft did not keep in mind the additional error detection which occurs in the upper layers in the OSI model or TCP/IP stack. In the Microsoft application of the checksum, the checksum is the only layer of detection. A larger concern to the author is that the checksum is one of the last safeguards between loading a Kernel Driver or Trusted Service and the Operating System. What is disappointing is that Microsoft choose speed over a slighly more robust CRC-32. To add to the woes, Microsoft's PE format leaves plenty of room for tampering after the MS-DOS 2.0 Compatible EXE Header. Perhaps Microsoft will close these holes with Code Signing and Next Generation Secure Computing Base in the future. As of this writing, Microsoft only requires Code Signing for x64 based Vista Kernel Mode drivers. The reader is invited to read Kernel-Mode Code Signing Walkthrough. In fairness to Microsoft, the author would like to offer David Delaune's somewhat differing opinion: .... Finally, this is the author's opinion, and clearly open to misinterpretations during the analysis. Please feel free to correct any mistakes. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) #include <afxmt.h> #include <atlbase.h> #include <imagehlp.h> #pragma comment(lib, "imagehlp.lib") DWORD CUtils::GetPEChecksum(const WCHAR* u16_Path, DWORD* pu32_CalcChecksum, // Calculated DWORD* pu32_PEChecksum) // Read from PE header { *pu32_CalcChecksum = 0; *pu32_PEChecksum = 0; CHandle i_File(CreateFileW(u16_Path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0)); if ((HANDLE)i_File == INVALID_HANDLE_VALUE) return GetLastError(); DWORD u32_Size = GetFileSize(i_File, 0); CHandle i_Map(CreateFileMapping(i_File, NULL, PAGE_READONLY, 0, 0, NULL)); if (!(HANDLE)i_Map) return GetLastError(); void* p_Mem = MapViewOfFile(i_Map, FILE_MAP_READ, 0, 0, 0); if (!p_Mem) return GetLastError(); // CheckSumMappedFile() is not threadsafe static CCriticalSection i_Critical; CCritSecLock i_Lock(*i_Critical); IMAGE_NT_HEADERS* pk_NT = CheckSumMappedFile(p_Mem, u32_Size, pu32_PEChecksum, pu32_CalcChecksum); if (!pk_NT) return GetLastError(); if (!UnmapViewOfFile(p_Mem)) return GetLastError(); return 0; } header computed wininet.dll 0x11111111 0x11111111 user32.dll 0x22222222 0x22222222 version.dll 0x33333333 0x03030303 * MISMATCH * urlmon.dll n/a 0x44444444 * INVALID HEADER * . . . WORD ChkSum(WORD oldChk, USHORT * ptr, DWORD len) { DWORD c = oldChk; while (len) { int l = min(len, 0x4000); len -= l; for (int j=0; j<l; ++j) { c += *ptr++; } c = (c&0xffff) + (c>>16); } c = (c&0xffff) + (c>>16); return (WORD)c; } DWORD GetPEChkSum(LPCTSTR filename) { HANDLE hf = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); if (hf == INVALID_HANDLE_VALUE) return 0; DWORD dwRead = 0; DWORD dwSize = GetFileSize(hf, 0); IMAGE_DOS_HEADER dosh; IMAGE_NT_HEADERS nth; ReadFile(hf, &dosh, sizeof(dosh), &dwRead, 0); SetFilePointer(hf, dosh.e_lfanew, 0, FILE_BEGIN); ReadFile(hf, &nth, sizeof(nth), &dwRead, 0); SetFilePointer(hf, 0, 0, FILE_BEGIN); const int sz = 0x10000; void * mem = malloc(sz); DWORD dwCheck = 0; dwRead = 0; while (ReadFile(hf, mem, sz, &dwRead, 0) && dwRead > 0) { dwCheck = ChkSum(dwCheck, (PUSHORT)mem, dwRead/2); } if (dwRead & 1) { dwCheck += ((BYTE*)mem)[dwRead-1]; dwCheck = (dwCheck>>16) + (dwCheck&0xffff); } free(mem); CloseHandle(hf); DWORD yy = 0; if (dwCheck-1 < nth.OptionalHeader.CheckSum) { yy = (dwCheck-1) - nth.OptionalHeader.CheckSum; } else { yy = dwCheck - nth.OptionalHeader.CheckSum; } yy = (yy&0xffff) + (yy>>16); yy = (yy&0xffff) + (yy>>16); yy += dwSize; return yy; } Hao Zhuang wrote:which i think scz has posted the rest of the story anyhow Randor Randor wrote:LdrVerifyMappedImageMatchesChecksum General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/19326/An-Analysis-of-the-Windows-PE-Checksum-Algorithm?fid=431671&df=90&mpp=25&noise=3&prof=True&sort=Position&view=None&spc=Relaxed&select=2097545&fr=1
CC-MAIN-2014-52
refinedweb
3,636
63.49
Various view conversion functions. More... #include <vcl_complex.h> #include <vil/vil_image_view.h> #include <vil/vil_rgb.h> #include <vil/vil_rgba.h> Go to the source code of this file. Various view conversion functions. vil_image_view<T>::operator=() can automatically perform these conversions for you. Definition in file vil_view_as.h. Return an complex component view of a 2N-plane image. Definition at line 80 of file vil_view_as.h. Return a 3-plane view of an RGB image, or a 4-plane view of an RGBA, or a 2-plane view of a complex image. Class T must be a compound pixel type. Definition at line 26 of file vil_view_as.h. Return an RGB component view of a 3-plane image. Definition at line 47 of file vil_view_as.h. Return an RGBA component view of a 4-plane image. Definition at line 63 of file vil_view_as.h. Return a view of the imaginary part of a complex image. O(1). Definition at line 121 of file vil_view_as.h. Base function to do the work for both vil_view_real/imag_part. O(1). Definition at line 97 of file vil_view_as.h. Return a view of the real part of a complex image. O(1). Definition at line 111 of file vil_view_as.h.
http://public.kitware.com/vxl/doc/release/core/vil/html/vil__view__as_8h.html#a5433f35aac75c10dc612fcd3243a090b
crawl-003
refinedweb
205
72.12
Connecting the View to the Model in Django Specifically, our models were set up to let us record the favorite Web sites, by URL, of users. We can record a URL in the Hyperlink model and a user in the User model and then record both the user and the user's selected hyperlink in the Favorite model (from models.py, where you define your models in a Django application). We created a Hyperlink model with one field, url: class Hyperlink(models.Model): url = models.URLField( ) The User model is built into Django, so all we had to do was import it, like this: from django.contrib.auth.models import User The Favorite model lets us store a user and a hyperlink—so, for example, if the user 'steve' listed USA Today as one of his favorite Web sites, we could record both the user and hyperlink in a Favorite object, which was defined like this in models.py: class Favorite(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User) hyperlink = models.ForeignKey(Hyperlink) We set up the models in the previous chapter and filled the models with some data using the shell. In this chapter, we'll use those models, accessing the models from the view. Does that mean that we have to create the models all over again and fill them with data a second time for the new chapter4 (as opposed to chapter3) project? Not at all. You can transfer databases between Django projects if you are careful about what you're doing, and you'll see how in this chapter. After transferring the database, we'll access that database from the view in our new application: the favorites application in the chapter4 project. After all, the best model in the world is of no use to us if we can't access the data in that model. So that's the plan in this chapter: create the chapter4 project, create the favorites application in it, transfer the database we created in the previous chapter, and then access the model's data from the new application's view (recall that in Django applications, the view is the brains of the application). Creating the Project and Application The first step is to create the chapter4 project and then create the favorites application inside that project. That's what we'll do in this task. To create the Django project and application: - To create the Django project, use django-admin.py. Open a command prompt and change to the directory that contains that application: $ cd Django-1.1\django\binAs discussed in previous chapters, you do not need to run django-admin.py from Django's bin directory. You can run this program from anywhere if you specify the path to it. - Run django-admin.py, telling it you want to start a new project named chapter4: $ python django-admin.py startproject chapter4The django-admin.py program creates a new directory named chapter4 under the current directory. - Change to the chapter4 directory: $ cd chapter4 - Run the manage.py program to create the new application named first like this: $ python manage.py startapp favorites - Now you have to tell Django about your new application, favorites. Open settings.py in the chapter4 project's directory and find the INSTALLED_APPS section (Listing 4.1). Listing 4.1. The settings.py file. INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', ) - Add a line to tell Django about the chapter4.favorites application, shown in Listing 4.2. Listing 4.2. The edited settings.py file. INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'chapter4.favorites',) - Save the file. Now we have a new project, named chapter4, and a new application, named favorites. The next step is to transfer the database file, favoritesdb, that we created so carefully in the previous chapter.
https://www.peachpit.com/articles/article.aspx?p=1439184&amp;seqNum=9
CC-MAIN-2020-29
refinedweb
649
56.45
> Hello, as a GSoC student, I'm working on PyPI to Debian repository converter. Great! I hope you’re aware of previous efforts like stdeb (unfortunately requires setuptools) and py2rpm (for rpm systems but some parts can be inspiration, like the download code). I follow debian-python so we may encounter each other there. > I wanted to compare versions of packages available in PyPI and it broke while comparing appwsgi, > wsgi-design ('default') and gar ('prototype.1') versions. I wonder why you need to compare versions from different projects. What is “it” in “it broke”? If it’s a regular distutils command, please paste the full command and log; if you meant you used the LooseVersion class in your code, then I’m afraid I will say this won’t be fixed: this is not a public class. distutils2.version however does contain a public class that implements PEP 386; even if the project is still in alpha (and I want to make a few renamings and API changes), you can still use it (and when I break your code a quick look at the CHANGES file will help you update).
https://bugs.python.org/msg161515
CC-MAIN-2019-22
refinedweb
191
65.25
Spark Rising is a build & battle FPS sandbox game. This action conquest game has you conquering worlds, plundering resources, and building fortresses, all for the purpose of taking down a mad god. The game is now live on Steam early access! Get! Prepping for the next update, the dev team is going bonkers trying to fix glitches and bugs. But sometimes you just gotta laugh at them! spark rising: funny glitches An inside look at development of a couple of simple features for Spark Rising. We're creating more YouTube vids to showcase life as an indie game developer... spark rising - dev vlogs - inside look see A continued look at our redesign efforts for our little hero, the Spark Bot! spark bot redesign - round 3 Insight into our creative process while working on Spark Rising, an action conquest game that is equal parts construction + destruction. This is a continuation... spark bot redesign - round 2 Now that Spark Rising is live on Steam Early Access, it's time to explore a redesign of the titular protagonist, the Spark Bot! reenvisioning the spark bot In the past few weeks, Spark Rising was greenlit on Steam, and the game was selected to showcase at GDC at The MIX indie event. Lots more news of what's... spark rising greenlit on steam - showcased at gdc Available for Win PC and Mac. Gaiden 2: Build Play provides early pre-alpha access to gameplay mechanics that will eventually find its way into Spark... spark rising - gaiden 2: build play. now available! Retro Rising RAMPAGE (RRR) is a fast-paced FPS arcadey homage to 8-bit NES, built entirely in the Spark Rising engine. Some of the features in this experiment... retro rising rampage - playable demo of spark rising Sharing stats about our Steam Greenlight effort, as well as new screenshots showcasing the variety of levels you can create. spark rising in top 40 on steam greenlight! plus new screenshots! 1st look at a fun side project building a retro-themed level in Spark Rising. spark rising: retro rampage! Our new forums are jam packed with all new screenshots, game dev blogs, and antics for your entertainment! all new inside scoop on spark rising With the tragedy going on in the Philippines, Wicked Loot and Hashbang Games has collaborated to give away 3 free games for anyone that donates more than... donate to the philippines, get 3 free games With Spark Rising successfully hitting its Kickstarter goal, what's next? post kickstarter plans for spark rising In our final 48 hours on Kickstarter we are doing a live stream on Twitch.tv revealing all new gameplay, behind the scenes concept art, and discussions... spark rising 48 hour live stream on twitch.tv! An all new trailer for Spark Rising showcasing the back story for the Spark Bot, and all new battle footage! spark rising trailer Like many of you, we’re big Minecraft fans here at Wicked Loot. Which got me thinking: Could we make it wicked easy to take your Minecraft creations... import your minecraft creations into spark rising For Spark Rising, exo-suits are more than fancy gear. It's destruction incarnate. You don exo-suits to gain unique class-based abilities to take down... spark rising - the awesome power of exo-suits Our big announcement for the week: All +$10 Kickstarter backers will now get ALPHA ACCESS to Spark Rising. to all kickstarter backers: alpha access to all! Spark Rising, a Build + Battle Sandbox, which combines the building mechanics from Minecraft with the battle mechanics from Star Wars Battlefront, now... spark rising teaser trailer Spark Rising, a game many call Minecraft + Big Battles, is now live on Kickstarter! Get early alpha access to the game and also exclusive bonuses! spark rising now on kickstarter! build + battle + conquer A look inside our battle system, and what makes it stand out. Is it crowd combat? Horde mode? Big battles? Tower defense? All of the above? spark rising = minecraft + big battles! Spark Rising is a build + battle sandbox game. When it comes to battles, there are 4 key components that allow for dynamic battle scenarios - Terrain... spark rising update #3 - overview of our dynamic battle scenario We're seeking feedback on the overall visual direction for our voxel based action strategy game. Let us know what you think! spark rising prototype build v.01 now available How would we describe a game like Spark Rising? Let's talk about the games that inspired our latest creation! the inspiration for spark.
http://www.moddb.com/games/spark-rising/features
CC-MAIN-2017-34
refinedweb
753
74.39
I need to analyze a dictionary for values that include a number between two given numbers (as parameters) and return those values preceded by their key Dictionary: {")] } between_two_values(dictionary1(), 1464, 1496) {'P': [('Six', 1465, 81.0, 127.1, 'tempera', 'Netherlands')], 'C': [('Ten', 1496, 365.0, 389.0, 'tempera', 'Italy')]} def between_two_values(dictionary,start,end): for x in dictionary: if end < x < start in dictionary: return dictionary(x) You're on the right track. Here's one solution to the problem posed. I've formatted the data better for clarity. When it was condensed down I didn't immediately see that each dictionary value was wrapped in a list. Of course this is a style-oriented change, but style helps with readability. Note that I have made a few assumptions, such as that each dictionary value will be a list. For example, that your edge case of a key with no values will be represented as [] rather than None. I have also sort of extrapolated what I think the desired output is from the example you gave. Finally, you may consider using collections.defaultdict to simplify where matches are stored. Besides that, this code is nothing fancy. You certainly could condense it down more, or use classes for semantics. Speaking of semantics, I recommend that you use better variable names than I did: "data", "record", and "value" are pretty generic, but I feel they helped explain the solution without me having insight as to what this data represents. Data data = { '), ], } Code def between_two_values(dictionary, start, end): matches = {} for key, record_list in dictionary.items(): for record in record_list: value = record[1] if start < value < end: if key in matches: matches[key].append(record) else: matches[key] = [record] return matches result = between_two_values(data, 1464, 1496) print(result) Output {'P': [('Six', 1465, 81.0, 127.1, 'tempera', 'Netherlands')]}
https://codedump.io/share/powPCRuxF7Hj/1/searching-for-keys-in-dictionary-that-have-a-value-between-two-numbers
CC-MAIN-2018-22
refinedweb
304
56.66
What I've Learned Validating with Joi I’ll be honest, despite all of my experience as a front-end developer I haven’t had a lot of projects that dealt heavily with forms and data. Form validation was just something I never really had to work with much. My most recent project, however, is entirely form- and data-driven and I needed a way to easily handle front-end validation. For this, I turned to Joi. Joi is a validation library that allows you to build schemas to validate JavaScript objects. And what that generally means to me is Joi provides methods to easily validate common data types, such as e-mail addresses and phone numbers. But I’ve also learned that it allows you to easily validate less common data and complex data structures. And it was here, in Joi’s simplification of complex validation, where I found the urge to share what I’ve learned. Setting Up For this project, which consisted of React, Redux, and TypeScript, the validation needed to occur on the front end in the browser. Because of this I leveraged both Joi and Joi-Browser. yarn add joi --dev && yarn add joi-browser --dev With the libraries installed Joi can be imported into your validation file and the writing of schemas can begin. import * as Joi from ‘joi-browser'; When validating with Joi, two pieces of data are needed: 1) The data object to validate 2) The Joi schema Joi.validate(data, schema, [options]); An optional third argument could be supplied to customise the validation behaviour but I won’t be covering that in this post. The Basics Validating Strings This particular project consisted of multiple forms with general information fields — the user’s name, address, e-mail, and phone number. These fields are pretty straight forward and quite fittingly so is the validation. Let’s take a look at an example of some data: const data = { name: 'Sydney Prescott', address: '1996 Woodsboro Ln', email: 'sydney.prescott@woodsborocc.edu', phone: '2135551997' }; With this general data structure, we can begin writing our Joi schema for validation. Let’s begin with the strings. const schema = Joi.object().keys({ name: Joi.string().required(), address: Joi.string().required(), email: Joi.string().email().required() }); One thing I really like about Joi is how it reads. From the schema above it is pretty clear to see what we’re expecting of each property. Additionally, by adding the required() method we can quickly organise important data while being able to double up on the required property on form fields themselves for extra security. The address field, however, required additional consideration. While living in the States I didn’t think much about additional characters outside of our alphabet. Having moved to Finland, though, made me realise that I must now account for values that have characters such as Ää and Öö. Luckily, Joi provides additional ways to support such circumstances. address: Joi .string() .trim() .regex(/^[a-z\d\s\-\.\,]*$/i) .max(100) .required() The schema above introduces a couple nice options. First, the trim() method will remove any trailing spaces from the value. The max() method is also used to limit the length of the value to 100 characters. But the primary method I’d like to draw attention to here is regex(). This method allows greater control over what values are supported — virtually extending the default string() validation and adding custom behaviour on top. If you had noticed, our data object stores the phone number as a string. Let’s see how we can leverage the regex() method in our schema for this case. phone: Joi.string().trim().regex(/^[0-9]{7,10}$/).required(); By using the regex() method here, we can validate the string to ensure its value is 7–10 characters all of which fall between 0 and 9. But you won’t always be storing phone numbers as strings. Eventually, validation for number fields will need to written and Joi makes this just as direct. Validating Numbers Let’s look at the following example data: const data = { salary: 48000, age: 30 }; Assuming we’re looking for users between the ages of 18 and 65 our schema could look like the following: const schema = Joi.object().keys({ salary: Joi.number().required(), age: Joi.number().min(18).max(65).required() }); Again, the readability of Joi is a big selling point as the use of the min() and max() methods quickly convey how we’re validating our data. However, we won’t always have such defined ranges like 18 and 65. So how can data be validated against other data values? Validate Against Data References In this particular project, which deals with applying for a loan, the user is asked to specify both their total wealth as well as their total savings and investments. Because a person’s savings is part of their total wealth, the savings field should never be greater than the totalWealth value. But since we won’t know those values until the time of validation, Joi provides the ref() method for situations exactly like this. const data = { totalWealth: 5000, savings: 10000 }; const schema = Joi.object().keys({ totalWealth: Joi.number().required(), savings: Joi.number().max(Joi.ref('totalWealth')).required() }); Inside of the max() method the value of totalWealth is referenced by using Joi’s ref() method and passing in the key of the target field. With this schema our data object would error. Conditional Validation There’s a fair chance you’ve either used or built a form with conditional fields. For example, why show the user fields concerning credit card debt if the user selected “No” to owning any credit cards? Our validation should follow the same logic — only validate certain fields when other criteria is met. const data = { hasCreditCards: true, creditCardDebt: 750, creditCardMonthlyPayment: 75 }; With the data model above and understanding our need for conditional validation, let’s look at our Joi schema. const schema = Joi.object().keys({ hasCreditCards: Joi.bool().required, creditCardDebt: Joi.number().when('hasCreditCards', { is: true, then: Joi.number().min(0).required() }), creditCardMonthlyPayment: Joi.number().when('hasCreditCards', { is: true, then: Joi.number().min(0).required() }) }); In this example, the when() method is leveraged. Again, Joi reads quite clearly — when hasCreditCards is true then validate using the following schema. But let’s say we wanted to expand our data model to include an array of credit card objects, all containing their own individual values. const data = { hasCreditCards: true, allCreditCards: [{ type: 'Visa', balance: 250, payment: 25 }, { type: 'Discover', balance: 1200, payment: 100 }] }; In this case, we have an array with a variable number of objects that we need to validate only if the user hasCreditCards. Let’s start with what we know: const schema = Joi.object().keys({ hasCreditCards: Joi.bool().required(), allCreditCards: Joi.array().when('hasCreditCards', { is: true, then: ... } }); Again, using the when() method, we can conditionally validate the allCreditCards array. The next step is to validate the individual properties of each object within the array. then: Joi.array().items({ type: Joi.string().required(), balance: Joi.number().required(), payment: Joi.number().required() }) By using the items() method, we define the contents of the array. In this specific case, the items are an object but this method can support any combination of comma-separated Joi schemas. For example, if our array would only contain a required string and an optional number our schema could look like this: Joi.array().items(Joi.string().required(), Joi.number()) Back to our original credit card example, though. Let’s say we want to have more control over which credit card providers are supported. For example, my Discover card isn ‘t accepted anywhere in Finland (like literally, anywhere!). So how could we write our validation to include and/or exclude particular values? then: Joi.array().items({ type: Joi .string() .valid(['Visa', 'Mastercard']) .invalid('Discover') .required(), balance: Joi.number().required(), payment: Joi.number().required() }) By using the valid() and invalid() methods greater control can be applied to the validation. This can be nicely paired with enum values as well. Now, for it all together. const schema = Joi.object().keys({ hasCreditCards: Joi.bool().required(), allCreditCards: Joi.array().when('hasCreditCards', { is: true, then: Joi.array().items({ type: Joi .string() .valid(['Visa', 'Mastercard']) .invalid('Discover') .required(), balance: Joi.number().required(), payment: Joi.number().required() }) }) }); Cue the record scratch because yet again I love how quickly this can be read and understood. My hat goes off to the work done with the naming within Joi. Joi is capable of doing so much more than what I’ve covered here and luckily, their documentation (found here) is terrific. I feel this project has given me a great crash course on validation and using Joi to do some things that would otherwise be quite challenging. Well done, Joi. Really cool Article! I've just started with Joi on a React/ExpressJs app as well and your thoughts and examples have helped me a lot! Thanks for sharing, Cheers :)
https://codepen.io/Yuschick/post/what-i-ve-learned-validating-with-joi
CC-MAIN-2018-17
refinedweb
1,491
58.38
Using Bearer for Easier OAuth and API Calls For the past few days I've been playing with a new service that I'm really excited about, Bearer. At a high level, Bearer gives you a proxy to other APIs to provide monitoring, logging, incident reporting, and more. At a lower level, there's one aspect of Bearer (and again, this blog entry is on one aspect of Bearer) that really got my attention. Working with OAuth isn't terribly difficult, especially if you can use a library like Passport to simplify it a bit. I first blogged about my experiences with Passport back in 2016. Things get more interesting when you then work with APIs that require OAuth first, as you typically (or at least in my experience) have to follow up the initial OAuth flow with a call to get a "bearer token" and then call your API. Again, not terribly difficult, but not exactly fun either. It's also something you can't do 100% client-side. (Auth0 helps here, I'll talk about it a bit more at the end.) With serverless functions it's possible to have a "mostly" client-side JAMStack type site but what if you could skip that entirely? Bearer will give you the ability to login with OAuth flow and handle the process of getting bearer tokens for you. Finally, it lets you use it's JavaScript library to make calls to remote API, CORS or not, by proxying via it's network. It took me a few tries to get it working correctly, but once I did, I was incredibly impressed. As an example, I'd like to share a demo I built. Back in 2016, I create a Node.js demo that retrieved images from a Twitter account: Getting Images from a Twitter Account I built this because I follow (and have created) a number of Twitter accounts that only (or mostly) post pictures. My tool would let you specify an account, fetch the pictures, and just display them in one big wall of media. If you look at the repo for that demo, you can see a lot of code involved in the OAth flow and then handling the API calls to Twitter. Again, not terrible, but "work". I don't like work. So what was this like in Bearer? The first thing I did was sign up at Bearer of course. Then I registered a new Twitter API. This involved me making an app on Twitter's developer portal first and then providing those credentials to Bearer. Once registered, if you intend to use their API, you must go into Settings, scroll down to Security, and toggle Client-Side API Calls. Don't forget this. I did. Once enabled, it's time for the code. At a basic level, it comes down to doing the auth first, which can look like this: this.client = bearer('pk_development_e38bd15803c95f9c09e64a0da804e181299dc477dd05751651') this.client.connect("twitter") .then(data => { this.authId = data.authId; }) .catch(console.error); The resulting authId value is then used in later API calls: this.client.integration('twitter') .auth(this.authId) .get('users/show.json?screen_name=raymondcamden') .then(({ data }) => { this.settings = data; }) .catch(err => { console.log('Error: ', err) }) Note I only use the ending portion of the URL for Twitter API calls. Bearer knows how to handle it. And that's basically it. With that in mind, I rebuilt my previous demo using Vue.js. I didn't built it exactly the same as the previous one. I didn't add the "lightbox" effect for example. But I got everything done in one simple(ish) component. First - the template: <template> <v-app> <v-app-bar app dark> <v-toolbar-title>Twitter Image Search</v-toolbar-title> </v-app-bar> <v-content <p> This tool provides an "image only" view of a Twitter account. Simply enter the username of an account and you'll see the most recent pictures they've embedded into their Tweets. You can click an individual image for a close up view. </p> <div v- <v-btn @Authenticate with Twitter</v-btn> </div> <div v-else> <v-row> <v-col <v-text-field</v-text-field> </v-col> <v-col <v-btn @Get Images</v-btn> </v-col> </v-row> <div v- <p> <i>Loading...</i> </p> </div> <v-container fluid <v-row> <v-col <v-img : </v-col> </v-row> </v-container> </div> </v-content> </v-app> </template> I'm using Vuetify for the UI layout. Initially the button prompting for login is displayed, and after you've authenticated, I then show a form where you can enter a username and ask for their images. I defaulted to oneperfectshot as it's a damn cool account. Here's how it renders. Now for the JavaScript: import bearer from '@bearer/js'; const BEARER_KEY = 'pk_development_e38bd15803c95f9c09e64a0da804e181299dc477dd05751651'; export default { name: 'App', data: () => ({ authId: null, client: null, images: [], user: 'oneperfectshot', loading: false }), mounted() { this.client = bearer(BEARER_KEY); }, methods: { login() { this.client .connect("twitter") .then(data => { this.authId = data.authId; }) .catch(console.error); }, getImages() { this.images = []; this.loading = true; let account = this.user; console.log(`loading images for ${account} and my auth is ${this.authId}`); this.client .integration("twitter") .auth(this.authId) .get( `search/tweets.json?q=from%3A${account}+filter%3Amedia&count=100&tweet_mode=extended` ) .then(({ data }) => { this.loading = false; console.log(`Got ${data.statuses.length} tweets`); // in theory not needed since we asked for stuff with media let filtered = data.statuses.filter(t => { return ( t.entities && t.entities.media && t.entities.media.length > 0 ); }); console.log(`Filtered to ${filtered.length} tweets with media`); filtered.forEach(t => { t.entities.media.forEach(m => { this.images.push(m.media_url_https); }); }); }) .catch(err => { console.log("Error: ", err); }); } } }; Outside of the Vue stuff, this is mostly a repeat of what I showed before. One call to auth and one call to the API. In this case, I'm using Twitter's API to search for tweets from a user, that have media, and then filtering out to get the image URLs. Want to try it out yourself? I'm hosting it here: You can find the source code here: And that's basically it. As I said, Bearer does more. As one more small example, here are the included logs for my demo. I also like the simpler stats on the dashboard: As I said, I'm really impressed by their service and how easy it was to get going with an entirely client-side application. Earlier I mentioned Auth0. Auth0 obviously does login really simple. What it doesn't do simply is the bearer token stuff. It is definitely possible and my buddy Bobby Johnson showed me an example. I couldn't get it working, but I trust his worked and that it was my issue. But honestly, I was really surprised Auth0 didn't make this as simple as Bearer did. All in all, Bearer just feels easier to use. (I should add that while I worked at Auth0, I never worked with their main identity product. My experience there was with their serverless platform.) Anyway - I'd love to hear from anyone who may be using Bearer. Please leave me a comment below and tell me what you think. Header photo by Annie Spratt on Unsplash
https://www.raymondcamden.com/2019/12/11/using-bearer-for-easier-oauth-and-api-calls
CC-MAIN-2020-16
refinedweb
1,212
66.33
By Udeesh S B on Aug 9, 2016 5:45:33 AM Introduction much more modular. There is no System. Web namespace anymore and everything which came with it. ASP.NET Core 1.0 is a big fundamental change to the ASP.NET landscape and it is open source. It is also cross platform. Microsoft has invested a lot of money and effort into making ASP.NET Core 1.0 truly cross platform portable. This means there is a new Core CLR which is an alternative to Mono. You can develop, build and run an ASP.NET Core 1.0 application either on Mono or the Core. ASP.NET Core is a modular version of ASP.NET that combines ASP.NET MVC and the ASP.NET Web API. It runs on both the .NET Framework and .NET Core and is designed for building high-performance cloud and micro service apps; it is not intended as a replacement to ASP.NET in the .NET Framework. The changes are certain to impact the way you develop ASP.NET sites going forward. However, this new approach promises a number of important benefits: Open Source All sources for ASP.NET Core 1.0 packages can be found at their GitHub site. Microsoft and the developer community have embraced the transparency of Open Source software. ASP.NET’s GitHub site has a large number of active repositories which contain the source for the major features of ASP.NET, as well as middleware, demos, and useful tools. All projects are actively updated by both Microsoft contributors and the community at large. This approach enables a faster development cycle and continuous code improvement. Modularity NuGet packages have become the standard way to add new functionality to applications. Since Visual Studio 2010, developers have used the Package Manager Console and the NuGet Package Manager to install and configure frameworks and libraries. This has now been extended to include the core features of ASP.NET. The .NET developer has the ability to pick and choose which ASP.NET features to include in their solutions. This opt-in model allows developers to be more deliberate with regard to which libraries are included in their projects. The packages include logging, diagnostics, Kestrel (hosting server), and more. When code evolves at a rapid pace, packaged-based software helps make maintaining and updating projects easier. Unified MVC and WEB.API In previous versions of ASP.NET, MVC and WEB.API were based on different versions of the framework: System.Web.Mvc and System.Web.Http/System.Net.Http, respectively. At a minimum, the differences in the concepts, namespace organization and classes led to confusion. For example, the base class for controllers (Controller) was in a different namespace than the common result interface for controller actions (IActionResult). This has been resolved with ASP.NET CORE 1.0 MVC 6. There is now a single set of objects within a single namespace (currently Microsoft.AspNet.Mvc). This standardized approach simplifies developing both MVC and WEB.API endpoints. Dependency Injection and Middleware Dependency Injection has become a widely-accepted industry practice. It separates the concerns of type resolution from lifetime management and enables more effective unit testing. It has always been available as an add-on to ASP.NET development by using Microsoft’s own Unity library or a third party library such as Autofac or Ninject. Now, dependency injection is integrated into the framework. Third party products such as Autofac should still be available as an alternative to the build-in ASP.NET DI functionality. Developer Productivity IIS is the logical web host for all Microsoft web products. However, some developers prefer a lightweight web server like those built upon node.js. Microsoft has packaged their own lightweight web server called Kestrel with ASP.NET. This has several uses, from development to cross-platform use. In fact, Kestrel can be chosen as the development server within Visual Studio 2015. Kestrel enables the developer to run their site on OSX. If the developer is using the new editor, Visual Studio Code, they will be able to edit and debug ASP.NET CORE 1.0 solutions on OSX. Developers on any platform only have to save changes and refresh the browser – the tedious compile process has been eliminated. Cross-Platform ASP.NET Core 1.0 will run on the existing version of the .NET framework (4.6), but is designed to use the new .NET Core 1.0. When the .NET Core 1.0 is targeted, the framework code will be packaged with the deployed app. This version of the .NET framework has been ported to function on OSX and Linux. This extends the usability of .NET development beyond the Windows platform. If developers wish to work in OSX or Linux, Microsoft has developed Visual Studio Code, an editor that will allow the user to develop on any of those platforms. Conclusion ASP.NET on the .Net Core 1.0 framework enables the most flexible version of ASP.NET yet. Its modular design, updated programming model and productivity improvements are certain to make it popular with developers. It is difficult to predict whether the cross-platform capability will be popular. Overall, it is good to see Microsoft re-inventing its product with the future in mind.
https://blog.trigent.com/six-key-benefits-of-asp-net-core-1-0-which-make-it-different-better
CC-MAIN-2018-51
refinedweb
879
61.93
21 October 2010 19:48 [Source: ICIS news] TORONTO (ICIS)--Oil majors such as Shell and Chevron should mount a rival bid for Canada’s PotashCorp to edge out BHP Billiton’s $40bn (€29bn) bid, a Canadian analyst said on Thursday. “A big oil company with a big enough pocket is the only one to do a deal like this” apart from BHP, said Chris Damas, principal at equity research BCMI Research in a briefing on Canadian business television. Oil exploration and production is not all that different from potash mining, he said. In fact, there were a lot of direct links, given that sulphur from oil and gas production is used to make key phosphate fertilizers. Also, the potash business “comes with a little cartel, kind of like OPEC”, but with fewer members and better compliance, and the potash business is a lot less risky than deep-sea exploration, Damas said. “You can buy the whole company, it’s in play, and [oil] is just as essential for human life as energy,” he said. Some 20 or 30 years down the road, an investment in potash would turn out to be a very profitable for an oil major, he said. Damas, joining other analysts and commentators, also said that ?xml:namespace> Commentators said that Prime Minister Stephen Harper, who prided himself on making “pro-business” decisions, would be worried about the impact of a negative decision on foreign investors. In a related development, news media reports quoted BHP Billiton chairman Jacques Nasser as telling investors earlier on Thursday that his company would not be caught in a bidding war for PotashCorp – an indication that BHP may not raise its $130/share bid from August. (
http://www.icis.com/Articles/2010/10/21/9403489/analyst-touts-shell-oil-majors-as-rival-bidders-for.html
CC-MAIN-2015-14
refinedweb
285
60.38
Set Up a Cloud Service for Windows Azure Updated: April 13, 2011 To set up a cloud service, you must create the service model. The service model provides definition settings for the cloud service and configuration values for those settings. You cannot change the definition of a cloud service while it is running in Windows Azure. Although you can change the configuration of the service model for a running cloud service, to change the definition settings of a service model, you must upgrade the cloud service by using a VIP swap. You can use the following information to get started creating, configuring, and changing the service model for a cloud service: Windows Azure to determine how the application should run. The ServiceDefinition.csdef file specifies the settings that are used by Windows Azure to configure a cloud service. The Service Definition Schema understanding the format of an element, and you can use the following information for a better understanding of how to use these Windows Azure Connect. - LocalResources – contains the definitions for local storage resources. A local storage resource is a reserved directory in the file system of the virtual machine in which an instance of a role is running. - Imports – contains the definitions for imported modules. The previous code example shows the modules for Remote Desktop Connection and Windows Azure Connect. - Startup – contains tasks that are run when the role starts. The tasks are defined in a .cmd or executable file. Service Configuration Schema provides the allowable format for a service configuration file. The service configuration file is not packaged with the application, but is uploaded to Windows understanding the format of an element, and you can use the following information for a better understanding of how to use these elements: - Instances – configures the number of running instances for the role. To prevent your cloud service from potentially becoming unavailable during upgrades, it is recommend that you deploy more than one instance of your web-facing roles. By doing this, you are adhering to the guidelines in the Windows Azure Compute Service Level Agreement (SLA), which guarantees 99.95% external connectivity for Internet-facing roles when two or more role instances are deployed for a service. For more information about the Windows Azure Service Level Agreement, see Service Level Agreements. - ConfigurationSettings – configures the settings for the running instances for a role. The name of the Setting elements must match the setting definitions in the service definition file. The following table lists some of the settings that can be configured. - Certificates – configures the certificates that are used by the service. The previous code example shows how to define the certificate for the RemoteAccess module. The value of the thumbprint attribute must be set to the thumbprint of the certificate to use. The thumbprint for the certificate can be added to the configuration file by using a text editor, or the value can be added on the Certificates tab of the Properties page of the role in Visual Studio. The multi-web application service model in Windows Azure allows only one entry point to the web role. This means that all traffic occurs through one IP address. You can configure your web sites to share a port by configuring the host header to direct the request to the correct location. You can also configure your web sites and web applications to listen to well-known ports on the IP address. The following sample shows the configuration for a web role with a web site and web application. The web site> You can update the configuration of your cloud service while it is running in Windows, Windows Azure gracefully takes the instance offline to update the certificate and bring it back online after the change is complete. The Windows Azure Managed Library includes the Microsoft.WindowsAzure.ServiceRuntime namespace, which provides classes for interacting with the Windows Azure environment from code running in an instance of a role. The RoleEnvironment class defines the following events that are raised before and after a configuration change: - The Changing event occurs before the configuration change is applied to a specified instance of a role. This event may be cancelled, which causes Windows Azure to recycle the role. When the role is recycled, the configuration change is applied before the role is brought back online again. For more information about using the Changing event, see Use the RoleEnvironment.Changing Event. - The Changed event occurs after the configuration change is applied to a specified instance of a role. For more information about using the Changed event, see Use the RoleEnvironment.Changed Event. See Also
http://msdn.microsoft.com/en-us/library/hh124108.aspx
CC-MAIN-2013-48
refinedweb
766
52.8
Macroeconomics unit3 <?xml:namespace prefix = w 4. answer a, b, c, and d using the following information:? c. using the combined u.s. and french demand schedule, the u.s. demand schedule and the supply schedule, and the graph below, analyze the change in the market for lobsters. (hint: use the 10 question worksheet approach) explain your analysis and answer these two questions. 1. what will happen to the price at which fishermen can sell lobster? 2. what will be the final output of lobsters? d. what will happen to the price paid by u.s. consumers? what will happen to the quantity consumed by u.s.
https://www.studypool.com/questions/969/macroeconomics-unit3
CC-MAIN-2017-22
refinedweb
107
69.58
How to Use the XPathAPI in Flash - Introduction to the XPathAPI Object - Example - Search Examples - Conclusion XML has bridged the gap between technologies and added a lot of power to Flash, allowing it to be more dynamic and flexible for building large applications. XML in Flash has been a possibility since Flash 5 with ActionScript 1, and significantly improved when it became a native object in Flash Player 6 with the introduction of ActionScript 2. But along with all of this power came certain limitations that don’t exist in more complete programming languages. One huge difference was that there had been no implementation of the XPath in Flash, but this situation finally changed with the release of Flash 8. The native XPathAPI object in Flash 8 provides the capabilities to do simple searches for node names and attribute values in an XML file. This article explains how to use the XPathAPI in Flash 8 to make your XML parsing extremely easy. We’ll explore the available methods and the many different ways to search your XML files. Let’s get started with an understanding of the methods available through the XPathAPI. Introduction to the XPathAPI Object Perhaps the most interesting thing about the XPathAPI is that it has been available since Flash version, but it was undocumented and could only be accessed through the DataBindingClass by adding the component to your movie. This also happens to be the way that the help documentation in Flash 8 explains how to use the class, but you no longer have to add the DataBindingClass to your file; all you have to do is add an import statement for the XPathAPI as follows: import mx.xpath.XPathAPI; Or you could call specific methods with the full path to the object plus the method name, like so: mx.xpath.XPathAPI.method_name Because the XPath methods have been available since version 6 of Flash, the code is compatible with Flash Player 6 (6.0.79.0). This means that you can create backwardly compatible projects and still make use of the XPathAPI methods, a small set that packs quite a bit of power: - XPathAPI.getEvalString(node, path); - XPathAPI.selectNodeList(node, path); - XPathAPI.selectSingleNode(node, path); - XPathAPI.setNodeValue(node, path, nodeValue); The getEvalString method takes two parameters, a node and a path, and returns code as a string that would be required to target this node using standard XML parsing. It’s useful when you’re uncertain of the depth of a node and you want to see where it is in relationship to other nodes in an XML file. The selectNodeList and selectSingleNode methods take the same two parameters, a node and a path. The path is used to search from the node location that was passed as the first parameter. For selectNodeList, it will return all the matching nodes as an array, whereas selectSingleNode returns the first matching node on its own. These methods are very powerful and can be manipulated to search for many different elements in an XML file, as we’ll see in the next section. The setNodeValue method takes the same two parameters, a node and a path, with the addition of a nodeValue parameter that replaces the value of the node once it’s found. As you can imagine, these methods make XML parsing extremely easy and can be used to create more advanced searches, which we’ll learn about shortly.
https://www.informit.com/articles/article.aspx?p=459947&amp;seqNum=2
CC-MAIN-2021-21
refinedweb
572
56.79
Hello, I inserted two pictures into my Excel file. These images have very similar size and the same resolution. But in Excel they look very different. I tried to change size of image but it did no have any effect to Excel or I even got worst result. Image smaller than second image looks like it is bigger. How I can control size of image? Or maybe I can re-size it to be sure that it always will fit into necessary space? Regards, Sergey Roznikov. Hello, Hi,<?xml:namespace prefix = o Thank you for considering Aspose. Well, I am not very clear about your problem. Can you please provide a bit more detail or share your image files and the code snippet, so we can better understand the issue, For simple image insertion, I have taken two different images and inserted them in an excel file and they seem to work ok. Following is my sample code and attached is my resultant file. Sample Code: Workbook workbook = new Workbook(); //Get the first sheet. Worksheet sheet = workbook.Worksheets[0]; //Get an image file to the stream. FileStream stream = new FileStream("c:\\school.JPG",FileMode.Open,FileAccess.Read); //Add a new picture to the sheet int i = sheet.Pictures.Add(2, 3,6, 5, "c:\\logo.jpg"); i = sheet.Pictures.Add(7, 8, 11, 10, stream); //Save the excel file. workbook.Save("C:\\tstpictures.xls"); I used two different over loaded Picture.Add() methods and there are certain other overloads of Picture.Add() method, which you can see in the following link and use them according to your need. Thank You & Best Regards,
https://forum.aspose.com/t/image-size/83463
CC-MAIN-2022-40
refinedweb
272
69.58
Pick In this article, we are going to see how to make a Django field which will save pickle objects. We will only work with models.py and Django shell First of all, install the django-picklefield package − pip install django-picklefield In models.py − from django.db import models from picklefield.fields import PickledObjectField # Create your models here. class new_model(models.Model): args = PickledObjectField() Here, we created a model and added the pickle field. Now let's check if it works or not. On the terminal run "python manage.py shell" and type the following − from myapp.models import * obj=new_model(args=['fancy', {'objects': 'inside'}]).save() new_model.objects.all() We run the shell and create a new model instance that can store pickle objects. Any object stored in it will be converted to a pickle object. To save in models, you can write like this − from django.http import HttpResponse def my_view(request): Object=new_model(args=['fancy',{'name': 'ath'}]) Object.save() return HttpResponse("Object saved") You can add any pickle object or anything that can be pickeled in this field. In [4]: new_model.objects.all() Out[4]:<QuerySet [<new_model: new_model object (1)>]>
https://www.tutorialspoint.com/making-a-pickle-field-in-django-models
CC-MAIN-2021-43
refinedweb
193
53.78
Sample Chapter 9: Common Tasks in Python At this point, we have covered the syntax of Python, its basic data types, and many of our favorite functions in the Python library. This chapter assumes that all the basic components of the language are at least understood and presents some ways in which Python is, in addition to being elegant and "cool," just plain useful. We present a variety of tasks common to Python programmers. These tasks are grouped by categories--data structure manipulations, file manipulations, etc. Data Structure Manipulations One of Python's greatest features is that it provides the list, tuple, and dictionary built-in types. They are so flexible and easy to use that once you've grown used to them, you'll find yourself reaching for them automatically. Making Copies Inline Due to Python's reference management scheme, the statement a = bdoesn't make a copy of the object referenced by b; instead, it makes a new reference to that object. Sometimes a new copy of an object, not just a shared reference, is needed. How to do this depends on the type of the object in question. The simplest way to make copies of lists and tuples is somewhat odd. If myListis a list, then to make a copy of it, you can do: newList = myList[:] which you can read as "slice from beginning to end," since you'll remember from Chapter 2, Types and Operators, that the default index for the start of a slice is the beginning of the sequence (0), and the default index for the end of a slice is the end of sequence. Since tuples support the same slicing operation as lists, this same technique can also copy tuples. Dictionaries, on the other hand, don't support slicing. To make a copy of a dictionary myDict, you can use: newDict = {} for key in myDict.keys(): newDict[key] = myDict[key] This is such a common task that a new method was added to the dictionary object in Python 1.5, the copy()method, which performs this task. So the preceding code can be replaced with the single statement: newDict = myDict.copy() Another common dictionary operation is also now a standard dictionary feature. If you have a dictionary oneDict, and want to update it with the contents of a different dictionary otherDict, simply type oneDict.update(otherDict). This is the equivalent of: for key in otherDict.keys(): oneDict[key] = otherDict[key] If oneDictshared some keys with otherDictbefore the update()operation, the old values associated with the keys in oneDictare obliterated by the update. This may be what you want to do (it usually is, which is why this behavior was chosen and why it was called "update"). If it isn't, the right thing to do might be to complain (raise an exception), as in: or, alternatively, combine the values of the two dictionaries, with a tuple, for example: def mergeWithOverlap(oneDict, otherDict): newDict = oneDict.copy() for key in otherDict.keys(): if key in oneDict.keys(): newDict[key] = oneDict[key], otherDict[key] else: newDict[key] = otherDict[key] return newDict To illustrate the differences between the preceding three algorithms, consider the following two dictionaries: phoneBook1 = {'michael': '555-1212', 'mark': '554-1121', 'emily': '556-0091'} phoneBook2 = {'latoya': '555-1255', 'emily': '667-1234'} If phoneBook1is possibly out of date, and phoneBook2is more up to date but less complete, the right usage is probably phoneBook1.update(phoneBook2). If the two phoneBooks are supposed to have nonoverlapping sets of keys, using newBook = mergeWithoutOverlap(phoneBook1, phoneBook2)lets you know if that assumption is wrong. Finally, if one is a set of home phone numbers and the other a set of office phone numbers, chances are newBook = mergeWithOverlap(phoneBook1, phoneBook2)is what you want, as long as the subsequent code that uses newBookcan deal with the fact that newBook['emily']is the tuple ('556-0091', '667-1234'). Making Copies: The copy Module Back to making copies: the [:]and .copy()tricks will get you copies in 90% of the cases. If you are writing functions that, in true Python spirit, can deal with arguments of any type, it's sometimes necessary to make copies of X, regardless of what X is. In comes the copymodule. It provides two functions, copyand deepcopy. The first is just like the [:]sequence slice operation or the copymethod of dictionaries. The second is more subtle and has to do with deeply nested structures (hence the term deepcopy). Take the example of copying a list listOneby slicing it from beginning to end using the [:]construct. This technique makes a new list that contains references to the same objects contained in the original list. If the contents of that original list are immutable objects, such as numbers or strings, the copy is as good as a "true" copy. However, suppose that the first element in listOneis itself a dictionary (or any other mutable object). The first element of the copy of listOneis a new reference to the same dictionary. So if you then modify that dictionary, the modification is evident in both listOneand the copy of listOne. An example makes it much clearer: >>> import copy >>> listOne = [{"name": "Willie", "city": "Providence, RI"}, 1, "tomato", 3.0] >>> listTwo = listOne[:] # or listTwo=copy.copy(listOne) >>> listThree = copy.deepcopy(listOne) >>> listOne.append("kid") >>> listOne[0]["city"] = "San Francisco, CA" >>> print listOne, listTwo, listThree [{'name': 'Willie', 'city': 'San Francisco, CA'}, 1, 'tomato', 3.0, 'kid'] [{'name': 'Willie', 'city': 'San Francisco, CA'}, 1, 'tomato', 3.0] [{'name': 'Willie', 'city': 'Providence, RI'}, 1, 'tomato', 3.0] As you can see, modifying listOnedirectly modified only listOne. Modifying the first entry of the list referenced by listOneled to changes in listTwo, but not in listThree; that's the difference between a shallow copy ( [:]) and a deepcopy. The copymodule functions know how to copy all the built-in types that are reasonably copyable,[1] including classes and instances. Sorting and Randomizing In Chapter 2, you saw that lists have a sort method that does an in-place sort. Sometimes you want to iterate over the sorted contents of a list, without disturbing the contents of this list. Or you may want to list the sorted contents of a tuple. Because tuples are immutable, an operation such as sort, which modifies it in place, is not allowed. The only solution is to make a list copy of the elements, sort the list copy, and work with the sorted copy, as in: listCopy = list(myTuple) listCopy.sort() for item in listCopy: print item # or whatever needs doing This solution is also the way to deal with data structures that have no inherent order, such as dictionaries. One of the reasons that dictionaries are so fast is that the implementation reserves the right to change the order of the keys in the dictionary. It's really not a problem, however, given that you can iterate over the keys of a dictionary using an intermediate copy of the keys of the dictionary: keys = myDict.keys() # returns an unsorted list of # the keys in the dict keys.sort() for key in keys: # print key, value pairs print key, myDict[key] # sorted by key The sortmethod on lists uses the standard Python comparison scheme. Sometimes, however, that scheme isn't what's needed, and you need to sort according to some other procedure. For example, when sorting a list of words, case (lower versus UPPER) may not be significant. The standard comparison of text strings, however, says that all uppercase letters "come before" all lowercase letters, so ' Baby'is "less than" ' apple'but ' baby'is "greater than" ' apple'. In order to do a case-independent sort, you need to define a comparison function that takes two arguments, and returns - 1, 0, or 1depending on whether the first argument is smaller than, equal to, or greater than the second argument. So, for our case-independent sorting, you can use: >>> def caseIndependentSort(something, other): ... something, other = string.lower(something), string.lower(other) ... return cmp(something, other) ... >>> testList = ['this', 'is', 'A', 'sorted', 'List'] >>> testList.sort() >>> print testList ['A', 'List', 'is', 'sorted', 'this'] >>> testList.sort(caseIndependentSort) >>> print testList ['A', 'is', 'List', 'sorted', 'this'] We're using the built-in function cmp, which does the hard part of figuring out that 'a'comes before 'b', 'b'before 'c', etc. Our sort function simply lowercases both items and sorts the lowercased versions, which is one way of making the comparison case-independent. Also note that the lowercasing conversion is local to the comparison function, so the elements in the list aren't modified by the sort. Randomizing: The random Module What about randomizing a sequence, such as a list of lines? The easiest way to randomize a sequence is to repeatedly use the choicefunction in the randommodule, which returns a random element from the sequence it receives as an argument.[2] In order to avoid getting the same line multiple times, remember to remove the chosen item. When manipulating a list object, use the removemethod: while myList: # will stop looping when myList is empty element = random.choice(myList) myList.remove(element) print element, If you need to randomize a nonlist object, it's usually easiest to convert that object to a list and randomize the list version of the same data, rather than come up with a new strategy for each data type. This might seem a wasteful strategy, given that it involves building intermediate lists that might be quite large. In general, however, what seems large to you probably won't seem so to the computer, thanks to the reference system. Also, consider the time saved by not having to come up with a different strategy for each data type! Python is designed to save time; if that means running a slightly slower or bigger program, so be it. If you're handling enormous amounts of data, it may be worthwhile to optimize. But never optimize until the need for optimization is clear; that would be a waste of time. Making New Data Structures The last point about not reinventing the wheel is especially true when it comes to data structures. For example, Python lists and dictionaries might not be the lists and dictionaries or mappings you're used to, but you should avoid designing your own data structure if these structures will suffice. The algorithms they use have been tested under wide ranges of conditions, and they're fast and stable. Sometimes, however, the interface to these algorithms isn't convenient for a particular task. For example, computer-science textbooks often describe algorithms in terms of other data structures such as queues and stacks. To use these algorithms, it may make sense to come up with a data structure that has the same methods as these data structures (such as popand pushfor stacks or enqueue/ dequeuefor queues). However, it also makes sense to reuse the built-in list type in the implementation of a stack. In other words, you need something that acts like a stack but is based on a list. The easiest solution is to use a class wrapper around a list. For a minimal stack implementation, you can do this: class Stack: def _ _init_ _(self, data): self._data = list(data) def push(self, item): self._data.append(item) def pop(self): item = self._data[-1] del self._data[-1] return item The following is simple to write, to understand, to read, and to use: >>> thingsToDo = Stack(['write to mom', 'invite friend over', 'wash the kid']) >>> thingsToDo.push('do the dishes') >>> print thingsToDo.pop() do the dishes >>> print thingsToDo.pop() wash the kid Two standard Python naming conventions are used in the Stackclass above. The first is that class names start with an uppercase letter, to distinguish them from functions. The other is that the _dataattribute starts with an underscore. This is a half-way point between public attributes (which don't start with an underscore), private attributes (which start with two underscores; see Chapter 6, Classes), and Python-reserved identifiers (which both start and end with two underscores). What it means is that _datais an attribute of the class that shouldn't be needed by clients of the class. The class designer expects such "pseudo-private" attributes to be used only by the class methods and by the methods of any eventual subclass. Making New Lists and Dictionaries: The UserList and UserDict Modules The Stackclass presented earlier does its minimal job just fine. It assumes a fairly minimal definition of what a stack is, specifically, something that supports just two operations, a pushand a pop. Quickly, however, you find that some of the features of lists are really nice, such as the ability to iterate over all the elements using the for...in...construct. This can be done by reusing existing code. In this case, you should use the UserListclass defined in the UserListmodule as a class from which the Stackcan be derived. The library also includes a UserDictmodule that is a class wrapper around a dictionary. In general, they are there to be specialized by subclassing. In our case: # import the UserList class from the UserList module from UserList import UserList # subclass the UserList class class Stack(UserList): push = UserList.append def pop(self): item = self[-1] # uses _ _getitem_ _ del self[-1] return item This Stackis a subclass of the UserListclass. The UserListclass implements the behavior of the []brackets by defining the special _ _ getitem_ _ and _ _ delitem_ _methods among others, which is why the code in popworks. You don't need to define your own _ _ init_ _ method because UserListdefines a perfectly good default. Finally, the pushmethod is defined just by saying that it's the same as UserList's appendmethod. Now we can do list-like things as well as stack-like things: >>> thingsToDo = Stack(['write to mom', 'invite friend over', 'wash the kid']) >>> print thingsToDo # inherited from UserList ['write to mom', 'invite friend over', 'wash the kid'] >>> thingsToDo.pop() 'wash the kid' >>> thingsToDo.push('change the oil') >>> for chore in thingsToDo: # we can also iterate over the contents ... print chore # as "for .. in .." uses _ _getitem_ _ ... write to mom invite friend over change the oil NOTE: As this book was being written, Guido van Rossum announced that in Python 1.5.2 (and subsequent versions), list objects now have an additional method calledNOTE: As this book was being written, Guido van Rossum announced that in Python 1.5.2 (and subsequent versions), list objects now have an additional method called pop, which behaves just like the one here. It also has an optional argument that specifies what index to use to do the pop (with the default being the last element in the list). Manipulating Files Scripting languages were designed in part in order to help people do repetitive tasks quickly and simply. One of the common things webmasters, system administrators, and programmers need to do is to take a set of files, select a subset of those files, do some sort of manipulation on this subset, and write the output to one or a set of output files. (For example, in each file in a directory, find the last word of every other line that starts with something other than the #character, and print it along with the name of the file.) This is a task for which special-purpose tools have been developed, such as sed and awk. We find that Python does the job just fine using very simple tools. Doing Something to Each Line in a File The sysmodule is most helpful when it comes to dealing with an input file, parsing the text it contains and processing it. Among its attributes are three file objects, called sys.stdin, sys.stdout, and sys.stderr. The names come from the notion of the three streams, called standard in, standard out, and standard error, which are used to connect command line tools. Standard output ( stdout) is used by every writeand writelines. The other often-used stream is standard in ( stdin), which is also a file object, but with the input methods, such as read, readline, and readlines. For example, the following script counts all the lines in the file that is "piped in": import sys data = sys.stdin.readlines() print "Counted", len(data), "lines." On Unix, you could test it by doing something like: % cat countlines.py | python countlines.py Counted 3 lines. On Windows or DOS, you'd do: C:\> type countlines.py | python countlines.py Counted 3 lines. The readlinesfunction is useful when implementing simple filter operations. Here are a few examples of such filter operations: - Finding all lines that start with a # - import sys for line in sys.stdin.readlines(): if line[0] == '#': print line, - Note that a final comma is needed after the linestring already includes a newline character as its last character. - Extracting the fourth column of a file (where columns are defined by whitespace) - import sys, string for line in sys.stdin.readlines(): words = string.split(line) if len(words) >= 4: print words[3] - We look at the length of the words list to find if there are indeed at least four words. The last two lines could also be replaced by the try/except idiom, which is quite common in Python: - try: print words[3] except IndexError: # there aren't enough words pass - Extracting the fourth column of a file, where columns are separated by colons, and lowercasing it - import sys, string for line in sys.stdin.readlines(): words = string.split(line, ':') if len(words) >= 4: print string.lower(words[3]) - Printing the first 10 lines, the last 10 lines, and every other line - import sys, string lines = sys.stdin.readlines() sys.stdout.writelines(lines[:10]) # first ten lines sys.stdout.writelines(lines[-10:]) # last ten lines for lineIndex in range(0, len(lines), 2): # get 0, 2, 4, ... sys.stdout.write(lines[lineIndex]) # get the indexed line - Counting the number of times the word "Python" occurs in a file - import string text = open(fname).read() print string.count(text, 'Python') - Changing a list of columns into a list of rows - In this more complicated example, the task is to "transpose" a file; imagine you have a file that looks like: - Name: Willie Mark Guido Mary Rachel Ahmed Level: 5 4 3 1 6 4 Tag#: 1234 4451 5515 5124 1881 5132 - And you really want it to look like the following instead: - Name: Level: Tag#: Willie 5 1234 Mark 4 4451 ... - You could use code like the following: - import sys, string lines = sys.stdin.readlines() wordlists = [] for line in lines: words = string.split(line) wordlists.append(words) for row in range(len(wordlists[0])): for col in range(len(wordlists)): print wordlists[col][row] + '\t', print - Of course, you should really use much more defensive programming techniques to deal with the possibility that not all lines have the same number of words in them, that there may be missing data, etc. Those techniques are task-specific and are left as an exercise to the reader. Choosing chunk sizes All the preceding examples assume you can read the entire file at once (that's what the readlinescall expects). In some cases, however, that's not possible, for example when processing really huge files on computers with little memory, or when dealing with files that are constantly being appended to (such as log files). In such cases, you can use a while/ readlinecombination, where some of the file is read a bit at a time, until the end of file is reached. In dealing with files that aren't line-oriented, you must read the file a character at a time: # read character by character while 1: next = sys.stdin.read(1) # read a one-character string if not next: # or an empty string at EOF break Process character 'next' Notice that the read()method on file objects returns an empty string at end of file, which breaks out of the whileloop. Most often, however, the files you'll deal with consist of line-based data and are processed a line at a time: # read line by line while 1: next = sys.stdin.readline() # read a one-line string if not next: # or an empty string at EOF break Process line 'next' Doing Something to a Set of Files Specified on the Command Line Being able to read stdinis a great feature; it's the foundation of the Unix toolset. However, one input is not always enough: many tasks need to be performed on sets of files. This is usually done by having the Python program parse the list of arguments sent to the script as command-line options. For example, if you type: % python myScript.py input1.txt input2.txt input3.txt output.txt you might think that myScript.py wants to do something with the first three input files and write a new file, called output.py. Let's see what the beginning of such a program could look like: import sys inputfilenames, outputfilename = sys.argv[1:-1], sys.argv[-1] for inputfilename in inputfilenames: inputfile = open(inputfilename, "r") do_something_with_input(inputfile) outputfile = open(outputfilename, "w") write_results(outputfile) The second line extracts parts of the argvattribute of the sysmodule. Recall that it's a list of the words on the command line that called the current program. It starts with the name of the script. So, in the example above, the value of sys.argvis: ['myScript.py', 'input1.txt', 'input2.txt', 'input3.txt', 'output.txt']. The script assumes that the command line consists of one or more input files and one output file. So the slicing of the input file names starts at 1 (to skip the name of the script, which isn't an input to the script in most cases), and stops before the last word on the command line, which is the name of the output file. The rest of the script should be pretty easy to understand (but won't work until you provide the do_something_with_input()and write_results()functions). Note that the preceding script doesn't actually read in the data from the files, but passes the file object down to a function to do the real work. Such a function often uses the readlines()method on file objects, which returns a list of the lines in that file. A generic version of do_something_with_input()is: def do_something_with_input(inputfile): for line in inputfile.readlines() process(line) Processing Each Line of One or More Files: The fileinput Module The combination of this idiom with the preceding one regarding opening each file in the sys.argv[1:]list is so common that Python 1.5 introduced a new module that's designed to help do just this task. It's called fileinputand works like this: import fileinput for line in fileinput.input(): process(line) The fileinput.input()call parses the arguments on the command line, and if there are no arguments to the script, uses sys.stdininstead. It also provides a bunch of useful functions that let you know which file and line number you're currently manipulating: import fileinput, sys, string # take the first argument out of sys.argv and assign it to searchterm searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] for line in fileinput.input(): num_matches = string.count(line, searchterm) if num_matches: # a nonzero count means there was a match print "found '%s' %d times in %s on line %d." % (searchterm, num_matches, fileinput.filename(), fileinput.filelineno()) If this script were called mygrep.py, it could be used as follows: % python mygrep.py in *.py found 'in' 2 times in countlines.py on line 2. found 'in' 2 times in countlines.py on line 3. found 'in' 2 times in mygrep.py on line 1. found 'in' 4 times in mygrep.py on line 4. found 'in' 2 times in mygrep.py on line 5. found 'in' 2 times in mygrep.py on line 7. found 'in' 3 times in mygrep.py on line 8. found 'in' 3 times in mygrep.py on line 12. Filenames and Directories We have now covered reading existing files, and if you remember the discussion on the openbuilt-in function in Chapter 2, you know how to create new files. There are a lot of tasks, however, that need different kinds of file manipulations, such as directory and path management and removing files. Your two best friends in such cases are the osand os.pathmodules described in Chapter 8, Built-in Tools. Let's take a typical example: you have lots of files, all of which have a space in their name, and you'd like to replace the spaces with underscores. All you really need is the os.curdirattribute (which returns an operating-system specific string that corresponds to the current directory), the os.listdirfunction (which returns the list of filenames in a specified directory), and the os.renamefunction: import os, string if len(sys.argv) == 1: # if no filenames are specified, filenames = os.listdir(os.curdir) # use current dir else: # otherwise, use files specified filenames = sys.argv[1:] # on the command line for filename in filenames: if ' ' in filename: newfilename = string.replace(filename, ' ', '_') print "Renaming", filename, "to", newfilename, "..." os.rename(filename, newfilename) This program works fine, but it reveals a certain Unix-centrism. That is, if you call it with wildcards, such as: python despacify.py *.txt you find that on Unix machines, it renames all the files with names with spaces in them and that end with .txt. In a DOS-style shell, however, this won't work because the shell normally used in DOS and Windows doesn't convert from *.txt to the list of filenames; it expects the program to do it. This is called globbing, because the *is said to match a glob of characters. Matching Sets of Files: The glob Module The globmodule exports a single function, also called glob, which takes a filename pattern and returns a list of all the filenames that match that pattern (in the current working directory): import sys, glob, operator print sys.argv[1:] sys.argv = reduce(operator.add, map(glob.glob, sys.argv)) print sys.argv[1:] Running this on Unix and DOS shows that on Unix, the Python globdidn't do anything because the globbing was done by the Unix shell before Python was invoked, and on DOS, Python's globbing came up with the same answer: /usr/python/book$ python showglob.py *.py ['countlines.py', 'mygrep.py', 'retest.py', 'showglob.py', 'testglob.py'] ['countlines.py', 'mygrep.py', 'retest.py', 'showglob.py', 'testglob.py'] C:\python\book> python showglob.py *.py ['*.py'] ['countlines.py', 'mygrep.py', 'retest.py', 'showglob.py', 'testglob.py'] This script isn't trivial, though, because it uses two conceptually difficult operations; a mapfollowed by a reduce. mapwas mentioned in Chapter 4, Functions, but reduceis new to you at this point (unless you have background in LISP-type languages). mapis a function that takes a callable object (usually a function) and a sequence, calls the callable object with each element of the sequence in turn, and returns a list containing the values returned by the function. For an graphical representation of what mapdoes, see Figure 9-1. [3] mapis needed here (or something equivalent) because you don't know how many arguments were entered on the command line (e.g., it could have been *.py *.txt *.doc). So the glob.globfunction is called with each argument in turn. Each glob.globcall returns a list of filenames that match the pattern. The mapoperation then returns a lists of lists, which you need to convert to a single list--the combination of all the lists in this list of lists. That means doing list1 + list2 + ... + listN. That's exactly the kind of situation where the reducefunction comes in handy. Just as with map, reducetakes a function as its first argument and applies it to the first two elements of the sequence it receives as its second argument. It then takes the result of that call and calls the function again with that result and the next element in the sequence, etc. (See Figure 9-2 for an illustration of reduce.) But wait: you need +applied to a set of things, and +doesn't look like a function (it isn't). So a function is needed that works the same as +. Here's one: define myAdd(something, other): return something + other You would then use reduce(myAdd, map(...)). This works fine, but better yet, you can use the addfunction defined in the operatormodule, which does the same thing. The operatormodule defines functions for every syntactic operation in Python (including attribute-getting and slicing), and you should use those instead of homemade ones for two reasons. First, they've been coded, debugged, and tested by Guido, who has a pretty good track record at writing bugfree code. Second, they're actually C functions, and applying reduce(or map, or filter) to C functions results in much faster performance than applying it to Python functions. This clearly doesn't matter when all you're doing is going through a few hundred files once. If you do thousands of globs all the time, however, speed can become an issue, and now you know how to do it quickly. The filterbuilt-in function, like mapand reduce, takes a function and a sequence as arguments. It returns the subset of the elements in the sequence for which the specified function returns something that's true. To find all of the even numbers in a set, type this: >>> numbers = range(30) >>> def even(x): ... return x % 2 == 0 ... >>> print numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] >>> print filter(even, numbers) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28] Or, if you wanted to find all the words in a file that are at least 10 characters long, you could use: import string words = string.split(open('myfile.txt').read()) # get all the words def at_least_ten(word): return len(word) >= 10 longwords = filter(at_least_ten, words) For a graphical representation of what filterdoes, see Figure 9-3. One nice special feature of filteris that if one passes Noneas the first argument, it filters out all false entries in the sequence. So, to find all the nonempty lines in a file called myfile.txt, do this: lines = open('myfile.txt').readlines() lines = filter(None, lines) # remember, the empty string is false map, filter, and reduceare three powerful constructs, and they're worth knowing about; however, they are never necessary. It's fairly simple to write a Python function that does the same thing as any of them. The built-in versions are just as fast, especially when operating on built-in functions written in C, such as the functions in the operatormodule. Using Temporary Files If you've ever written a shell script and needed to use intermediary files for storing the results of some intermediate stages of processing, you probably suffered from directory litter. You started out with 20 files called log_001.txt, log_002.txt etc., and all you wanted was one summary file called log_sum.txt. In addition, you had a whole bunch of log_001.tmp, log_001.tm2, etc. files that, while they were labeled temporary, stuck around. At least that's what we've seen happen in our own lives. To put order back into your directories, use temporary files in specific directories and clean them up afterwards. To help in this temporary file-management problem, Python provides a nice little module called tempfilethat publishes two functions: mktemp()and TemporaryFile(). The former returns the name of a file not currently in use in a directory on your computer reserved for temporary files (such as /tmp on Unix or C:\TMP on Windows). The latter returns a new file object directly. For example: # read input file inputFile = open('input.txt', 'r') import tempfile # create temporary file tempFile = tempfile.TemporaryFile() # we don't even need to first_process(input = inputFile, output = tempFile) # know the filename... # create final output file outputFile = open('output.txt', 'w') second_process(input = tempFile, output = outputFile) Using tempfile.TemporaryFile()works well in cases where the intermediate steps manipulate file objects. One of its nice features is that when it's deleted, it automatically deletes the file it created on disk, thus cleaning up after itself. One important use of temporary files, however, is in conjunction with the os.systemcall, which means using a shell, hence using filenames, not file objects. For example, let's look at a program that creates form letters and mails them to a list of email addresses (on Unix only): formletter = """Dear %s,\nI'm writing to you to suggest that ...""" # etc. myDatabase = [('Bill Clinton', 'bill@whitehouse.gov.us'), ('Bill Gates', 'bill@microsoft.com'), ('Bob', 'bob@subgenius.org')] for name, email in myDatabase: specificLetter = formletter % name tempfilename = tempfile.mktemp() tempfile = open(tempfilename, 'w') tempfile.write(specificLetter) tempfile.close() os.system('/usr/bin/mail %(email)s -s "Urgent!" < %(tempfile)s' % vars()) os.remove(tempfilename) The first line in the forloop returns a customized version of the form letter based on the name it's given. That text is then written to a temporary file that's emailed to the appropriate email address using the os.systemcall (which we'll cover later in this chapter). Finally, to clean up, the temporary file is removed. If you forgot how the %bit works, go back to Chapter 2 and review it; it's worth knowing. The vars()function is a built-in function that returns a dictionary corresponding to the variables defined in the current local namespace. The keys of the dictionary are the variable names, and the values of the dictionary are the variable values. vars()comes in quite handy for exploring namespaces. It can also be called with an object as an argument (such as a module, a class, or an instance), and it will return the namespace of that object. Two other built-ins, locals()and globals(), return the local and global namespaces, respectively. In all three cases, modifying the returned dictionaries doesn't guarantee any effect on the namespace in question, so view these as read-only and you won't be surprised. You can see that the vars()call creates a dictionary that is used by the string interpolation mechanism; it's thus important that the names inside the %(...)sbits in the string match the variable names in the program. More on Scanning Text Files Suppose you've run a program that stores its output in a text file, which you need to load. The program creates a file that's composed of a series of lines that each contain a value and a key separated by whitespace: value key value key value key and so on... A key can appear on more than one line in the file, and you'd probably like to collect all the values that appear for each given key as you scan the file. Here's one way to solve this problem: #!/usr/bin/env python import sys, string entries = {} for line in open(sys.argv[1], 'r').readlines(): left, right = string.split(line) try: entries[right].append(left) # extend list except KeyError: entries[right] = [left] # first time seen for (right, lefts) in entries.items(): print "%04d '%s'\titems => %s" % (len(lefts), right, lefts) This script uses the readlinesmethod to scan the text file line by line, and calls the built-in string.splitfunction to chop the line into a list of substrings--a list containing the value and key strings separated by blanks or tabs in the file. To store all occurrences of a key, the script uses a dictionary called entries. The trystatement in the loop tries to add new values to an existing entry for a key; if no entry exists for the key, it creates one. Notice that the trycould be replaced with an ifhere: if entries.has_key(right): # is it already in the dictionary? entries[right].append(left) # add to the list of current values for key else: entries[right] = [left] # initialize key's values list Testing whether a dictionary contains a key is sometimes faster than catching an exception with the trytechnique; it depends on how many times the test is true. Here's an example of this script in action. The input filename is passed in as a command-line argument ( sys.argv[1]): % cat data.txt 1 one 2 one 3 two 7 three 8 two 10 one 14 three 19 three 20 three 30 three % python collector1.py data.txt 0003 'one' items => ['1', '2', '10'] 0005 'three' items => ['7', '14', '19', '20', '30'] 0002 'two' items => ['3', '8'] You can make this code more useful by packaging the scanner logic in a function that returns the entriesdictionary as a result and wrapping the printing loop logic at the bottom in an iftest: #!/usr/bin/env python import sys, string def collect(file): entries = {} for line in file.readlines(): left, right = string.split(line) try: entries[right].append(left) # extend list except KeyError: entries[right] = [left] # first time seen return entries if _ _name_ _ == "_ _main_ _": # when run as a script if len(sys.argv) == 1: result = collect(sys.stdin) # read from stdin stream else: result = collect(open(sys.argv[1], 'r')) # read from passed filename for (right, lefts) in result.items(): print "%04d '%s'\titems => %s" % (len(lefts), right, lefts) This way, the program becomes a bit more flexible. By using the if_ _ name_ _ == "_ _ main_ _ "trick, you can still run it as a top-level script (and get a display of the results), or import the function it defines and process the resulting dictionary explicitly: # run as a script file % collector2.py < data.txt result displayed here... # use in some other component (or interactively) from collector2 import collect result = collect(open("spam.txt", "r")) process result here... Since the collectfunction accepts an open file object, it also works on any object that provides the methods (i.e., interface) built-in files do. For example, if you want to read text from a simple string, wrap it in a class that implements the required interface and pass an instance of the class to the collectfunction: >>> from collector2 import collect >>> from StringIO import StringIO >>> >>> str = StringIO("1 one\n2 one\n3 two") >>> result = collect(str) # scans the wrapped string >>> print result # {'one':['1','2'],'two':['3']} This code uses the StringIOclass in the standard Python library to wrap the string into an instance that has all the methods file objects have; see the Library Reference for more details on StringIO. You could also write a different class or subclass from StringIOif you need to modify its behavior. Regardless, the collectfunction happily reads text from the string str, which happens to be an in-memory object, not a file. The main reason all this works is that the collectfunction was designed to avoid making assumptions about the type of object its fileparameter references. As long as the object exports a readlinesmethod that returns a list of strings, collectdoesn't care what type of object it processes. The interface is all that matters. This runtime binding[4] is an important feature of Python's object system, and allows you to easily write component programs that communicate with other components. For instance, consider a program that reads and writes satellite telemetry data using the standard file interface. By plugging in an object with the right sort of interface, you can redirect its streams to live sockets, GUI boxes, web interfaces, or databases without changing the program itself or even recompiling it. Manipulating Programs Calling Other Programs Python can be used like a shell scripting language, to steer other tools by calling them with arguments the Python program determines at runtime. So, if you have to run a specific program (call it analyzeData) with various data files and various parameters specified on the command line, you can use the os.system()call, which takes a string specifying a command to run in a subshell. Specifically: for datafname in ['data.001', 'data.002', 'data.003']: for parameter1 in range(1, 10): os.system("analyzeData -in %(datafname)s -param1 %(paramter1)d" % vars()) If analyzeDatais a Python program, you're better off doing it without invoking a subshell; simply use the importstatement up front and a function call in the loop. Not every useful program out there is a Python program, though. In the preceding example, the output of analyzeDatais most likely either a file or standard out. If it's standard out, it would be nice to be able to capture its output. The popen()function call is an almost standard way to do this. We'll show it off in a real-world task. When we were writing this book, we were asked to avoid using tabs in source-code listings and use spaces instead. Tabs can wreak havoc with typesetting, and since indentation matters in Python, incorrect typesetting has the potential to break examples. But since old habits die hard (at least one of us uses tabs to indent his own Python code), we wanted a tool to find any tabs that may have crept into our code before it was shipped off for publication. The following script, findtabs.py, does the trick: #!/usr/bin/env python # find files, search for tabs import string, os cmd = 'find . -name "*.py" -print' # find is a standard Unix tool for file in os.popen(cmd).readlines(): # run find command num = 1 name = file[:-1] # strip '\n' for line in open(name).readlines(): # scan the file pos = string.find(line, "\t") if pos >= 0: print name, num, pos # report tab found print '....', line[:-1] # [:-1] strips final \n print '....', ' '*pos + '*', '\n' num = num+1 This script uses two nested forloops. The outer loop uses os.popento run a findshell command, which returns a list of all the Python source filenames accessible in the current directory and its subdirectories. The inner loop reads each line in the current file, using string.findto look for tabs. But the real magic in this script is in the built-in tools it employs: - os.popen - Takes a shell command passed in as a string (called cmdin the example) and returns a file-like object connected to the command's standard input or output streams. Output is the default if you don't pass an explicit "r"or "w"mode argument. By reading the file-like object, you can intercept the command's output as we did here--the result of the find. It turns out that there's a module in the standard library called find.pythat provides a function that does a very similar thing to our use of popenwith the findUnix command. As an exercise, you could rewrite findtabs.py to use it instead. - string.find - Returns the index of the first occurrence of one string in another, searching from left to right. In the script, we use it to look for a tab, passed in as an (escaped) one-character string ( '\t'). When a tab is found, the script prints the matching line, along with a pointer to where the tab occurs. Notice the use of string repetition: the expression ' '*posmoves the print cursor to the right, up to the index of the first tab. Use double quotes inside a single-quoted string without backslash escapes in cmd. Here is the script at work, catching illegal tabs in the unfortunately named file happyfingers.py : C:\python\book-examples> python findtabs.py ./happyfingers.py 2 0 .... for i in range(10): .... * ./happyfingers.py 3 0 .... print "oops..." .... * ./happyfingers.py 5 5 .... print "bad style" .... * A note on portability: the findshell command used in the findtabs script is a Unix command, which may or may not be available on other platforms (it ran under Windows in the listing above because a findutility program was installed). os.popenfunctionality is available as win32pipe.popenin the win32extensions to Python for Windows.[5] If you want to write code that catches shell command output portably, use something like the following code early in your script: import sys if sys.platform == "win32": # on a Windows port try: import win32pipe popen = win32pipe.popen except ImportError: raise ImportError, "The win32pipe module could not be found" else: # else on POSIX box import os popen = os.popen ...And use popen in blissful platform ignorance The sys.platformattribute is always preset to a string that identifies the underlying platform (and hence the Python port you're using). Although the Python language isn't platform-dependent, some of its libraries may be; checking sys.platformis the standard way to handle cases where they are. Notice the nested importstatements here; as we've seen, importis just an executable statement that assigns a variable name. Internet-Related Activities The Internet is a treasure trove of information, but its exponential growth can make it hard to manage. Furthermore, most tools currently available for "surfing the Web" are not programmable. Many web-related tasks can be automated quite simply with the tools in the standard Python distribution. Downloading a Web Page Programmatically If you're interested in finding out what the weather in a given location is over a period of months, it's much easier to set up an automated program to get the information and collect it in a file than to have to remember to do it by hand. Here is a program that finds the weather in a couple of cities and states using the pages of the weather.com web site: import urllib, urlparse, string, time def get_temperature(country, state, city): url = urlparse.urljoin('', string.lower(country)+'_' + \ string.lower(state) + '_' + \ string.replace(string.lower(city), ' ', '_') + '.html') data = urllib.urlopen(url).read() start = string.index(data, 'current temp: ') + len('current temp: ') stop = string.index(data, '°v;F', start-1) temp = int(data[start:stop]) localtime = time.asctime(time.localtime(time.time())) print ("On %(localtime)s, the temperature in %(city)s, " +\ "%(state)s %(country)s is %(temp)s F.") % vars() get_temperature('FR', '', 'Paris') get_temperature('US', 'RI', 'Providence') get_temperature('US', 'CA', 'San Francisco') When run, it produces output like: ~/book:> python get_temperature.py On Wed Nov 25 16:22:25 1998, the temperature in Paris, FR is 39 F. On Wed Nov 25 16:22:30 1998, the temperature in Providence, RI US is 39 F. On Wed Nov 25 16:22:35 1998, the temperature in San Francisco, CA US is 58 F. The code in get_temperature.py suffers from one flaw, which is that the logic of the URL creation and of the temperature extraction is dependent on the specific HTML produced by the web site you use. The day the site's graphic designer decides that "current temp:" should be spelled with capitalized words, this script won't work. This is a problem with programmatic parsing of web pages that will go away only when more structural formats (such as XML) are used to produce web pages.[6] Checking the Validity of Links and Mirroring Web Sites: webchecker.py and Friends One of the big hassles of maintaining a web site is that as the number of links in the site increases, so does the chance that some of the links will no longer be valid. Good web-site maintenance therefore includes periodic checking for such stale links. The standard Python distribution includes a tool that does just this. It lives in the Tools/webchecker directory and is called webchecker.py. A companion program called websucker.py located in the same directory uses similar logic to create a local copy of a remote web site. Be careful when trying it out, because if you're not careful, it will try to download the entire Web on your machine! The same directory includes two programs called wsgui.py and webgui.py that are Tkinter-based frontends to websucker and webchecker, respectively. We encourage you to look at the source code for these programs to see how one can build sophisticated web-management systems with Python's standard toolset. In the Tools/Scripts directory, you'll find many other small to medium-sized scripts that might be of interest, such as an equivalent of websucker.py for FTP servers called ftpmirror.py. Checking Mail Electronic mail is probably the most important medium on the Internet today; it's certainly the protocol with which most information passes between individuals. Python includes several libraries for processing mail. The one you'll need to use depends on the kind of mail server you're using. Modules for interacting with POP3 servers ( poplib) and IMAP servers ( imaplib) are included. If you need to talk to a Microsoft Exchange server, you'll need some of the tools in the win32 distribution (see Appendix B, Platform-Specific Topics, for pointers to the win32 extensions web page). Here's a simple test of the poplibmodule, which is used to talk to a mail server running the POP protocol: >>> from poplib import * >>> server = POP3('mailserver.spam.org') >>> print server.getwelcome() +OK QUALCOMM Pop server derived from UCB (version 2.1.4-R3) at spam starting. >>> server.user('da') '+OK Password required for da.' >>> server.pass_('youllneverguess') '+OK da has 153 message(s) (458167 octets).' >>> header, msg, octets = server.retr(152) # let's get the latest msgs >>> import string >>> print string.join(msg[:3], '\n') # and look at the first three lines Return-Path: <jim@bigbad.com> Received: from gator.bigbad.com by mailserver.spam.org (4.1/SMI-4.1) id AA29605; Wed, 25 Nov 98 15:59:24 PST In a real application, you'd use a specialized module such as rfc822to parse the header lines, and perhaps the mimetoolsand mimifymodules to get the data out of the message body (e.g., to process attached files). Bigger Examples Compounding Your Interest Someday, most of us hope to put a little money away in a savings account (assuming those student loans ever go away). Banks hope you do too, so much so that they'll pay you for the privilege of holding onto your money. In a typical savings account, your bank pays you interest on your principal. Moreover, they keep adding the percentage they pay you back to your total, so that your balance grows a little bit each year. The upshot is that you need to project on a year-by-year basis if you want to track the growth in your savings. This program, interest.py, is an easy way to do it in Python: trace = 1 # print each year? def calc(principal, interest, years): for y in range(years): principal = principal * (1.00 + (interest / 100.0)) if trace: print y+1, '=> %.2f' % principal return principal This function just loops through the number of years you pass in, accumulating the principal (your initial deposit plus all the interest added so far) for each year. It assumes that you'll avoid the temptation to withdraw money. Now, suppose we have $65,000 to invest in a 5.5% interest yield account, and want to track how the principal will grow over 10 years. We import and call our compounding function passing in a starting principal, an interest rate, and the number of years we want to project: % python >>> from interest import calc >>> calc(65000, 5.5, 10) 1 => 68575.00 2 => 72346.63 3 => 76325.69 4 => 80523.60 5 => 84952.40 6 => 89624.78 7 => 94554.15 8 => 99754.62 9 => 105241.13 10 => 111029.39 111029.389793 and we wind up with $111,029. If we just want to see the final balance, we can set the traceglobal (module-level) variable in interestto 0 before we call the calcfunction: >>> import interest >>> interest.trace = 0 >>> calc(65000, 5.5, 10) 111029.389793 Naturally, there are many ways to calculate compound interest. For example, the variation of the interest calculator function below adds to the principal explicitly, and prints both the interest earned ( earnings) and current balance ( principal) as it steps through the years: def calc(principal, interest, years): interest = interest / 100.0 for y in range(years): earnings = principal * interest principal = principal + earnings if trace: print y+1, '(+%d)' % earnings, '=> %.2f' % principal return principal We get the same results with this version, but more information: >>> interest.trace = 1 >>> calc(65000, 5.5, 10) 1 (+3575) => 68575.00 2 (+3771) => 72346.63 3 (+3979) => 76325.69 4 (+4197) => 80523.60 5 (+4428) => 84952.40 6 (+4672) => 89624.78 7 (+4929) => 94554.15 8 (+5200) => 99754.62 9 (+5486) => 105241.13 10 (+5788) => 111029.39 111029.389793 The last comment on this script is that it may not give you exactly the same numbers as your bank. Bank programs tend to round everything off to the cent on a regular basis. Our program rounds off the numbers to the cent when printing the results (that's what the %.2fdoes; see Chapter 2 for details), but keeps the full precision afforded by the computer in its intermediate computation (as shown in the last line). An Automated Dial-Out Script One upon a time, a certain book's coauthor worked at a company without an Internet feed. The system support staff did, however, install a dial-out modem on site, so anyone with a personal Internet account and a little Unix savvy could connect to a shell account and do all their Internet business at work. Dialing out meant using the Kermit file transfer utility. One drawback with the modem setup was that people wanting to dial out had to keep trying each of 10 possible modems until one was free (dial on one; if it's busy, try another, and so on). Since modems were addressable under Unix using the filename pattern /dev/modem*, and modem locks via /var/spool/locks/LCK*modem*, a simple Python script was enough to check for free modems automatically. The following program, dokermit, uses a list of integers to keep track of which modems are locked, glob.globto do filename expansion, and os.systemto run a kermit command when a free modem has been found: #!/usr/bin/env python # find a free modem to dial out on import glob, os, string LOCKS = "/var/spool/locks/" locked = [0] * 10 for lockname in glob.glob(LOCKS + "LCK*modem*"): # find locked modems print "Found lock:", lockname locked[string.atoi(lockname[-1])] = 1 # 0..9 at end of name print 'free: ', for i in range(10): # report, dial-out if not locked[i]: print i, print for i in range(10): if not locked[i]: if raw_input("Try %d? " % i) == 'y': os.system("kermit -m hayes -l /dev/modem%d -b 19200 -S" % i) if raw_input("More? ") != 'y': break By convention, modem lock files have the modem number at the end of their names; we use this hook to build a modem device name in the Kermit command. Notice that this script keeps a list of 10 integer flags to mark which modems are free (1 means locked). The program above works only if there are 10 or fewer modems; if there are more, you'd need to use larger lists and loops, and parse the lock filename, not just look at its last character. An Interactive Rolodex While most of the preceding examples use lists as the primary data structures, dictionaries are in many ways more powerful and fun to use. Their presence as a built-in data type is part of what makes Python high level, which basically means "easy to use for complex tasks." Complementing this rich set of built-in data types is an extensive standard library. One powerful module in this library is the cmdmodule that provides a class Cmdyou can subclass to make simple command-line interpreter. The following example is fairly large, but it's really not that complicated, and illustrates well the power of dictionaries and of reuse of standard modules. The task at hand is to keep track of names and phone numbers and allow the user to manipulate this list using an interactive interface, with error checking and user-friendly features such as online help. The following example shows the kind of interaction our program allows: % python rolo.py Monty's Friends: help Documented commands (type help <topic>): ======================================== EOF add find list load save Undocumented commands: ====================== help We can get help on specific commands: Monty's Friends: help find # compare with the help_find() method Find an entry (specify a name) We can manipulate the entries of the Rolodex easily enough: Monty's Friends: add larry # we can add entries Enter Phone Number for larry: 555-1216 Monty's Friends: add # if the name is not specified... Enter Name: tom # ...the program will ask for it Enter Phone Number for tom: 555-1000 Monty's Friends: list ========================================= larry : 555-1216 tom : 555-1000 ========================================= Monty's Friends: find larry The number for larry is 555-1216. Monty's Friends: save myNames # save our work Monty's Friends: ^D # quit the program (^Z on Windows) And the nice thing is, when we restart this program, we can recover the saved data: % python rolo.py # restart Monty's Friends: list # by default, there is no one listed Monty's Friends: load myNames # it only takes this to reload the dir Monty's Friends: list ========================================= larry : 555-1216 tom : 555-1000 ========================================= Most of the interactive interpreter functionality is provided by the Cmdclass in the cmdmodule, which just needs customization to work. Specifically, you need to set the promptattribute and add some methods that start with do_and help_. The do_methods must take a single argument, and the part after the do_is the name of the command. Once you call the cmdloop()method, the Cmdclass does the rest. Read the following code, rolo.py, one method at a time and compare the methods with the previous output: #!/usr/bin/env python # An interactive rolodex import string, sys, pickle, cmd class Rolodex(cmd.Cmd): def _ _init_ _(self): cmd.Cmd._ _init_ _(self) # initialize the base class self.prompt = "Monty's Friends: " # customize the prompt self.people = {} # at first, we know nobody def help_add(self): print "Adds an entry (specify a name)" def do_add(self, name): if name == "": name = raw_input("Enter Name: ") phone = raw_input("Enter Phone Number for "+ name+": ") self.people[name] = phone # add phone number for name def help_find(self): print "Find an entry (specify a name)" def do_find(self, name): if name == "": name = raw_input("Enter Name: ") if self.people.has_key(name): print "The number for %s is %s." % (name, self.people[name]) else: print "We have no record for %s." % (name,) def help_list(self): print "Prints the contents of the directory" def do_list(self, line): names = self.people.keys() # the keys are the names if names == []: return # if there are no names, exit names.sort() # we want them in alphabetic order print '='*41 for name in names: print string.rjust(name, 20), ":", string.ljust(self.people[name], 20) print '='*41 def help_EOF(self): print "Quits the program" def do_EOF(self, line): sys.exit() def help_save(self): print "save the current state of affairs" def do_save(self, filename): if filename == "": filename = raw_input("Enter filename: ") saveFile = open(filename, 'w') pickle.dump(self.people, saveFile) def help_load(self): print "load a directory" def do_load(self, filename): if filename == "": filename = raw_input("Enter filename: ") saveFile = open(filename, 'r') self.people = pickle.load(saveFile) # note that this will override # any existing people directory if _ _name_ _ == '_ _main_ _': # this way the module can be rolo = Rolodex() # imported by other programs as well rolo.cmdloop() So, the peopleinstance variable is a simple mapping between names and phone numbers that the addand findcommands use. Commands are the methods which start with do_, and their help is given by the corresponding help_methods. Finally, the loadand savecommands use the picklemodule, which is explained in more detail in Chapter 10, Frameworks and Applications. This example demonstrates the power of Python that comes from extending existing modules. The cmdmodule takes care of the prompt, help facility, and parsing of the input. The picklemodule does all the loading and saving that can be so difficult in lesser languages. All we had to write were the parts specific to the task at hand. The generic aspect, namely an interactive interpreter, came free. Exercises This chapter is full of programs we encourage you to type in and play with. However, if you really want exercises, here are a few more challenging ones: - Redirecting stdout. Modify the mygrep.py script to output to the last file specified on the command line instead of to the console. - Writing a shell. Using the Cmdclass in the cmdmodule and the functions listed in Chapter 8 for manipulating files and directories, write a little shell that accepts the standard Unix commands (or DOS commands if you'd rather): ls( dir) for listing the current directory, cdfor changing directory, mv(or ren) for moving/renaming a file, and cp( copy) for copying a file. - Understanding map, reduce, and filter. The map, reduce, and filterfunctions are somewhat difficult to understand if it's the first time you've encountered this type of function, partly because they involve passing functions as arguments, and partly because they do a lot even with such small names. One good way to ensure you know how they work is to rewrite them; in this exercise, write three functions ( map2, reduce2, filter2), that do the same thing as map, filter, and reduce, respectively, at least as far as we've described how they work: - map2takes two arguments. The first should be a function accepting two arguments, or None. The second should be a sequence. If the first argument is a function, that function is called with each element of the sequence, and the resulting values are returned in a list. If the first argument is None, the sequence is converted to a list, and that list is returned. - reduce2takes two arguments. The first must be a function accepting two arguments, and the second must be a sequence. The first two arguments of the sequence are used as arguments to the function, and the result of that call is sent as the first argument to the function again, with the third element to the sequence as the second argument, and so on, until all elements of the sequence have been used as arguments to the function. The last returned value from the function is then the return value for the reduce2call. - filter2takes two arguments. The first can be Noneor a function accepting two arguments. The second must be a sequence. If the first argument is None, filter2returns the subset of the elements in the sequence that tests true. If the first argument is a function, filter2is called with every element in the sequence in turn, and only those elements for which the return value of the function applied to them is true are returned by filter2. 1. Some objects don't qualify as "reasonably copyable," such as modules, file objects, and sockets. Remember that file objects are different from files on disk. 2. The randommodule provides many other useful functions, such as the randomfunction, which returns a random floating-point number between 0 and 1. Check a reference source for details. 3. It turns out that mapcan do more; for example, if Noneis the first argument, mapconverts the sequence that is its second argument to a list. It can also operate on more than one sequence at a time. Check a reference source for details. 4. Runtime binding means that Python doesn't know which sort of object implements an interface until the program is running. This behavior stems from the lack of type declarations in Python and leads to the notion of polymorphism; in Python, the meaning of a object operation (such as indexing, slicing, etc.) depends on the object being operated on. 5. Two important compatibility comments: the win32pipemodule also has a popen2call, which is like the popen2call on Unix, except that it returns the read and write pipes in swapped order (see the documentation for popen2in the posixmodule for details on its interface). There is no equivalent of popenon Macs, since pipes don't exist on that operating system. 6. XML (eXtensible Markup Language) is a language for marking up structured text files that emphasizes the structure of the document, not its graphical nature. XML processing is an entirely different area of Python text processing, with much ongoing work. See Appendix A, Python Resources, for some pointers to discussion groups and software. © 2001, O'Reilly & Associates, Inc.
http://www.oreilly.com/catalog/lpython/chapter/ch09.html
crawl-001
refinedweb
10,789
63.59
Since ePO inexplicibly does not allow you to apply a tag to the results of an EEPC query I'm trying to call the same ePO query from python, dump the results to a file, and then use that same file with python to apply the tag I want. Running the query is no problem, but I'm new to python so I'm having trouble dumping it to a file.....or would it be more efficient to store it in a list or array and iterate through that to apply the tag? Efficiancy is always a matter of opinion... I personally would use both. I would store the information in an array that I can iterate through while always storing it to a file for future use and logging. If you are having a hard time with dumping the info to a file then I would just iterate through an array. You can always go back and modify your code once you figure it out. If I manually populate the list i.e. list = [1,2,3,4,5] I can iterate through it and write it out to a file no problem. My challenge is getting the results of core.executeQuery into a list or array. The best way I have managed it in Powershell is with XML. By outputting in xml I can then iterate through the tree and pull out the info that I need...even put it into an array. Otherwise it would be a string which can be more complicated to manipulate. So consider what you are having it output as String, XML, JSON...and maybe tackle it from a different perspective. Are you not able to apply a tag utilizing a server task? Either way when you utilize the McAfee python API files the results that are returned to you are in a list. Each element within the list is a DICT of the data you requested. Here is a simple example to hopefully help you: import mcafee mc = mcafee.client(address, port, username, password) target = 'EPOEvents' select = '(select EPOEvents.DetectedUTC EPOEvents.ThreatName EPOEvents.AnalyzerName EPOEvents.SourceProcessName EPOEvents.TargetFileName EPOEvents.ThreatActionTaken)' where = '( where ( and ( eq EPOEvents.AgentGUID "%s" ) ( newerThan EPOEvents.DetectedUTC 86400000 ) ) )' % (searchGUID) order = '(order(asc EPOEvents.DetectedUTC))' data = mc.core.executeQuery(target=target, select=select, where=where, order=order) for event in data: print string.ljust('Event Generated Time (UTC)', 40), string.ljust(event['EPOEvents.DetectedUTC'], 80) print string.ljust('Detecting Product', 40), string.ljust(event['EPOEvents.AnalyzerName'], 80) print string.ljust('Threat Name', 40), string.ljust(event['EPOEvents.ThreatName'], 80) print string.ljust('Process Name', 40), string.ljust(event['EPOEvents.SourceProcessName'], 80) print string.ljust('File Name', 40), string.ljust(event['EPOEvents.TargetFileName'], 80) print string.ljust('Action Taken', 40), string.ljust(event['EPOEvents.ThreatActionTaken'], 80) Now this code basically queries HBSS for events based on a Host Asset GUID and then loops the array and extracts the data.Message was edited by: mrjester on 9/23/13 9:35:45 PM CDT
https://community.mcafee.com/t5/ePolicy-Orchestrator/Python-Output-query-results-to-text-file/td-p/363444
CC-MAIN-2018-30
refinedweb
502
60.82
I'm building a timetable application using WPF. The first part of the project involves building a management application for the database. I built the database management application also in WPF. The application turned out really nice in my opinion (considering this is the first version and that I don't have much artistic sense ), and so I decided to post it here. I suppose you need a medium level knowledge of WPF in order to understand the code. You need to know some SQL (for the database), some WPF control templates (because I will not talk about the templates I'm using), and some data binding. I have an article talking about WPF control templates. If you want, you can check it out here. Before getting to the presentation, I want to tell you that the archive that is attached contains 30 pages of documentation that can help you understand everything about the application. You can read about the structure of the timetable and how to build one, about the structure of the database, and you also have a full documentation of the application presented here. The archive also contains a .sql file that you can use to set up the database. All you need to do is run it. Instead, I'm going to show you some screenshots in order to show you what the application does, and I'm also going to talk a bit about these screenshots. The image above represents the main application window. You can see here that the window is split up in two sections. The left section contains a list with all the tables in the database, while the section on the right is empty. This section will be empty only in the beginning. As soon as you select a table, the right part will be populated by a user control that will allow you to edit the respective table. You can see this in the image below: What these images don't show is that when you start the application, some animations run. The list of tables slides into view from the left, while the user control section slides into view from the right. Also, every time you select a user control, another animation runs while the control loads the data. You can see a glimpse of this in the image below: All the user controls in the application (there are 9 of them) are implemented very similarly. Because of this, I'm only going to show you two of them here. The rest look and work in the same way. The image above shows the user control used to edit the subjects table. You can add, edit, delete, and save subjects by using the three buttons at the bottom of the user control. The last user control I'm going to show you here is the group subjects user control. This control is used to bind subjects to groups. The control can be seen in the image below: As you can see, the UI is very friendly. At the top, we have the group for which we want to edit the subjects. This can be selected from a combo box. Below this, we have two lists. The list on the left shows the subjects that are linked to the current group. The list on the right shows the remaining subjects. We can add and remove subjects from the current group by using the two buttons that are located between the two lists. Like the title says, everything you can do with the mouse and the keyboard in this application you can also do hands free. You do this by using voice commands. In fact, the only manual thing you need to do (have to do) is start the application. The rest you can do with a microphone (even close the application). I'm doing this with the voice recognition API that comes with the .NET Framework. This voice recognition comes with Windows Vista. On Windows XP, you will have it only if you install Office XP with the speech recognition engine. You can select this option during installation. The speech recognition API is also a Windows accessibility feature, because it allows people with disabilities to operate applications on the PC. I added this feature because I was reading about this in a book and I thought it will be fun to implement. I hope you like this feature even though it is noticeably slower than the mouse. The most straightforward way to use speech recognition is to create an instance of the SpeechRecognizer class from the System.Speech.Recognition namespace. You can then attach an event handler to the SpeechRecognized event, which is fired whenever spoken words are successfully converted to text: SpeechRecognizer System.Speech.Recognition SpeechRecognized SpeechRecognizer recognizer = new SpeechRecognizer(); recognizer.SpeechRecognized += recognizer_SpeechReconized; You can then retrieve the text in the event handler from the SpeechRecognizedEventArgs.Result property: SpeechRecognizedEventArgs.Result private void recognizer_SpeechReconized(object sender, SpeechRecognizedEventArgs e) { MessageBox.Show("You said:" + e.Result.Text); } Another way to use speech recognition is to use a custom grammar. This is the approach I chose because I couldn't get the other one to work right. The grammar I'm using might not be the best, but it works well with the application. I'm building the grammar with the function below. private Grammar GetAppGramar() { GrammarBuilder builder = new GrammarBuilder(); builder.Append(new Choices(" ","computer")); builder.Append(new Choices(" ","select","details")); builder.Append(new Choices(" ", "save", "new", "delete", "add", "remove","remaining", "main")); builder.Append(new Choices(" ","rooms", "groups", "subjects", "professors","subject types", "room","professor","subject", "semester","number of hours","semi group", "specializations","specialization","bind subjects", "bind professors","bind rooms")); builder.Append(new Choices(" ", "name", "description", "first name", "last name", "type", "code", "list")); builder.Append(new Choices(" ", "next", "previous","first", "last","open list","close list","exit application")); return new Grammar(builder); } This grammar is then applied to the SpeechRecognizer by using the LoadGrammar() or LoadGrammarAsync() functions. This can be seen in the code below: LoadGrammar() LoadGrammarAsync() speech = new SpeechRecognizer(); speech.LoadGrammarAsync(GetAppGramar()); I think that the grammar I built works by combining one choice from the first row with one from the second and so on, in order to recognize a command. This is why every row in the grammar building function contains a space character. I use it to recognize single word commands. The rest of the interesting code is in the SpeechRecognized handler. In the following sub sections, I'm going to tell you about the commands I'm using. In order to select the items in the table list (the list on the left of the user controls), I am using the following commands: "select specializations", "select subject types", "select subjects", "select groups", "select rooms", "select professors", "bind rooms", "bind subjects", and "bind professors". When I use one of these commands, I'm setting the selected index of the list, and this in turn goes on to change the user control on the right. Some of the code that does this can be seen below: if (e.Result.Text.ToLower() == "select groups") { lstOptions.SelectedIndex = 3; } else if (e.Result.Text.ToLower() == "select rooms") { lstOptions.SelectedIndex = 5; } I'm using five voice commands in order to edit most of the tables in the database. This is easily done because I'm using commands in the corresponding user controls. The five voice commands are: "add", "new", "remove", "delete", and "save". The code that handles this for the delete and remove voice commands can be seen below. The rest of the commands are implemented the same way. else if (e.Result.Text.ToLower() == "delete") { if (currentControl != null && (currentControl is ProfsControl || currentControl is SubjectTypesControl || currentControl is RoomsControl || currentControl is SubjectsControl || currentControl is SpecializationsControl || currentControl is GroupsControl)) { Button delBtn = (Button)currentControl.FindName("btnDelete"); if(delBtn!=null) TimetableCommands.Delete.Execute(null, delBtn); } } else if (e.Result.Text.ToLower() == "remove") { if (currentControl != null && (currentControl is RoomsSubjectsControl || currentControl is ProfsSubjectsControl || currentControl is GroupsSubjectsControl)) { Button btn = (Button)currentControl.FindName("btnRemove"); if (btn != null) TimetableCommands.Remove.Execute(null, btn); } } As you can see, first of all, I'm retrieving the correct button for the current user control by using the FindName() method. After this, I'm explicitly triggering the corresponding command, passing as the second argument, the element from where the bubbling should start. Because the user control has the command bindings, the result is the same as I had pressed the button with the mouse. This feature would not have been possible had I implemented the user controls with normal event handlers. FindName() The text box selection is also easy. All you need to do is say the text of the label that is in front of the text box. A code example can be seen below. else if (e.Result.Text.ToLower() == "name") { if (currentControl != null) { TextBox txtName = (TextBox)currentControl.FindName("txtName"); if (txtName != null) txtName.Focus(); } } else if (e.Result.Text.ToLower() == "description") { if (currentControl != null) { TextBox txtDesc = (TextBox)currentControl.FindName("txtDescription"); if (txtDesc != null) txtDesc.Focus(); } } As you can see, the code first checks to see if we have an opened user control. If we do, it tries to retrieve the specified text box. If it finds the text box, it calls the Focus() method on it in order to set the focus. You can also see that this code depends heavily on the names of the text boxes. The same principle applies when selecting list boxes or combo boxes in the user controls on the right. Some commands for this might be: "number of hours", "specialization", "room list", "remaining rooms", "professor list", and "remaining professors", to name a few. Focus() The main list represents the list at the top of each user control. This can be a list box or a combo box. The selection of this main list can be done using the "select main list" voice command. The code checks the current user control, retrieves the list, and then sets the focus on that list. Some of the code that does this can be seen below. ItemsControl list = null; if(currentControl is ProfsControl) { list = (ItemsControl)currentControl.FindName("lstProfs"); } else if(currentControl is GroupsControl) { list = (ItemsControl)currentControl.FindName("lstGroups"); } In the case of combo boxes, the user might want to open the popup before navigating. In order to do this, he can use the "open list" voice command. To close the popup, he can use the "close list" voice command. The code that does this can be seen below. else if (e.Result.Text.ToLower() == "open list") { IInputElement el = FocusManager.GetFocusedElement(this); if (el is ComboBox) { ComboBox cb = el as ComboBox; cb.IsDropDownOpen = true; } } else if (e.Result.Text.ToLower() == "close list") { IInputElement el = FocusManager.GetFocusedElement(this); if (el is ComboBox) { ComboBox cb = el as ComboBox; cb.IsDropDownOpen = false; } else if (el is ComboBoxItem) { ComboBoxItem cbi = el as ComboBoxItem; Grid cbgr = FindDropDownGrid(cbi); if (cbgr!=null) { if (cbgr.TemplatedParent != null) { ComboBox cb = cbgr.TemplatedParent as ComboBox; if (cb != null) { cb.IsDropDownOpen = false; } } } } } The popup is opened by setting the IsDropDownOpen property. The interesting part of the code is in the "close list" command. When the popup is opened, the item with the focus is no longer the combo box but the current combo box item. In order to successfully use the "close list" voice command or the navigation commands (discussed in the next section), the combo box needs to have focus. In order to get a reference to the combo box, the code uses the FindDropDownGrid() function to get a grid in the control template with a certain name. After this, the code can use the TemplatedParent property of this grid to get this combo box. This can be done because this grid was created in a template. The function can be seen below: IsDropDownOpen FindDropDownGrid() TemplatedParent private Grid FindDropDownGrid(DependencyObject child) { DependencyObject p = VisualTreeHelper.GetParent(child); if (p == null) return null; if (p is Grid) { Grid gr = p as Grid; if (gr.Name.ToLower().Equals("dropdown")) return gr; return FindDropDownGrid(p); } else { return FindDropDownGrid(p); } } As you can see, the function uses the VisualTreeHelper to find a parent called "dropdown". You must keep in mind that this is heavily dependent on the combo box control template I'm using. VisualTreeHelper The last commands I'm going to talk about are the commands used to navigate the lists. I have four voice commands: "first", "next", "previous", and "last". The names are pretty self-explanatory. The navigation is done using a function called navigateMainList(). This function takes as its only parameter a string that represents the command. First, the function retrieves the focused control. This control needs to be an ItemsControl or a ComboBoxItem in case of an opened combo box. The function retrieves the view of the collection, and based on the parameter it gets, it uses one of the ICollectionView navigation methods. An example can be seen below. navigateMainList() ItemsControl ComboBoxItem ICollectionView ItemsControl itemsControl = el as ItemsControl; ICollectionView view = CollectionViewSource.GetDefaultView(itemsControl.DataContext); if (option == "first") { view.MoveCurrentToFirst(); } At the end, I call ScrollIntoView to show the element. This is done with the following code: ScrollIntoView if (itemsControl is ListBox) { ListBox lst = itemsControl as ListBox; lst.ScrollIntoView(lst.SelectedItem); } In case the selected item is a ComboBoxItem, the method does almost the same thing. The function first gets the corresponding combo box for the item using the FindGetDropDownGrid() method mentioned previously. After this, it gets the combo box view and uses the ICollectionView navigation functions. FindGetDropDownGrid() To exit the application, you can use the "exit application" voice command. This is it. Please feel free to download the application, and read the documentation to better understand what I did and how I did it. Also, feel free to post your comments and ideas about how the application can be improved (functionality, control templates, animations, etc.). Although, in my opinion, this isn't actually related to the article, I have decided to show some screenshots of the timetable client application. This application will use the database to build the actual timetables, and will also save them as XML files in order to be further edited at a later time. The application creates projects that contain one or more timetable files. In order to give you a better understanding of how the application will work, I'm going to present a common operation scenario. This scenario includes creating a timetable project and files, adding and editing entries, validating the timetable, and generating additional timetables. The image below presents the main window of the application: This is an MDI application that presents the timetable documents in multiple tabs, giving the user the possibility to edit multiple timetables very fast. In order to create a new timetable project, the user will need to select the File->New->Project option from the main menu or click the New Project toolbar button. From the New Project dialog, the user will select the Timetable template, will specify a name for the project, and will choose the project location. This can be seen in the image below. After the project has been created, the user can start adding timetable files by using the File->New->File menu option or by clicking the toolbar button. In the New File dialog, the user will select the name of the file, the specialization, and the semester. The image below shows the project after a few timetable files have been added and the documents have been opened. As you can see, from the image above, the application presents a tree view of the project that contains the project files. It also presents a list of the subjects for the selected specialization. The main area of the application is reserved for presenting the timetable documents. In order to add entries to a timetable, all the user needs to do is drag and drop items from the subjects list. If the subjects list is not visible, it can be shown from the View menu. After the user lets the entry on the timetable surface, a dialog appears asking for more information. In the Add New Entry dialog, the user can select the professor, room, and starting week type for the current entry. This can be seen in the image below: The image below shows the timetable for Automatics specialization after a few entries have been added: There are a few things you can notice here. First is that in some cases, not all the information can be displayed in the entries. If this is the case, you can use the tool tips to get more information about an entry. Another thing to notice is that the user can select entries and drag them over the surface of the timetable in order to change their position. The last thing is the validation. In order to validate a timetable, the user can press F6 or can access the command from the menu. The image below presents a timetable after validation. As you can see, the entries in error are marked with an orange color. Also, all the errors and warnings are listed in the error list. From here, the user can double click an error and be transported to the entry in question even if the file isn't currently opened. For each error, the application presents: a description of the error, the file that contains the entry, the day and period where the entry is positioned, the group and the semi group.
http://www.codeproject.com/script/Articles/View.aspx?aid=55383
CC-MAIN-2015-32
refinedweb
2,902
56.96
This is the fifth (and last) post in my series Sequence labelling in Python, find the previous one here: CRFs for sequence labelling. Get the code for this series on GitHub. What good is our system if we can not use it to predict the labels of new sentences. Before that, though, we need to make sure to set up a complete pipeline to go from having a new offer as displayed in the VuelaX site to have a fully labelled offer on our python scripts. The idea is to borrow functions from all other previous posts; these functions were replicated somewhere inside the vuelax packages and are imported to make them less messy to work with. We've got a new offer! Imagine getting a new offer that looks like this: ¡Sin pasar EE.UU! 🇪🇬¡Todo México a El Cairo, Egipto $13,677! If your spanish is not on point, I'll translate this for you: Without stops in the USA! 🇪🇬 any airport in México to Cairo, Egypt $13,677! offer_text = "¡Sin pasar EE.UU! 🇪🇬¡Todo México a El Cairo, Egipto $13,677!" Steps: Tokenise: the first step was to tokenise it, by using our index_emoji_tokenize function from vuelax.tokenisation import index_emoji_tokenize tokens, positions = index_emoji_tokenize(offer_text) print(tokens) POS Tagging: the next thing in line is to obtain the POS tags corresponding to each one of the tokens. We can do this by using the StanfordPOSTagger: from nltk.tag.stanford import StanfordPOSTagger spanish_postagger = StanfordPOSTagger('stanford-models/spanish.tagger', 'stanford-models/stanford-postagger.jar') _, pos_tags = zip(*spanish_postagger.tag(tokens)) print(pos_tags) Prepare for the CRF: This step involves adding more features and preparing the data to be consumed by the CRF package. All the required methods exist in vuelax.feature_selection from vuelax.feature_selection import featurise_token features = featurize_sentence(tokens, positions, pos_tags) print(features[0]) Sequence labelling with pycrfsuite: And the final step is to load our trained model and tag our sequence: import pycrfsuite crf_tagger = pycrfsuite.Tagger() crf_tagger.open('model/vuelax-bad.crfsuite') assigned_tags = crf_tagger.tag(features) for assigned_tag, token in zip(assigned_tags, tokens): print(f"{assigned_tag} - {token}") And the result: n - ¡ n - Sin n - pasar n - EE.UU n - ! n - ¡ o - Todo o - México s - a d - El d - Cairo d - , d - Egipto n - $ p - 13,677 n - ! By visual inspection we can confirm that the tags are correct: "Todo México" is the origin (o), "El Cairo, Egipto" is the destination and "13,677" is the price (p). And that is it. This is the end of this series of posts on how to do sequence labelling with Python. I hope you were able to follow, and if not, I hope you have some questions for me. Remember, post them here or ask me via twitter @io_exception. What else is there to do? There are many ways this project could be improved, a few that come to mind: - Improve the size/quality of the dataset by labelling more examples - Improve the way the labelling happens, using a single spreadsheet does not scale at all - Integrate everything under a single processing pipeline - "Productionify" the code, go beyond an experiment. Discussion (0)
https://dev.to/fferegrino/putting-everything-together-sequence-labelling-in-python-part-5-19ng
CC-MAIN-2021-49
refinedweb
521
55.84
Hi, is there a way to call a protected method of a class from a static method of the same class? Or to acces an instance variable of a class from a static method of the same class? Now I’m facing a problem. I use some static methods as “factory methods”, to create “prefilled” class instances. These methods can’t access the protected methods of the same class. Is this behavior intentional? Is there clean solution to this problem? If not, how can I work around this problem? This is a public class, so I don’t want to add other params to initialize. I get this error irb(main):032:0> Info.fromBytes("\010\008") NoMethodError: protected method length=' called for #<Info:0x300c3b70 @length=nil, @typeID=8> from (irb):23:infromBytes’ with this class class Info def initialize(typeID) @typeID = typeID @length = nil end attr_reader :typeID def length if @length.nil? @length = veryLongMathCalcs() end return @length end def Info.fromBytes(bytes) typeID = bytes[0, 1].unpack("c")[0] length = bytes[1, 1].unpack("c")[0] info = Info.new(typeID) info.length = length ## <<< this is the error! return info end protected attr_writer :length end
https://www.ruby-forum.com/t/protected-methods-and-class-methods/63516
CC-MAIN-2018-47
refinedweb
195
69.99
In today’s Programming Praxis exercise, our goal is to convert a decimal length value to the fractions used by carpenters. Let’s get started, shall we? Some imports: import Data.Ratio import Text.Printf To get proper rounding we first multiply by 32 and then see how many feet, inches and fractions of an inch there are. toCarpenter :: RealFrac a => a -> (Int, Int, Ratio Int) toCarpenter l = (feet, div r 32, mod r 32 % 32) where (feet, r) = divMod (round $ l * 32) (32 * 12) Formatting the text is a unfortunately a tad unwieldy due to the number of special cases. feetAndInches :: RealFrac a => a -> String feetAndInches l = case toCarpenter l of (0,0,0) -> "0 feet 0 inches" (f,i,t) -> showUnit "foot" "feet" (f % 1) ++ (if f > 0 && (i%1 + t) > 0 then " " else "") ++ showUnit "inch" "inches" (i % 1 + t) where showUnit _ _ 0 = "" showUnit s m n = printf "%s %s" (showVal n) $ if n <= 1 then s else m showVal v | d == 1 = show n | v < 1 = printf "%d/%d" n d | otherwise = printf "%d and %d/%d" (div n d) (mod n d) d where (n,d) = (numerator v, denominator v) Some tests to see if everything is working properly: main :: IO () main = do print $ feetAndInches 0 == "0 feet 0 inches" print $ feetAndInches 0.2785 == "9/32 inch" print $ feetAndInches 1.6895 == "1 and 11/16 inches" print $ feetAndInches 11.9999 == "1 foot" print $ feetAndInches 12.2785 == "1 foot 9/32 inch" print $ feetAndInches 71.9999 == "6 feet" print $ feetAndInches 72 == "6 feet" print $ feetAndInches 72.3492 == "6 feet 11/32 inch" print $ feetAndInches 72.9999 == "6 feet 1 inch" print $ feetAndInches 73 == "6 feet 1 inch" print $ feetAndInches 73.0135 == "6 feet 1 inch" print $ feetAndInches 73.0185 == "6 feet 1 and 1/32 inches" print $ feetAndInches 73.8218 == "6 feet 1 and 13/16 inches" Advertisements Tags: bonsai, carpenter, code, feet, Haskell, inches, kata, praxis, programming
https://bonsaicode.wordpress.com/2011/07/01/programming-praxis-feet-and-inches/
CC-MAIN-2017-30
refinedweb
323
62.27
- 23 Aug, 2021 1 commit This changes the TcPlugin datatype to allow type-checking plugins to report insoluble constraints while at the same time solve some other constraints. This allows better error messages, as the plugin can still simplify constraints, even when it wishes to report a contradiction. Pattern synonyms TcPluginContradiction and TcPluginOk are provided for backwards compatibility: existing type-checking plugins should continue to work without modification. - 19 Aug, 2021 4 commits The make build system apparently uses this special package.conf rather than generating it from the cabal file. Ticket: #19950 (cherry picked from commit e316a0f3) This prepares us to actually use them when the native size is 64 bits too. I more than saitisfied my curiosity finding they were gated since 47774449. There was a subtle error in the in-scope set during RULE matching, which led to #20200 (not the original report, but the reports of failures following an initial bug-fix commit). This patch fixes the problem, and simplifies the code a bit. In pariticular there was a very mysterious and ad-hoc in-scope set extension in rnMatchBndr2, which is now moved to the right place, namely in the Let case of match, where we do the floating. I don't have a small repro case, alas. - - 18 Aug, 2021 4 commits Changes checkUserTypeError to no longer look for custom type errors inside type family arguments. This means that a program such as foo :: F xyz (TypeError (Text "blah")) -> bar does not throw a type error at definition site. This means that more programs can be accepted, as the custom type error might disappear upon reducing the above type family F. This applies only to user-written type signatures, which are checked within checkValidType. Custom type errors in type family arguments continue to be reported when they occur in unsolved Wanted constraints. Fixes #20241 This was a small oversight in the original patch which leads to spurious recompilation when using `-fno-code` but not `-fwrite-interface`, which you plausibly might do when using ghci. Fixes #20216 This patch specifies and simplifies the module cycle compilation in upsweep. How things work are described in the Note [Upsweep] Note [Upsweep] ~~~~~~~~~~~~~~ Upsweep takes a 'ModuleGraph' as input, computes a build plan and then executes the plan in order to compile the project. The first step is computing the build plan from a 'ModuleGraph'. The output of this step is a `[BuildPlan]`, which is a topologically sorted plan for how to build all the modules. ``` data BuildPlan = SingleModule ModuleGraphNode -- A simple, single module all alone but *might* have an hs-boot file which isn't part of a cycle | ResolvedCycle [ModuleGraphNode] -- A resolved cycle, linearised by hs-boot files | UnresolvedCycle [ModuleGraphNode] -- An actual cycle, which wasn't resolved by hs-boot files ``` The plan is computed in two steps: Step 1: Topologically sort the module graph without hs-boot files. This returns a [SCC ModuleGraphNode] which contains cycles. Step 2: For each cycle, topologically sort the modules in the cycle *with* the relevant hs-boot files. This should result in an acyclic build plan if the hs-boot files are sufficient to resolve the cycle. The `[BuildPlan]` is then interpreted by the `interpretBuildPlan` function. * `SingleModule nodes` are compiled normally by either the upsweep_inst or upsweep_mod functions. * `ResolvedCycles` need to compiled "together" so that the information which ends up in the interface files at the end is accurate (and doesn't contain temporary information from the hs-boot files.) - During the initial compilation, a `KnotVars` is created which stores an IORef TypeEnv for each module of the loop. These IORefs are gradually updated as the loop completes and provide the required laziness to typecheck the module loop. - At the end of typechecking, all the interface files are typechecked again in the retypecheck loop. This time, the knot-tying is done by the normal laziness based tying, so the environment is run without the KnotVars. * UnresolvedCycles are indicative of a proper cycle, unresolved by hs-boot files and are reported as an error to the user. The main trickiness of `interpretBuildPlan` is deciding which version of a dependency is visible from each module. For modules which are not in a cycle, there is just one version of a module, so that is always used. For modules in a cycle, there are two versions of 'HomeModInfo'. 1. Internal to loop: The version created whilst compiling the loop by upsweep_mod. 2. External to loop: The knot-tied version created by typecheckLoop. Whilst compiling a module inside the loop, we need to use the (1). For a module which is outside of the loop which depends on something from in the loop, the (2) version is used. As the plan is interpreted, which version of a HomeModInfo is visible is updated by updating a map held in a state monad. So after a loop has finished being compiled, the visible module is the one created by typecheckLoop and the internal version is not used again. This plan also ensures the most important invariant to do with module loops: > If you depend on anything within a module loop, before you can use the dependency, the whole loop has to finish compiling. The end result of `interpretBuildPlan` is a `[MakeAction]`, which are pairs of `IO a` actions and a `MVar (Maybe a)`, somewhere to put the result of running the action. This list is topologically sorted, so can be run in order to compute the whole graph. As well as this `interpretBuildPlan` also outputs an `IO [Maybe (Maybe HomeModInfo)]` which can be queried at the end to get the result of all modules at the end, with their proper visibility. For example, if any module in a loop fails then all modules in that loop will report as failed because the visible node at the end will be the result of retypechecking those modules together. Along the way we also fix a number of other bugs in the driver: * Unify upsweep and parUpsweep. * Fix #19937 (static points, ghci and -j) * Adds lots of module loop tests due to Divam. Also related to #20030 Co-authored-by: Divam Narula <dfordivam@gmail.com> ------------------------- Metric Decrease: T10370 ------------------------- The logic didn't account for the fact that the paths could contain spaces before which led to errors such as the following from install_name_tool. Stderr ( T14304 ): Warning: -rtsopts and -with-rtsopts have no effect with -shared. Call hs_init_ghc() from your main() function to set these options. error: /nix/store/a6j5761iy238pbckxq2xrhqr2d5kra4m-cctools-binutils-darwin-949.0.1/bin/install_name_tool: for: dist/build/libHSp-0.1-ghc8.10.6.dylib (for architecture arm64) option "-add_rpath /Users/matt/ghc/bindisttest/install dir/lib/ghc-8.10.6/ghc-prim-0.6.1" would duplicate path, file already has LC_RPATH for: /Users/matt/ghc/bindisttest/install dir/lib/ghc-8.10.6/ghc-prim-0.6.1 `install_name_tool' failed in phase `Install Name Tool'. (Exit code: 1) Fixes #20212 This apparently also fixes #20026, which is a nice surprise. - 17 Aug, 2021 3 commits StgToCmm was only using literals signedness to determine whether using Int and Word range in Cmm switches. Now that we have sized literals (Int8#, Int16#, etc.), it needs to take their ranges into account. We don't want regressions like e8f7734d to regress. Co-Authored-By: Sylvain Henry <hsyl20@gmail.com> We desugar a recursive Stmt to somethign like (a,_,c) <- mfix (\(a,b,_) -> do { ... ; return (a,b,c) }) ...stuff after the rec... The knot-tied tuple must contain * All the variables that are used before they are bound in the `rec` block * All the variables that are used after the entire `rec` block In the case of GHCi, however, we don't know what variables will be used after the `rec` (#20206). For example, we might have ghci> rec { x <- e1; y <- e2 } ghci> print x ghci> print y So we have to assume that *all* the variables bound in the `rec` are used afterwards. We use `Nothing` in the argument to segmentRecStmts to signal that all the variables are used. Fixes #20206 - 15 Aug, 2021 6 commits - Greg Steuck authored This regressed in 544414ba causing configure: error: iconv is required on non-Windows platforms More details: ghc/ghc@544414ba This is the right thing to do, easy to do, and fixes a second not-in-scope crash in #20200 (see !6302) The problem occurs in the findBest test, which compares two RULES. Repro case in simplCore/should_compile/T20200a - Krzysztof Gogolewski authored As #20200 showed, there was a call to lookupIdSubst during RULE matching, where the variable being looked up wasn't in the InScopeSet. This patch fixes the problem at source, by dealing separately with nested and non-nested binders. As a result we can change the trace call in lookupIdSubst to a proper panic -- if it happens, we really want to know. We should not complain about TypeError in type T = TypeError blah This fixes #20181 The error message for T13271 changes, because that test did indeed have a type synonym with TypeError on the RHS This test exhibited inconsistent behaviour, with different CI runs having a 98% decrease in allocations. This commit addresses this problem by ensuring that we measure allocations of the whole collection of modules used in the test. ------------------------- Metric Increase: TcPlugin_RewritePerf ------------------------- We detect insoluble Givens by making getInertInsols take into account TypeError constraints, on top of insoluble equalities such as Int ~ Bool (which it already took into account). This allows pattern matches with insoluble contexts to be reported as redundant (tyOracle calls tcCheckGivens which calls getInertInsols). As a bonus, we get to remove a workaround in Data.Typeable.Internal: we can directly use a NotApplication type family, as opposed to needing to cook up an insoluble equality constraint. Fixes #11503 #14141 #16377 #20180 - 14 Aug, 2021 3 commits Since !6133 we are more consistent about producing versioned executables but we still didn't produce versioned wrappers. This patch adds the corresponding versioned wrappers to match the versioned executables in the relocatable bindist. I also fixed the ghci wrapper so that it wasn't overwritten during installation. The final bindir looks like: ``` lrwxrwxrwx 1 matt users 16 Aug 12 11:56 ghc -> ghc-9.3.20210809 -rwxr-xr-x 1 matt users 674 Aug 12 11:56 ghc-9.3.20210809 lrwxrwxrwx 1 matt users 17 Aug 12 11:56 ghci -> ghci-9.3.20210809 -rwxr-xr-x 1 matt users 708 Aug 12 11:56 ghci-9.3.20210809 lrwxrwxrwx 1 matt users 20 Aug 12 11:56 ghc-pkg -> ghc-pkg-9.3.20210809 -rwxr-xr-x 1 matt users 734 Aug 12 11:56 ghc-pkg-9.3.20210809 lrwxrwxrwx 1 matt users 14 Aug 12 11:56 haddock -> haddock-2.24.0 -rwxr-xr-x 1 matt users 682 Aug 12 11:56 haddock-2.24.0 lrwxrwxrwx 1 matt users 9 Aug 12 11:56 hp2ps -> hp2ps-0.1 -rwxr-xr-x 1 matt users 648 Aug 12 11:56 hp2ps-0.1 lrwxrwxrwx 1 matt users 8 Aug 12 11:56 hpc -> hpc-0.68 -rwxr-xr-x 1 matt users 646 Aug 12 11:56 hpc-0.68 lrwxrwxrwx 1 matt users 13 Aug 12 11:56 hsc2hs -> hsc2hs-0.68.8 -rwxr-xr-x 1 matt users 1.4K Aug 12 11:56 hsc2hs-0.68.8 lrwxrwxrwx 1 matt users 19 Aug 12 11:56 runghc -> runghc-9.3.20210809 -rwxr-xr-x 1 matt users 685 Aug 12 11:56 runghc-9.3.20210809 ``` Fixes #20225 This is necessary because the symlink needs to be created between two arbritary filepaths in the build tree, it's hard to compute how to get between them relatively. As this symlink doesn't end up in a bindist then it's fine for it to be absolute. This reverts commit d45e3cda. - 13 Aug, 2021 3 commits Type-checking plugins can now directly rewrite type-families. The TcPlugin record is given a new field, tcPluginRewrite. The plugin specifies how to rewrite certain type-families with a value of type `UniqFM TyCon TcPluginRewriter`, where: type TcPluginRewriter = RewriteEnv -- Rewriter environment -> [Ct] -- Givens -> [TcType] -- type family arguments -> TcPluginM TcPluginRewriteResult data TcPluginRewriteResult = TcPluginNoRewrite | TcPluginRewriteTo { tcPluginRewriteTo :: Reduction , tcRewriterNewWanteds :: [Ct] } When rewriting an exactly-saturated type-family application, GHC will first query type-checking plugins for possible rewritings before proceeding. Includes some changes to the TcPlugin API, e.g. removal of the EvBindsVar parameter to the TcPluginM monad. * Make mkDependencies pure * Use Sets instead of sorted lists Notable perf changes: MultiLayerModules(normal) ghc/alloc 4130851520.0 2981473072.0 -27.8% T13719(normal) ghc/alloc 4313296052.0 4151647512.0 -3.7% Metric Decrease: MultiLayerModules T13719 - Gergő Érdi authored We also add a new `ol_from_fun` field to renamed (but not yet typechecked) OverLits. This has the nice knock-on effect of making total some typechecker functions that used to be partial. Fixes #20151 - 11 Aug, 2021 3 commits - Alina Banerjee authored The inl_inline field of the InlinePragma record is modified to store pragma source text by adding a data constructor of type SourceText. This can help in tracking the actual text of pragma names. Add/modify functions, modify type instance for InlineSpec type Modify parser, lexer to handle InlineSpec constructors containing SourceText Modify functions with InlineSpec type Extract pragma source from InlineSpec for SpecSig, InlineSig types Modify cvtInline function to add SourceText to InlineSpec type Extract name for InlineSig, SpecSig from pragma, SpectInstSig from source (fixes #18138) Extract pragma name for SpecPrag pragma, SpecSig signature Add Haddock annotation for inlinePragmaName function Add Haddock annotations for using helper functions in hsSigDoc Remove redundant ppr in pragma name for SpecSig, InlineSig; update comment Rename test to T18138 for misplaced SPECIALIZE pragma testcase - Sven Tennie authored Using a hash map reduces the complexity of lookupIPE(), making it non linear. On registration each IPE list is added to a temporary IPE lists buffer, reducing registration time. The hash map is built lazily on first lookup. IPE event output to stderr is added with tests. For details, please see Note [The Info Table Provenance Entry (IPE) Map]. A performance test for IPE registration and lookup can be found here: !5724 (comment 370806) - Moritz Angermann authored - 10 Aug, 2021 4 commits Copy-paste error in 38faeea1 `diff` uses the locale to print its message. - Artyom Kuznetsov authored Parts of HsStmtContext were split into a separate data structure HsDoFlavour. Before this change HsDo used to have HsStmtContext inside, but in reality only parts of HsStmtContext were used and other cases were invariants handled with panics. Separating those parts into its own data structure helps us to get rid of those panics as well as HsDoRn type family. - David Simmons-Duffin authored - 09 Aug, 2021 8 commits `stack sdist` in the hadrian directory reported: Package check reported the following errors: To use the 'extra-doc-files' field the package needs to specify at least 'cabal-version: >= 1.18'. In order to make the packages in this repo "reinstallable", we need to associate source code with a specific packages. Having a top level `/includes` dir that mixes concerns (which packages' includes?) gets in the way of this. To start, I have moved everything to `rts/`, which is mostly correct. There are a few things however that really don't belong in the rts (like the generated constants haskell type, `CodeGen.Platform.h`). Those needed to be manually adjusted. Things of note: - No symlinking for sake of windows, so we hard-link at configure time. - `CodeGen.Platform.h` no longer as `.hs` extension (in addition to being moved to `compiler/`) so as not to confuse anyone, since it is next to Haskell files. - Blanket `-Iincludes` is gone in both build systems, include paths now more strictly respect per-package dependencies. - `deriveConstants` has been taught to not require a `--target-os` flag when generating the platform-agnostic Haskell type. Make takes advantage of this, but Hadrian has yet to. is used outside of the rts so we do this rather than just fish it out of the repo in ad-hoc way, in order to make packages in this repo more self-contained. I need to do this now or when I move these files the linter will be mad. fromIntegral is defined as: {-# NOINLINE [1] fromIntegral #-} fromIntegral :: (Integral a, Num b) => a -> b fromIntegral = fromInteger . toInteger Before this patch, we had a lot of rewrite rules for fromIntegral, to avoid passing through Integer when there is a faster way, e.g.: "fromIntegral/Int->Word" fromIntegral = \(I# x#) -> W# (int2Word# x#) "fromIntegral/Word->Int" fromIntegral = \(W# x#) -> I# (word2Int# x#) "fromIntegral/Word->Word" fromIntegral = id :: Word -> Word Since we have added sized types and primops (Word8#, Int16#, etc.) and Natural, this approach didn't really scale as there is a combinatorial explosion of types. In addition, we really want these conversions to be optimized for all these types and in every case (not only when fromIntegral is explicitly used). This patch removes all those ad-hoc fromIntegral rules. Instead we rely on inlining and built-in constant-folding rules. There are not too many native conversions between Integer/Natural and fixed size types, so we can handle them all explicitly. Foreign.C.Types was using rules to ensure that fromIntegral rules "sees" through the newtype wrappers,e.g.: {-# RULES "fromIntegral/a->CSize" fromIntegral = \x -> CSize (fromIntegral x) "fromIntegral/CSize->a" fromIntegral = \(CSize x) -> fromIntegral x #-} But they aren't necessary because coercions due to newtype deriving are pushed out of the way. So this patch removes these rules (as fromIntegral is now inlined, they won't match anymore anyway). Summary: * INLINE `fromIntegral` * Add some missing constant-folding rules * Remove every fromIntegral ad-hoc rules (fix #19907) Fix #20062 (missing fromIntegral rules for sized primitives) Performance: - T12545 wiggles (tracked by #19414) Metric Decrease: T12545 T10359 Metric Increase: T12545 - Ben Gamari authored Sized arrays cannot be used in headers that might be imported from C++. Fixes #20199. - Ben Gamari authored Ensures that Rts.h can be parsed as C++. - 08 Aug, 2021 1 commit
https://gitlab.haskell.org/sheaf/ghc/-/commits/tcplugins
CC-MAIN-2021-49
refinedweb
3,007
53.31
Given\example) Searching in Win7 is terrible. Let usu hope you fix it in win 8 in desktop style apps, and also metrp SA You said in the blog post that the functionality from Windows 7 where Start Search could replace the Run function still exists, but in my testing, this is not the case. I don't remember ever being able to do this in Windows 8. I seem to remember typing in the path for TOWN.MID in the serach box and Windows didn't display any results. Did you ship the developer preview with this functionality enabled? Also, please put a "Programs" button on the Start Screen or the Charms menu. Even though we all know by now that using the Seach charm has the duplicate effect of showing users all the apps on a system, many people don't, and it doesn't feel natural to use a "Search" function to open a program. One more thing: please answer the question about whether or not it will be possible to run Windows 8 with the Desktop as the primary UI, and with loading the Start Screen without covering everything on the desktop. The answer to this question will make or break Windows 8. In conclusion, I'm glad to see that the ability to type in file paths into the Search box will continue to work in Windows 8. This was one of Windows Vista's better features, and I would have hated to see it be removed. It takes a second to change the way you think to use the new start menu. I think most people are complaining because they are not making the connection. This short video does help make sense of it. @Win user What's wrong with searching in Windows 7? If you have a problem with Windows 7's search, you should explain what it is. Telling Microsoft that "it's terrible" doesn't make it any better. I also forgot to mention this:. @WindowsVista567 More precise, searching files is bad. Too few options, less than in XP. Also takes longer time. Some window with search parameters is required. Searching programs (in start menu) is ok. WINDOWS 8 IS BRILLANT!!!!! of course is diferent…. it's new… who would want the same thing on a new one as the older one??? is just dummm… if u people wants the older stuff… then stay with the win7… why are u here "trying" to help to make the "NEW" windows 8 if u want the Win7 stuff??? -______- dumm assess MS U'RE DOING IT GREAT! =) @WindowsVista567, you can also shut down Windows by pressing CTRL+ALT+DEL and using the shutdown button in the bottom-right corner of the screen. I'm a faithful Windows user, and I'm pretty sure that Metro is the new and correct way to approach the future, but c'mon. . . This new search thing is a MESS when desktop is related. Look at that horrible experience when you want to search for folders! Kill desktop or let it just how it is in W7. It would be nice to have "Search All" as default when the user begins typing. Then you could populate the highest rank hits by category (Documents, Control Panel, Apps, Music, etc.) Similar to Windows Vista / 7 search functionality in Start. Otherwise I feel like I'd have to constantly remember to hit Windows key + W for /just/ settings or Widnows key + F for files. If I don't go that route, I'm ending up with another mouse movement to change the search category. This stuff is looking good, but I think you folks should take a concept from the Games industry and stick built in tutorials into Windows itself, not just a simple help file or blogs. I think a lot of problems/complaints would evaporate if you did so (how often do you hear people complaining that some game changes the interface?). Looking forward to Windows 8 regardless 🙂 One thing these posts have taught me is that people are never satisfied no matter what. Good job on the search especially like the search contract and how you can search within individual apps. Again: providing more search results by separating search scenarios isn't a solution in my opinion. I was hoping for better results and more information at one glance. Instead you are throwing more results at me so I have to do the work by filtering and searching the search results list. And searching from the desktop world really is a bad experience as can be seen in this video. Jumping in and out of the Start Screen is confusing and the transitions are still not fast enough. I don't really see enough progress yet so my hope is that your team has a lot to reveal in the beta version. @The Grand User Microsoft has made good tutorials before. Remember the Windows XP Tour? As for why people don't complain when games change the interface: people don't rely on games to get their work done, or for any digital activites other than playing the game. Windows, however, is used by people for using the Internet, typing documents, creating scientific models, solving advanced math problems, editing photos, making movies and almost everything else you can think of doing on a computer. Thus, changes made to Windows impact users quite a bit. The Start Screen could be the greatest thing that ever happened to Windows or it could completely destroy the PC industry. That's why changes to the Windows UI are such a big deal. the new search option breaks the line of sight between my work and the start screen and this is annoying, also having a black windows button on the task bar is so ugly with this aero interace, god, everything abt windows 8 is pretty cool except the start screen Why not combine the Start Screen and the Desktop? @Steven and @Brian, I can't believe we're continuing down this road that the telemetry is seemingly taking us to. I'm estatic that the keyboard shortcuts have been retained and even improved. What about moving around with a mouse? Hello? At the end of a long work session, I can barely move my mouse the few mm it needs to navigate the complete start menu – without need of the keyboard – how is making me use the keyboard any better than with all previous versions of Windows? Please, take the time to listen to us: don't fix what is not broken. The start menu may need upgrading to be useful going forward – with this I can agree 100%. The start screen is (on a desktop) the opposite of ease and usability. The mouse is the most precise, effortless and natural way to navigate around a modern PC for any experienced user – take advantage of this fact and use the screen real estate wisely. Instead of simply banging our heads over and over on your inflexible start screen experience – on our desktops – try to realize that matching the best interface with the best available input tools is clearly the way forward. Keep Metro and the Desktop experiences separate, as they clearly don't mix – no matter what your telemetry shows. Thanks for the post. But I am not convinced the search experience is great compared to Win7. I think you are putting these results in APPs, Settings, Files silos. I like shortcuts win+w, win+f, but again you are expecting user to learn and remember about apps, settings and files. The cost of transaction is high. I will use the same example I used in previous post, try search for win + "sleep" in Win7 nad Win8. I have been really impressed with the search on the Samsung tablets with Windows 8. I love the fact that you start typing and it brings up the dialog.. looks well thought out. Onuora Keyboard shortcuts? Is this 1991 with WordPerfect 5.1? Where are the usability videos of how much better the user experience is with Win8 and a mouse? There aren't any because Win8 is harder to use on a real system than any other O/S available. This is not progress, match the interface to the hardware available on each different type of platform, please! Why is this obvious point being ignored? Why is the obvious point that folders and the organization they bring being ignored too? I don't want an 'app' first O/S – my files are what are important – not the tools I use to create them. Give me first-class file search, organization and data manipulation tools. Keep the dizzying effects, the glitz and the telemetry. Another issue I see here: there is no information what kind of file "121" is (the first search result for searching files for "build"). In Windows 7 there is a headline showing you that it is a video file plus the icon shows the file type and the associate program that will open the file (in this case Windows Media Player). On Windows 8 you only get a thumbnail. It could be an image, a presentation or a video. Even after hovering over it you have to know that the file extension WMV means it is a video. My mother wouldn't know this. How can you call this an improvement? While I'm not a huge fan of the start screen yet, I'm more than willing to give it a try. However, the search has a few issues – The one glaring problem is when searching for something that has no "program" matches, but *does* have "settings" matches. In this case I get a huge screen that says "0 results". I would prefer (and expect) the results screen to default to the search group actually produced results. Can we have a setting to disable the "Swoop in" animation? When I'm searching for something, I normally know just what I want and want it to start – On win 7 I hit the windows key, type a bit and hit enter. Boom, started. On win8 I hit the windows key, and there's a distracting animation while the entire screen turns green. Neat-ish the first time, but not the 960th time. Well, I found the updates to search to be far less useful than the search from Windows 7. The Windows 7 Search is primarily useful in that it added the entire contents of the control panel to the search AND because you're basically unable to visually scan the start menu any more due to the removal of the classic start menu (you're visually constrained to a scrollable corner) it is a way to gradually inspect against it. I still would like to have an efficient way to BROWSE what is currently in the menu (a real limitation of the current design). However, if we look at the new search, in the scenario of "Remove Programs" or "Windows Update", there is a clearly identified task that is narrowed down to 0 results on the search in Windows 8. Not only that, but getting ONLY the Metro version of that (with no option to launch the FULL Windows Update), you have to work your way around to the desktop, get a computer, right click, properties, navigate to Windows Update from there and launch the fully capable version. One way around that would be either letting the search be configured to launch metro version OR full version – the metro one in general is usually less capable. However this was a big step backwards in expectations to see that the search can identify NO RESULTS FOUND under apps and still show the category. Why not show all categories by default and allow filtering if we want to into types via the navigation? I think I'd prefer it if the Application results and Settings results were combined into a single (mixed) list. Often used items should move to the first place, no matter whether they're Apps or control panel items. while it is nice easy to press win key and type app name => you are covering keyboard what about just the mouse? where we click the start menu and , clicking in all programs and clicking on my application how is this achieved in win 8? it would atleast be great if there was a All Programs tab on the metro UI that would by default show all the installed programs .. withouf user pinning each application.–> really a consolation gift for the mouse users. If discoverability is such a problem for this feature, why not borrow from webOS? Include a text entry box between the "Start" and the username at the top of the start screen. The default text can include "Type to search". This would provide minimum impact way to make the feature obvious to all users. Why are ALL your screenshots (and this blog) using such tiny, tiny, TINY type? Some of us are getting older (I'm only 70, now, having been in the computer business since I was 15), and frankly, I'm tired of having to use extra tools (magnifiers, on the screen, or in my hand) just to read the @)(%*%& text that all your 25-year-old programmers can see just fine. Give us a practical (and universal) way to change global font sizes without breaking the application (eg., XP allows 96 or 120 dpi, but many apps won't work with 120 dpi, or they work, but they scramble the screen because programmers' haven't written adaptive code. Please, move the "stock" font size for Windows 8 into the common core of code, and let those of us who find 3 pt (or even 8 pt) type too damned small! @Steven, huge, fast movements (of the entire desktop) are not conducive to a productive workflow. The 'designing search for the start screen' has a long way to go. Too big (the fonts). Too little (the information presented). Too dumbed down (the expectations are for kids and old people, while not catering to them either). Too keyboard driven (great on a desktop/bad on a desktop with a mouse – bad on a touch device/bad on a touch device with no real keyboard). Too much concentration on being different (from Win7) instead of being better (the user experience should be obviously better – the rest will follow). While the dev preview is great to play around with – it is no Win7. This latest post shows that it may never be. Why are desktop users being punished? You know that MS will pay in the end. The contract design you implemented could just as easily provide the same results in the current start menu. Again, the main problem is the full screen of it. Do it less obtrusive by reusing the start menu (for example, when you offer the CHOICE of disabling the start screen) The green is ugly, I hope in the final release we can change the colours. Having used Windows from ver. 3.1, I welcome the changes happening in the new Windows 8. No one will ever be satisfied or happy with change of any kind. If you are one of them, then stay with what you have and don't move on, but don't try to change everything new for the rest of us who don't want to keep the same old thing. I have no problem with anything in this Developer Preview and can't wait for updates. I'm on a laptop and have no problem with using the mouse/keyboard to navigate through my files or apps. And if I can do it at my age anyone can. You just have to open your minds and let the change happen.. I agree with @WindowsVista567 I believe that the main problem with the new metro design (i.e. start screen and full screen metro apps) is the feeling of alienation it imposes on users. Microsoft says that Metro is a design languageparadigm, but users perceive it as a "mode" that is distinct from the rest of the windows experience. That's why you read about: "I want to boot into the desktop mode", "I don't want to leave the desktop mode", etc… That's a clear indication that there is something inherently wrong with the design. If it's absolutely necessary to bring a mobile experience into the desktop world (something than many, myself included, are not entirely convinced of), it should at least be handled in a different manner. That said, the work you've done in other areas of the os is amazing and much appreciated. Windows is a great os and if you keep innovating and adding features that make people's lives simpler and more efficient, it can become even greater. Keep at it … There wil be a GUI to use the search options ? I mean, not everybody is going to remember commands (ex filename:$<Metro* size:>1mb) If there are no app results, why not show the settings results immediately? Seems like wasted keystrokes to switch panes when Windows already knows that what you're searching for is most likely a setting. Win+W will help, but it still seems silly to present the user with a "nothing found" window while knowing there are results elsewhere. ADD THE ABILITY TO DO MATH AND DEFINE WORDS RIGHT IN THE SEARCH BAR. I'm kinda hyper rn. sorry for shouting. There is only one thing that bothers me with the whole "Start Screen" stuff. It's the disruption when you invoke it. The fact that my desktop slides away and a totally different (let's say… "very green") thing takes its place completely breaks my context. Maybe try that simple trick: when I press the Win key, darken the desktop and makes the Start Screen appear smoothly on top of it. So that it doesn't feel like I'm switching from the most important context (my desktop) to something totally different (and back), just to launch calc. I'm pretty sure it would make an important difference in how people perceive the Start Menu and it may have a better reception. That way people could more easily think of it as a "mega-start menu" rather than "a totally new Start Screen that I don't want". The enhancement it brings to usability are good, I think! Great post! The new search system is much improved over Windows 7, but could still use some improvements. One of the biggest complaints about the new Start screen (and one that I agree with) is that there is no easy way to quickly and easily access your files through the Start screen. The file seach interface could be improved to fix this. The default view for the app search when no text is typed is to show all the apps. This is great and the main idea should be extended to the file search. That is, when the deafult file search is shown (no text has been typed), instead of showing a blank space, it could show the libraries (or some other folders). Clicking on a specific folder opens that folder in the search UI, and clicking on another folder opens that one and so on. Then search could function the same way it does in Windows explorer: As you explore down through the folders, the search functions only searches the folder you are in and its subfolders. For example, if you move to the Documents library, then search will only search that library. A breadcrumb view of the folder directory should also be given to move in and out of the folders seamlessly. The allows someone to search specific folders, but also allows someone to easily find files on their system based on folder location. It improves the search functionality and gives users direct access to their files from the Start screen. I see two main problems in Windows 8 search. (1) Again, we are forced to operate in full screen mode. This is really annoying. (2) It gets even worst: not only are we obliged to search in full screen mode, but the search window disappears as soon as we switch to another window. So, if I search for a specific expression in a PDF file out of a 500 Gb hard drive, I need to pause what I am doing and wait until the end of search; otherwise, I will lose my search query. @Steven Sinofsky AConcernedWindowsUser is right. It's clear that Metro is poorly integrated into Windows and that the whole experience seems more basic, broken, and less powerful than the regular Windows experience. You and the rest of the Windows team have a tendency to talk about "Metro-style apps" and "Desktop apps," but I see it a little bit differently. In my mind, Windows 8 is firmly split down the middle into two sections: "Metro" and "Windows." Notice I didn't say "Metro" and "Desktop." I said "Metro" and "Windows." This indicates a fundamental problem with Windows 8: it's such a radical, and in some ways not as good, departure from the regular Windows experience that it doesn't feel like using a computer so much as it feels like navigating an iPhone with the mouse. This has less to do with the Start Screen and more to do with the entire Metro experience. Implemented properly, using the suggestions I have provided on other posts (do an Edit-Find for WindowsVista567 if you want to look for them), the Start Screen can be a good thing, but not in its current implementation. Fortunately, though, this blog post seems to indicate that the Search function will be ultimately unchanged from Windows 7. That's a good thing, as Search definitely should not be changed. One good idea of Windows Vista will remain in Windows 8. Now, what about Flip 3D? I really hope that the serach tool in Win 8 will have big improvements, in desktop use and in metro…. There will be a paint for desktop and one for the Metro UI? Please add in this software the possibility of make a background trasparent Also, can you add please driver for sixasis (controller PS3) via usb/bluetooth?Win 8 have to be also for gaming experience The move from Desktop-Windows to Startscreen-Tiles is too distracting. Not only it is full screen it also breaks the "line of sight" with what one is doing. It is anti-productive. Having different kinds of searches (apps, settings, files) instead of a global search is limiting. The engineering part of Windows 8 is shaping up beautifully (Task Manager, file management, boot times, etc), the shoehorning of a touch UI into a KB+M world is a disgrace. Hopefully we can bypass Startscreen-Tiles entirely using a KB+M controlled desktop. "where each app developer understands their data and users best" You guys continue to hang yourself with the what you think is accurate telemetry data (it doesn't reflect almost all business& power users who turn it off) and assumptions. You've never installed something and had 28 useless icons and ads show up on your desktop and start menu? Ever seen the garbage on the desktop of the average home user? The start screen is going to be too polluted and bloated with crapware to use without constant maintenance with today's software — and if MS wants to push an App Store model it's going to get much, much worse. You can assume developers will play nice, but what they are really going to do is manipulate every loophole they can find to "improve" their visibility to the user and sell other apps. The start screen, they way you envision it, is ripe for abuse. Yes, better searching MAY help that (and it does perform much better), but most of us don't want to have to search to run programs we run every day, and we certainly don't want to have to stop what we are doing, have our entire work environment yanked around to search for calculator or notepad. At least for me, a Win7 style taskbar will help alleviate that massive work interruption — and I can mostly never use the start screen then. I like how the tool-tips give more information about files; that is a welcome improvement. I do wonder though how I would distinguish between launching a 'desktop' version of calc and a 'Metro' version of calc. If I'm working in desktop mode I'd want the desktop version, if I'm working in Metro, I'd want the Metro version. I don't want to have to learn two different commands or have two calculator shortcuts on my start screen. This is particularly important because I eventually hope to get a tablet PC and use it as my primary PC, docking it with a keyboard and mouse when at my desk. In that case I'll have to frequently switch between the two calculator, or two of seemingly everything. Having the option for Metro programs to run in a windowed mode as Visual Studio was shown during Build to do would be a good way to have a single calculator (or other application) that can be used in a desktop mode or in a Metro mode. If the last place I was in was the desktop, launch the app in windowed mode, if it was a full-screen Metro application, launch it in Metro mode. You also mention semantic zoom again. There really needs to be information given on how that will work. It seems the same gestures that work on the screen should work on the touch pad (if available) or I should be able to use my mouse wheel for zooming the start screen. Then the start screen should zoom in around my pointer. The wheel isn't needed to scroll horizontally. Finally, I heard a rumor that one might be able to get a tablet pre-reloaded with Windows 8 beta. That would be something I'd be very interested in because right now I have no way to really test Windows 8 extensively as it is loaded on an old notebook. I'm sure many techs would purchase such a tablet and gladly submit bug reports. I'd even be OK if the beta version forced the customer improvement reporting tool on so you could get some telemetry on what is working and what isn't during the beta test. Do you think you can fix how search works? In Windows XP in Outlook I could use the build-in search to find an email and the search would search for a part of a word. With Windows Search and Vista/7 you broke that so now I can only search the beginning of words. This drives me up a wall with a tool like MyMobiler. I know it has the word 'mobile' in it, but I can never find it in my start menu because I have to search for mymobil to find it. I eventually renamed the shortcut to My Mobiler so I could find the application again. I long for the days when search actually searched correctly. To all of you that turn off the customer improvement feedback because you are afraid of sending data to Microsoft (including corporate customers) I've always said that was foolish. The more data Microsoft has about applications crashing and how we use our computers, the better computer Microsoft can make for us. Microsoft can't design for what it doesn't know about. I wanted to be counted in Microsoft's next OS, so I opted in. If you didn't want to be counted in Windows 8, then you opted out and can't complain that this isn't what you expected or what your corporate users want. The data is anonymized, send it in, staring now, and let's help Microsoft give us what we really want. Thank you guys are for posting these blogs, they are professionally done and we all appreciate your efforts. Actually I could not thank you enough for taking the time to speak to us in such a professional way and also adding the Video. I really try hard to “accept” the message but unfortunately I cannot. I am totally disappointed that your message has no value what so ever, apart from to prove that you are either totally detached from reality or you really want to replace your customer base completely from one that generates content with one that just consumes it, nothing in between. This style of working with a desktop PCs and/or laptops is what I usually laugh about when I see some of my colleagues that are stack in UNIX era, when the keyboard was still the king. (I am not saying this applies to every UNIX person out there, only those guys that refuse to use the mouse most of the time and they love to type countless lines of instructions that could easily be performed with a mouse click on the right icon. Unfortunately you made lots of variants of UNIX to seem more desirable now than ever, because they have moved on since then). I thought that I was not using my preview build correctly or something so I watched the demo and the screen view was switched N times between the full screen of the Metro UI and the desktop. You expect me or any person than still values his eyes to have to put up with a desktop that changes 100% in brightness/contrast 1000s of times a day just so I can do what? Search for applications, files, images! Believe me when I say a “professional” user does not want the Start Menu jumping on his face with every search (I asked a lot of professional IT people in my office none agreed with this concept). Then there are all the “magic” key strokes we have to memorize now, else I will end up lost in the endless sea of rectangles. So if I am to understand the whole objective right, the Windows users, even those that want to use Windows on the desktop, are going to be buying 1000s of applications very soon because…doesn’t matter why, Microsoft is saying so…and we need to solve the problem of locating them quickly because during the course of a day we may want to run 500 of those important apps. Of course your telemetry will show up favourite results for the new method, you are STEALING THE WHOLE DESKTOP! Sorry for not being able to add any more “constructive” comments, but you are really presenting us with a joke here and I am really trying hard not to laugh. Is it possible to put the search results into a Window? In my experience with the DP when you click on a file the program for that file launches. For example, typing in a commonly used photo tag brings up all of those photos (excellent). However, if I left or right mouse click on one of them I'm switched over to Windows Explorer (left clicking launches the Windows Photo Viewer with the applicable photo). How do I get back to the resultant set? Search in windows explorer was the worse "feature" ever. It can't not find what you looking for and it slow like a turtle and less options. I have to use thirth-party tool like Agent Ransack () to do the job. Please don't based your search on indexed/offline-index. It doesn't make it faster and slow everything down. @c_barth: I think that no matter what you/me or anybody says, Microsoft is always driven by marketing ideas and not telemetry. It is obvious that the telemetry data used here just to “support” their marketing decisions. They are comparing a full screen application like the Start/Search menu with the old menu and they “conclude” that it is more efficient. Of course it is, if something is 8 times bigger of course you will be able to display more information. My guess is that the marketing line here is “unify the desktop and the tablet user experience in the best way you can”. And all I can say about their efforts is that it seems they are doing a fantastic job. No, I am serious, they are trying their best and they almost seem (to the common user) that they are getting somewhere. Of course all they have done is ruin the user interface experience for both worlds and it is going to end in tears. But hey we have been here before, at least there is some stability in their approach of “new”. Win+W doesn't make sense to me as a keyboard shortcut for searching settings (e.g. why not Win+S). Can we customize shortcuts in Windows 8? It'd be nice to not have to rely on AutoHotKey. this is a joke. MS please stop justifying the tiles when people are rejecting them. Remembering windows keys just to use your tile interface more efficiently? Are you kidding me? Steven: Have you given any real thought to how you're going to handle the discoverability issue? Yes, I realize that you said that users "serendipitously" discover search, but I find that hard to believe. I doubt very many people would expect to just start typing on the desktop to launch search. Go to any major web site (Amazon, Facebook, YouTube, eBay, etc.) None of them work this way. Not one. They all have dedicated search boxes. Most likely, users are going to scan through all the live tiles until the find the Search tile. And if they can't find the Search tile, they'll give up in frustration. At the very least, Microsoft should add a Search tile to the Start screen. This will make it easy for users to figure out how to get to search. At least until users figure out they can just type at the start screen. Also, I'm a little concerned about focus on keyboard shortcuts. Of course, they're great for power users, but many consumers don't know how to copy and paste using keyboard shortcuts. The days of expecting consumers to memorize keyboard shortcuts are gone. I don't want my searches to be full-screen. I got a 1080p resolution screen for a reason. Stop shoehorning a touch screen onto desktop PCs! You're not listening to feedback at all, at least don't keep on pretending you are, insulting our intelligence in the process. Great job with the search screen, I've found it helpful on my Dell duo. One piece of feedback I have for you is to help make all these new and even old windows shortcuts easier to find. I've learned quite a few shortcuts by reading these blog posts that I had no idea existed. It would be nice if there were a way built into windows to help me learn new keyboard shortcuts and improve my productivity. Telemetry just says half of the story. Altough Telemetry is usefull to give certain facts, it only gives you what you are expecting to see, not the all picture. You say that "Our telemetry data shows that 67% of all searches in Windows 7 are used to find and launch programs. Searching for files accounts for 22% of all Windows 7 Start menu searches, and searching for Control Panel items about 9%." Well fair enough. Can you measure how people would like to use 3 different shortcuts to open diferent things? Or how much time will they loose trying to reach +f or + W? I dont really think that on your video, being on Desktop word and wanting to open just an calculator you'll have to leave the Desktop and enter Metro. How can Telemetry measure people attitude towards that? This switch back and forth is not elegant, or even useful. I think the full search is usefull when you want to open items you usually dont open. Like an app that i want to use it help me with video or that app that i dont remember my name. But for calculator the start menu is simpler, at least visually. Or you could replace the start menu for a mini-search-screen Metro. You could add and Window Key + k (mouse right click) for instance to open the win7 start menu or the mini metro green search screen. Have you measured how fast is opening the calculator or word from windows 7 vs and 8 by telemetry? And only with a mouse can you measure that? I think that people who are used live by the mouse will find not very pratical to move the mouse around an entire screen to open Word or other app. You can say well, 1 time what's the big deal. Well the entire day. Can you measure telemetrically how much people will use the mouse and how much tendinitis people will have? How much times switching between Green (whatever) to Desktop back and forth will make sight more tired? The truth about Telemetry is that as a usefull tool must be useful with care. You will only see what you want/are looking at. You can measure a full other stuffs, that gives you all other conclusions. I like Metro and the ability to use the Search Apps/Files/Settings on an full screen. Just not always. I think i will use Google Desktop just when i just want a calculator or Notepad. I just tried the file search. Buggy in the dev preview but works. (Buggy as in explorer crashed several times) One thing I don't like is it seems to take longer than expected for a tooltip/preview to show up. It'd be nice if that time was shortened a bit. Also the addition of flying tooltips wouldn't be a bad idea. By which I mean once a tooltip is open and you hover over an item near it the tooltip follows the cursor and the information is updated rather than tooltip close, pause, tooltip open. I'm beginning to like the overall direction of the Start screen, but there's one thing that still bothers me: Jarring transitions. I'm sure you've heard it many times, but that's only because its true. What if, when hitting the Start button, you render the tiles on top of the current running metro app (including the Desktop) ? To differentiate the Start screen from the background you could apply some effects like a gray scale to the app in the background , and/or shrink the background app a little bit like you do with tiles when you're dragging one around on the screen. This could give the user the impression that their work hasn't just disappeared… it feels safer knowing stuff is still there because you can still see it. Also its easier on the eyes, and could even look cooler. the more I use it the more I realise that Metro just doesn't work on a PC. It is clumsy, unintuitive and just plain disruptive to work flow. For the people that like it fine but at least provide the option to switch it off. Just because it is a change doesn't mean that its better for me using a PC 12+ hours a day it is just painful and the closest I have come to physically abusing my PC. On more than one occasion I have had to get up and simply walk away thru frustration. Yes I know this is technically off topic but an improved search is useless if the shell which you operate it from is not usable. How I am going to search for folders in “Start” screen? Still have to use Windows Explorer, right? It would be better if the right search pane appeared in the Desktop view without switching back and forth from the tiles interface. Just my 2 cents. Let it appear into the Desktop, leave alone the Metro interface. That would be great. Might I suggest a small textblock within the start menu's appbar that reads "type anytime to search". I think that'd solve most discoverability concerns people have, though users just discovering the feature might be convinced they need to bring up the appbar to search for a while. HONESTLY! How the heck is continuously switching contexts from the desktop for the smallest things a great improvement in any way? So continuously having to watch your desktop swap out from under you just to type something in to search and then swipe back in to view is possibly the most annoying thing I can think of about W8. Please DO NOT overlook "context switching" as a major mood killer for power users *on my knees begging*!! Ah ***. Are you serious MS that I have to have a complete switch from desktop/application to Metro Start screen every time I want to type things in to the search box? What happens when I have a document open and I want to type in a few words in the search box from said document? I lose focus of the document to do that? I don't want that to happen. It's well and good having specific search-keys like Winkey+W but why not just incorporate that in to the NORMAL start menu? I think the constant transitions from metro UI to desktop and back again are going to get VERY frustrating. Have you considered how awkward it will be if I want to perform repeated searches for different things to pull up content? Please, I beg you, give us a normal start menu for normal desktop use. One of the biggest problems with Windows 7 search is the Indexer. It crushes the hard drive and brings system performance to a halt. It is almost as bad to performance as virus (er… antivirus) software. Please build a new API into windows, something like: FileActivityInfo[] FilesTouched(searchPattern, oldestActivityReturned, changeType)… AND a notification API for active applications. This way, the Indexer, AV software, and other random apps could plug into this, and eat less hard drive. IT would make more sense to have a minimalistic bar swipe in from the left-hand-side without the huge transition to that metro interface. THEN, perhaps introduce some transparency, so results come up on a transparent glass overlay on top of the standard desktop. Perhaps upon the metro-bar coming in from the left, have the entire desktop shrink a little so that everything can still be visible. Please! @ tN0 Thanks for your feedback. We use dynamic property layout in File search to show the user what property their search term matched and to provide additional relevant information about each specific file type. In the case of pictures and videos, thumbnails can also help quickly identify a file. For most document files there isn’t a thumbnail available and so an icon is shown. If a user were looking for a the “Build” video in this scenario then the thumbnail should help them identify it. They could also use the type-based filters to narrow the set to just videos. If instead the user were looking for a PowerPoint, for example, then they should be able to quickly identify that the first result isn’t what they are looking for and move on to the next three results which are PowerPoints. @WindowsVista567 Thanks for your feedback. The “Run” functionality available in the Windows 7 Start menu is available in the Windows 8 Developer Preview. To launch this particular file just type c:w and start using path completion to get to C:WindowsMediatown.mid and hit enter. @Windows user I fully agree with the option of a mini metro search screen. I'd prefer it to be the default action for when hitting Windows key from the desktop but I'd settle for 'Win + whatever'. Your suggestion to right click "to open the win7 start menu or the mini metro green search screen" is also an excellent one. @Steven I honestly believe the current fullscreen 'in your face' transition when pressing the Windows key from the desktop is going to have a significant and completely disproportionate impact on the acceptance of Windows 8. I'm sure the Windows team wouldn't want all their great work overshadowed by somthing that in hindsight was so easy to remedy. My comment no where to be found…. sry if it's doble post: I like the new search… mainly because "Apps"; Files and Settings are diferent and when looking for one of those the relevant information its diferent: For example when i look an "app" to launch i just care about the name…"Outlook" (maybe some tags like "mail" or "send"; "e-mail") but when im looking for a file i care more about the author, size, date and path… (maybe even thumbnails to set apart homonymous files)… One thing i also use the start or run box is to open webs; just tipe, for myself its easier than open my default browser, stop loading the star page, and type the url …. i dont konw if many people use this … What if we need more filters to find files, like size, modif date scrols, type and so on… Tiny <–||——————-> Huge Less than 64 KB Old <——————-||—> New After Last week With search taking the whole screen you could easily find a place to put this filters, maybe a + sig with the text add filters or something.. Good work anyway …. it has room for improvement Alvaro If I hear "Our telemetry data shows that…" one more time, I think I'm going to have to stop reading these blogs. How about listing to what people are saying in these comments. What about this question, that heaps of people are asking, including @WindowsVista567 : "One more thing: please answer the question about whether or not it will be possible to run Windows 8 with the Desktop as the primary UI, and with loading the Start Screen without covering everything on the desktop." And I completely agree with this from @WindowsVista567 – The answer to this question will make or break Windows 8. Windows 8. Humm. Should i cry ? Should i laugh ? Is there an Advanced Find screen? I find Windows 7+Vista search far less productive than even XPs limited search options. Take Google or ebay advanced searches as an example, everything they offer can also be done by entering text in the usual search, but the Advanced Search form provides discoverability to the various search parameters available. It's difficult to know what options are available in Windows 7. This blog: it'd be interesting to add a check box to comments to indicate whether people have actually tried Windows 8 or are just irrationally frothing at the mouth. (I haven't installed it). @BrianUp I see what the problem was. The results appeared in the Search bar on the right-hand side. This is why user interface design is so important, and is just another example of the many mistakes that the Windows team has made. If you do a search like this, even when in the "Apps" view, the results are still expected to appear in the main viewing area. Strangely, they do not. When I didn't see the results where I expected them to be, I assumed the feature was broken. The Start Search behavior in Windows 8 probably needs to be more like what it is in Windows 7, and Apps/All Programs needs a dedicated menu. I will not be embracing an app-centric model with Windows 8, and many other users will agree with me, so it makes sense to restore some file-centric aspects of Search that were in Windows 7. When I say I will not embrace an app-centric model, here is what I mean: if an app stores its files in a hidden, app-specific folder or does not let me choose where to store saved files, I WILL NOT use it, period. If a photo app stores photos in a folder that is hidden or locked down, perhaps in the Applications folder, I will not use it. I will instead use an app that is file-centric, as managing files from a central location is much easier than trying to use photo managers like Adobe Organizer or Windows Photo Gallery. What I really don't understand regarding search is why is it so good NOT to have a search box on the Start Screen? Some people might find the function regardless, but why not make it easier to find it? Are you running low on screen real estate? My impression is that you still have plenty of room there, and that's an understatement. You addressed one of my main concerns with Win 8; I couldn't search for settings quickly. That shortcut fixes that. But remember to support the best feature from win 7: win+#. I know this works in windows 8, but you can't see the pinned apps to see what number goes to which application unless you are in the desktop app. These should be visible at least in the start menu.. Why not to combine a Metro windows explorer to this search engine ? this will make it powerful and universal . search transition needs to be addressed. It is jarring to having to back and forth from your context to the search. This is not ipad. I loath mobile operating systems and apps so i was reluctant to take to the new start menu but the video won me over. Is this being developed in concert with the promotion of a new HULK film? Seriously, what the heck is with your love of green? I just can't comprehend how any adult looks at that and thinks "Welp, needs more shades of green". You've forgotten about pen input. I regularly search for things on my start menu in Windows 7 by tapping on the search field in the start menu, bringing up the TIP and writing what application I want. If you don't have the ability to make the magic search charm swipe action that's being mentioned in these entries, you see no way to get to the field and there's no TIP or keyboard to come up. So this means anyone with an existing or upcoming non-touch device is out of luck unless they have a physical keyboard… and memorize a hot key. And goodness knows how this all works with JAWS and similar. I definitely think a search field or button should be visible on the start screen at all times as it's not discoverable otherwise. I know it says here that "people will just try it and see how it works", but my own experiences with testing show that when hiding features in new versions (particularly with existing input fields), people assume the feature has just been taken out. For instance, I know of someone who used the search field in IE7/8 and when they were upgraded to IE9, started searching by going to msn.com and using the search field on the web page. How should they magically somehow know that they can search from the IE9 address bar? (I'll note at least the IE team tried to sneak a search button in there to help you out). Said person now prefers a different browser. Great work on the search in windows 8. @WindowsVista567 you keep going off topic, stop writing the same on every post please. I don't really care if you "METRO" or "WINDOWS" or DESKTOP or whatever. Try to stay on topic. Can't wait for the beta. @CapoxD Sorry, you're right, but this Search feature is fully integrated with and directly tied to the Metro UI, so I tend to consider any post like this at least somewhat available for Metro UI criticism. Also, many criticims and suggestions for Search have to be brought back to the rest of the Metro UI discussion in order to be complete. Sorry if I caused any problems with my posts, I'll try to make sure it doesn't happen again. I agree the transition is a little jarring.. maybe if you leave the desktop background or the taskbar … one advantage of leaving the taskbar would be that you can see tha apps currently runnig …. just a tought. @Win user, wait wait.. did WindowsXP has search, really? Well in Windows 7, you can include all your fixed/internal or external hard-drive in index by going to indexing options (probably via start menu search) then modifying the path. Once the index is ready (in few hours), afterwards it would take too few keystrokes (a fuzzy search) to get to the file/folder/program or control-panel-item needed even if it's buried deep inside the folders (like you type ser.. while you are typing you will see Control Panel's services in start-menu list). You are missing the real goodness of Windows 7 for too long mate! I rarely open Windows Explorer to access a file or folder in Windows 7, because Start Menu search caters the need: To find the right file in no time! Hope it helps! Great work MS really lookin forward to the beta, METRO is the future for touch and mice and I can't wait. Now back to a hardcore COD session. Is this a joke? omg new windows looks so ugly. wtf micrsoft? Are you crazy? You aren't fooling anyone with this silly game of yours. The real WindowsVista567 posts better comments than you! Are you crazy? You aren't fooling anyone with this silly game of yours. The real WindowsVista567 posts better comments than you! Switching to the Start Screen to do simple tasks (like search) cannot possibly be optimal. On a multiple monitor desktop workstation, there is ample screen real-estate to display a search UI with results and keep my work in front of me at the same time. I simply do not see any benefit from implementing search on the start screen. After thinking about it, start screen search is also not optimal for tablets. None on the screenshots presented here show an on-screen keyboard. How do you expect tablet users to enter search information? How will the presence of the on-screen keyboard change the layout of the search results? A lot slower this way. I like old way. I hope there will be a option to disable metro. WOW.. the transition is so jarring and ugly…make me dizzy just watching the context switch from Metro to the Desktop… I'm sure MS can do a better job making the transition smoother… this is such a non-starter.. the context switch from full screen search to the desktop…now you're in Metro, the next minute you're in the Desktop..from a modern UI to and old UI..this absolutely makes no UI sense… the concept is ok…although I do not like the full screen mode search, but they need to work on polishing the Desktp UI to bring it closer to Metro so that the transition is not so jarring… If we had real-time voice recognition, there would be no need to type anything. :-/ Sigh. I guess I must wait another 10 damn years before this stupid touch craze dies down. Off-topic but made relevant by some of the comments: Those bemoaning the preponderance of green in Start should consider that this is just a preview edition, and the background color (#0e6e39ff) is simply hard-coded into the theme at this stage. All this will change long before RTM. Please stop being so superficial. You should be focusing on the *content* of this post, not what your favorite color is.…/dissecting-the-new-windows-8-start-ui-layers-images-and-colors-oh-my Why didn't the user in the video add the Calculator shortcut to the task bar. Then it would have been one mouse movement, and one click and the Calculator would open. Instead you have him pressing WIN, then typing CALC, then pressing enter – that's hardly more efficient. @Steven Sinofsky Searching is a pain in windows 8. for windows 7, all i need to do is to press or click start manu and type and everything is there. i dont have to browse thru many categories or remember those shortcuts. Multitask in windows 8 is also a pain. I don't like to use keyboard to multitask, alt + tab or win + tab. it's not userfriendly. all i want is to click to multitask. Please do not foget us diabled folks who only have a few (3) fingers left on my hand after a run in with a saw at home. My mouse is so much better to use for me to search with and a lot faster than trying to type for me as I am left handed to boot.. My only complaint is that the search results are very green. Even the highlighted text is green. It'd be great to add more colors to have more contrast. Off Topic, but I have been asking this from Microsoft for a long long time before Apple started doing this, but are you going to start making video tutorials on your product. I bet the reason a ton of people never used the Run/Search command for finding a program was 1 they had no idea they could even click in that box and 2. you have the crappiest tutorials ever. How about teach your customers how to use your products a bit, no wonder why so many customers are jumping ship its easy. 1. You have Mac Geniuses for about $150 / year anytime you need to learn something 2. They have hundreds of free video tutorials. 3. To upgrade to Windows costs $350 / license ugh… @Jason, Thanks for the feedback! There are existing file system notification APIs that many applications use to obtain information about file system updates – resource consumption depends on how apps respond to these notifications. Each release we’ve improved the performance of the search indexer. The indexer dynamically backs off resource usage when the user is active, making the resources available for other processes. In Windows 8 we have done further work to improve the indexer. When compared with Windows 7, disk writes have been reduced by 50% while indexing files and the index now uses 10-20% less hard disk space. That green is the most hideous color. And theres too much of it Seriously, we can change that, right? Themes for the whole system?, I have some issues with the Start Screen to which Microsoft hasn't given satisfactory replies and some suggestions: Issues: 1. Feature lost: Why can't the user define custom keyboard shortcuts for the Start Screen items, the way he can assign any keyboard shortcut to Start Menu items? 2. Unproductive UI: Contextual options like Run as administrator, Open file location are hidden beneath one additional click – the "Advanced" button – at the bottom of the Start Screen. Please show contextual actions as individual buttons below on the Start screen. No need to hide those 3 actions in a menu. 3. Unproductive UI: For mouse usage, when you right click on an app, the mouse has to travel all the way down to the bottom of the Start screen to Pin or access advanced contextual options. Whereas in the Start menu, the context menu appeared right at the position of the mouse pointer where the user right clicked.. 4. Feature lost: Loss of many context menu actions. In the Metro UI, I only get Run, Run as Administrator, Open file location and Pin/Unpin. Where are Rename, Properties, Delete and any custom actions added by Microsoft's own Sysinternals tools like shellrunas which adds the "Run as different user" option? 5. Usability issue: At the Start Screen, because the white box that shows keyboard focus is on the top left most tile, only pressing the Down arrow key or Right arrow key does something. Pressing the Up arrow key or Left key does nothing, whereas in a menu, the keyboard focus/blue selection begins from the top or bottom depending on whether Up or Down arrow key was pressed. 6. Feature lost: The Start Screen does not show tooltips for apps from the app shortcut's "Comment" field. The Start Menu showed tooltips from the shortcut (LNK file's) comment field. 7. Feature lost: The Start Screen does not show tooltips for folders defined using desktop.ini in that folder. In Windows 7, the Start Menu shows tooltips for folders. 8. Just to prove your point and justify your design decisions, you continue to ignore the point we are making that we do not want a full-screen view of anything covering the work we are doing. The lack of the Taskbar on the Start Screen is also a deal-breaker. Suggestions: 1. Run dialog supports executing apps defined in the AppPaths registry key at HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionApp Paths (read more about what App Paths is at blogs.msdn.com/…/10189298.aspx) which Start Screen Search does not support. You should add running apps defined in AppPaths from Start Search (Start Menu search box and Start Screen search). 2. The mouse charms menu is poorly designed. The mouse charms menu is activated by hovering over the bottom left corner (to follow Fitt's law you say) but this creates a problem for clicking the left button of the scroll bar on the Start Screen. Secondly, the mouse charms menu is shown on the left but clicking any charm shows the UI on the right, so the mouse has to travel from left to right unnecessarily. You have given us no reason why there two separate charms menus (one for touch and one for mouse). The same touch charm menu should be shown for the mouse by swiping from the right using the mouse. 3. Add options to Run dialog to elevate using checkbox and Ctrl+Shift+Enter. Task Manager's Run dialog already has that checkbox. @Jonathan Kay You can perform the swipe gestures with a stylus, so searching with only a pen is a similar experience to touch. I'm sorry, but I disagree with every part of this post. There needs to be an 'all' option. Really? Typing uninstall doesn't get you want because there's 20 searches? Well how many users are searching for uninstall and not searching for the control panel by its name, Programs and features? If I press start, type programs, and hit enter its done. Hiding things between more keyboard shortcuts that most people aren't going to ever know does not make things more efficient, it makes them more obtuse. And yes, you can arrow down to the search parameters you want, but that's a bunch of extra keystrokes, making it less efficient. Finally, the one thing that is ridiculous about all this telemetry data that Microsoft is collecting is that it's not a representative group. Don't get me wrong, I'm sure you get tons of responses all over the world. But EVERY unknowledgable computer user is leaving these options enabled, and most advanced users are turning them off. It's no wonder why you get so many people who don't use the advanced features. And whatever happened to the special folders in the Start Menu's right column? How can we directly launch Devices and Printers, or Games Explorer? Searching for printers shows nothing, not even the printers themselves nor Devices and Printers. What happened to the browsable list of "Recent Items" (Recent documents)? Also, right clicking a file in the Start Screen after searching is opening it. What if I want to see its properties? Why are the contextual options missing? You have taken away entirely any context menu options we got by right clicking an item in the Start Menu. I've reached the conclusion that I use my PC in a very different way to Microsoft's user panel. I spend 80% of my time using 20% of my applications and files. As a result I organize my workspace and shortcuts to make accessing that 80% as fast as possible. I only use 'search' when I have lost something! My main complaint about Windows 7 search is in two areas, which I'm afraid cause me a great deal of dissatisfaction. a) Accessing any network file inevitably results in the 'Green Bar of Death' during which the PC seems to be rebuilding its search index of the network files (which I assume includes real or imagined ACLs changes). Leastways that is the only explanation I can reach for a very major irritant and time-waster. b) The current search engine seems to spend a lot of its time thrashing the hard drives. This i/o threshing causes knock-on problems for i/o intensive operations such as the use of virtual guests. Surely indexes should only be built or updated when a real change has been made to a file. Seriously, I'm continue saying that until the metro screen will not merged with desktop, this approach will be ugly. IMHO start screen for desktop and laptop should be something different in many ways on desktops and laptops: – add transparency; it is really ugly to switch between two completely different screens – add an easy way to switch between apps (like windows preview and something more) – who says that the computer should start with the start screen…start on the desktop and then use the start button…please do not use windows 8 as a first step to drop desktop in future versions. Desktop may be an old approach but it works. I know I'm part of the "I've been using WINDOWS since version 1.12 – if it ain't broke don't fix it" brigade, but there is one thing the "new search" really points out the failure of Metro. Sometimes, get this Microsoft, I do MORE THAN ONE SEARCH AT ONCE. Yes, being a WindowS user, I use the multiple-things in multiple-windowS interface you have provided over the years so I can do DIFFERENT TASKS ON THE SAME COMPUTER at the same time. If you do insist on releasing this product as it is the UK, I will take you to Trading Standards if you call it WindowS anything. It clearly isn't WindowS, perhaps "Window 8" would describe it, or "MS-DOS launcher". Another lost feature: You cannot search for folders any more? There is a folder called "Letters" in my Documents library. When I type "let" in the Start menu search, it shows me the "Letters" folder. But nothing on the Start Screen because apparently the Start Screen only shows files, not folders??? Steven give me the beta soooooooon. period As usual, xpclient makes many valid points. @Philip > The one glaring problem is when searching for something that has no "program" matches, but *does* have "settings" matches. In this case I get a huge screen that says "0 results". I would prefer (and expect) the results screen to default to the search group actually produced results. Thank you; this is very annoying and I hope it will be revised in future builds. When I type 'windows up' in the WDP, I have to switch to the settings group in order to launch Windows Update. In Windows 7, the first control panel item is automatically selected if there are no results under 'programs' (as it happens, Windows Update is listed under 'programs' in Windows 7, but that is not relevant). The whole notion of taking over the entire screen is disagreeable to me, but I suppose that's a fundamental Windows 8 design issue and not limited to search. I'd rather see the improvements described here, like rich tooltips, be part of search in Windows Explorer. . I like the fact that most of the productivity optimizations this new UI paradigm is bringing depend heavily on the Win-key+# combination. In the same time we are supposed to be previewing a tablet oriented interface. Do you see the contradiction here? So they are creating a tablet oriented user interface, but they are using it to replace the desktop interface. On the desktop it is really unusable and it cannot compete with the existing desktop but on the tablet I need a keyboard to use it efficiently. I love where this is going…(not).. @ Marc Wautier – MSFT "…When compared with Windows 7, disk writes have been reduced by 50% while indexing files and the index now uses 10-20% less hard disk space." Good work, but too bad. Hideous Metro will distract me 100% of the time to notice. . Any word on ARM windows 8 ?? Will my old win 7 softwares work on it?? It's hard to tell where everything is going in regards to Windows. If the desktop is expected to be depreciated and eventually go away, then the current design makes more sense. If it is not, then it seems like it would make much more sense to put the tiles on top of the current desktop rather than transition to another screen entirely. It's the constant back and forth between two 'worlds' that seems disjointed. Perhaps some guidance in this area would help alleviate some of the concerns. Yes app search seems pretty nice in Window 8. But not MetroUI! Implement the same search in Desktop/Start Menu search and it will be nice. Used MetroUI/Start Screen for a week and I could not get used to it. It is a continuous pain in the ass. Now I switched back to W7 for all my daily work and just use w8 to look up what you post about. No way for me to use Windows 8 unless I can turn MetroUI off completely I just had an epiphany. We should all open our Windows 7 computers and complain about Metro in the Start Menu search field. This will show up in the telemetry data and they will remove Metro. "Given the ton of interest in the design of the new Start screen" To be precise, the ton of interest in DISABLING the new start screen. Your interpretation is just sugar coating reality. @Steven – you said "If you wish to do more than one search at a time you can use the Explorer windows in the desktop just as you do today." – That would be great. In fact, thats all that is being asked for. Continued use of the explorer interface without a single hint of Metro, whatsoever, ever. I'm still at a loss for any technical reason not to implement a simple toggle (similar to current classic interface option under advanced options). Can anyone explain how in Win 8 I can watch a video (in either the desktop or a Metro app) and then open a new (not open) application without browsing away from the video (as the start screen would cover it)? I'm not talking about snapping already open apps (like in Video#1)… this seems like such a basic use case, but I can't see how to do it with the new start screen…. >For professional scenarios, every keystroke matters. Indeed. So why give us search that by default is non-customizable. I want a search box that I can use immediately to specify file filters, multiple search folders, optionally specify content to match for and optionally specify a date range. And I want feedback, including the current location being searched (so I can guess rougly how far it is – the progress bar is useless for that). now with Windows 8 you've made it just a variation on Windows Vista/7. And what am I searching for the vast majority of the time? Is it applications or is it data of one sort or another? Yes, you guessed it. Its data I am searching for. I rarely use search to look for programs because they are present on my very usable Windows XP start menu, or my less usable Windows 7 start menu. >As you install more and more apps, these tools become increasingly important. Only because you have disregarded the utility that is afforded by the start menu and replaced it with this useless start screen. I've got between 450-900 applications on my machine. THe ones I need regularly I can find on the start menu. The ones I need rarely I may search for. And when I do search for them I'll open the search box and tell it which folder to search in if I know. That is quick and easy on XP and clumsy on 7 because you messed up search. Likewise very clumsy on 8 because no easy to specify this. >we wanted to make sure the efficiency and dexterity of the Windows 7 Start menu search was carried forward What efficiency? Windows 7 is mcuh less efficient than Windows XP search box. I have to fail a search before I can customize it. How can that be more efficient? > Had we continued using the Windows 7 Start menu search interface to search for a Control Panel item, >you would always see app or program results before Control Panel results Doh! But if you'd jsut let us have a useful start menu we'd be able to open the control panel easily and not need to search for it. Going to the start screen, clicking control panel, scrolling down, clicking more settings and finally getting the control panel can hardly be considered efficient. >In Windows 7, the total number of results that could be shown in the Start menu was limited Indeed, but in Windows XP, the search results are shown in their own window. You can show lots of results there. >Search charm. That is the thing on the popup menu from the start button that on displays on seemingly random occasions? I haven't found a method to reliably display that menu or reliably not-display it. It just seems to appear at random some of the time when my mouse hovers over it. > You don’t have to first click on the Search charm to begin searching – simply start typing in the Start screen and you’ll see your list of apps filter down to the one you are looking for. Completely undiscoverable. I wondered where search had gone. Only when I read your blog did I know I could do this. I've been writing software since 1984. I'm not a newbie or an idiot. But I couldn't find this functionality. How are less computer savvy folks like my parents, my girlfriend, the people at the vetinary surgeons going to discover this? They are not going to discover it. You haven't preserved the search functionality from Windows 7 – part of that functionality is knowing there is a place to go to, to search. It was on the Start menu, but you#ve removed that, so… You claim that at //build/ people easily discovered this. A room full of advanced computer users and hi-tech phone users. Hardly john and jane average computer user is it? >More relevant and contextual information for each file is also now displayed to make the search experience complete. Er, no. Why isn't the date shown, etc? I have all this information available (in one row) in Windows XP. You're wasting screen real estate On Windows 8. And of course, Windows 8 search is full screen, which again like all things in Metro is exactly what desktop users don't want. We want a search experience like that of Windows 7, or preferrably of Windows XP where you can set the search up without wasting time doing a search that will fail so you can get to the customize stage. We also want the search windows resizable and on the desktop, with current folder feedback so that we can see our other activities as the search progresses and so we can use the search results in context with the applications we are working on. Windows 8 search gives us none of that. This reply is not to disagree with you for the sake of disagreeing. The purpose is to point out that, yet again, Metro is a tablet UI (that probably works quite well for tablets) but which is totally inappropriate for those of us that work on the desktop. Its also interesting to see the use of telemetry data to justify these decisions, claiming the results are going to help power users. You had a good start menu in XP, broke it in Vista/7 and then use the telemetry data from VIsta/7 to say people don't use the start menu very much. Hardly surprising considering the Vista/7 start menu is so hard to use compared to the WIndows XP one. And again, the same thing happening with the search telemetry. I use Windows 7 on my email machine. I do very little searching on this machine – mainly because the search experience is so painful (setup a search to fail, then customize, watch the search with no search location indicator). I use XP x64 as my development machine. I use search a lot. I can start a search, fully customize it before search starts. I get to see where it is currently searching. And I get to view the results in a fully resizable, moveable (to another monitor, perhaps?) windows. Really useful, real utility in that. I can't see any utility (for me) in what you've done for Windows 8. I can see if I had to use that for any length of time Id be writing my own search utility to give me back what you've taken away. Please, will you stop breaking what you spent so long acheiving? Windows 7 is good. A few things (start menu, search) could be better but you are going in completely the wrong direction for your desktop users. I still don't see how this is better than Windows 7. I still don't want an ugly, green, full screen thing every time I want to do the simplest of tasks.. I think the desktop to metro transition would work a lot better if rather than the current side-swipe the whole metro interface appeared in the foreground of the desktop window in an "aero" style, with the background desktop de-emphasised by dropping the brightness so metro is any overlay over the desktop. The best example of this I can think of is when you you get the UAC prompt in Vista / 7. Why the f%%k are you shoving Metro down our throat? You would be fired like the person IIRC Brian who released Vista. We will show you with our wallet. Never underestimate the power of geek community (no matter how small) as we influence the world and the word of mouth. My fear is – seeing these screenshots – that the overall green color (which will be customizable, I know) may cause pretty painful effects on your eyes if you have to look at that color all day long. Why not use an even lighter shade (mostly being white with green accents) for the right search bar and anything that appears over there? Just a thought. @Andy G. In my perception, Metro is a paradigm shift towards new kind of apps compared to the one we are accustomed to. Metro encapsulates some features of desktop, like search where you can find files/folders from desktop world as well as the metro world but reverse is not possible. That is; the metro apps doesn't appear in program files folder or under uninstall programs and you cannot search for metro app from Windows Explorer search. So I guess you got a nice suggestion about the overlay to make it look like a part of the desktop world, but it's highly unlikely. Wish I could see a post named, "Improvements in Windows Media Player". ID3v2.4 tag; APE, FLAC, ALAC, OGG; DIVX, MKV, FLV, XVID formats — where available, where allowed — support. Please, Steven Sinofsky As you know it will be fixed. So chillout! @Steven Sinofsky "." Wrong. Just as we do today is not search using Explorer windows. I'd never have thought of doing that until I read your reply to Brian. I've just tried it on Windows 8. Yes I can have multiple different searches that way. But if I do that, for each search I have to do the following sub-optimal actions (none of which are as good as Windows 7 or Windows XP search): 1) Launch an explorer. In windows 8 I need to remember to right click to launch 2nd and 3rd ones otherwise I'll just bring the current one to the front. Un-necessary mental complications there. It should be same for every window. 2) Change the address bar to the root of where I want to search. 3) Specify the file filter then press return Problems with this: No ability to specify multiple search locations. No ability to specify content filters (words inside files, etc) If you change the folder root after specifying the file filter the file filter is lost No search progress No ability to customize search None-obvious – despite using Windows for the last 15 years I hadn't thought of this Nothing like WIndows 7 search, nothing like Windows XP search. nothing like WIndows 8 search. #fail Why can't you leave alone what is already working and give us something useful? Don't you understand the anger and frustration coming from folks like me is because we want Windows 8 to be a success and we are really seriously concerned and worried that you are about to do something even less successful than Vista? Go and make Windows 8 search like this: So when you search for something, anything, it finds it no matter where it is. That is surely the simplist basis of a search routine. @Steven Sinofsky I've been playing with Windows 8 Explorer search a bit more. Took me a while to realise I can customize the search experience. And what a backwards step that is compared to say the Windows XP cusomtization experience. Let me explain why. In Windows 8 you've done this with a drop down ribbon control. As soon as I modify one setting the whole ribbon goes away, so I have to redisplay it then modify another setting. And so on. So tedious. Such a waste of time. Leave the darned ribbon displayed will you! I know when I've finished changing the settings, not you. Whereas in Windows XP, start menu, search. Enter my file filter, enter optional multiple folders to search, modify the date range, enter a file content filter and go. None of it goes away or is reset if I change anything. Its all there, right from the start. I can see the results in my search window. Quick, easy, efficient. I also notice that the other attributes you normally control from the menu in Windows 7 (such as view settings etc) are controlled via similar ribbon controls. For all of these ribbons you use huge amounts of screen real estate. Nothing is easy to find. Nothing is easy to modify (because everything goes away as soon as I modify anything). Its a dreadful user experience compared to anything that came before it. Why are you dumbing your OS down? It needs to be usable for experts, not idiots. Windows 8 feels like its designed for idiots. Makes sense then, if only idiots will use it. [Yes, its an obnoxious rant. More or less on par with the responses from microsoft] I want to know the price. Period. Maximum 50 dollars for "Windows 8 Home Premium" upgrade from Windows 7 is OK for me. Otherwise, Windows 8 will never exist for me. No tablet either. @@Steven Sinofsky So far you are posting about the features in windows developer preview 8102 but when Microsoft will add new features in windows 8 developer. As there are maximum number of users of win8beta and other are giving suggestions for interesting features to include it in windows. also there is no like or dislike options for posts so we can check which post are good to read and which not also no any ms official member is giving reply for suggestions given by users or developers Sadly as windows user, i realise that MS isn't slightly interested in helping and making life easier to users. They just follow their guidelines to achieve what purposes they want. I am not saying only about Metro. But also things like Flac, mkv, divx, which require codecs installations… MS want to stick with their own thing. But its not easying life for users… Even if people are all using flac and divx they dont natively support it. Flash on Tablets also. Android users are complaing that they have reduced battery life. With Metro on Desktop is only going to get worst. The full screen search apps all the time is really obtrusive and schizrophenic in switching contexts just to open an common/often used app or a simple file. The Desktop is not an app. It's an context like Metro. Desktop as an app is just an immense absurdity. I dont realise not how one can invent this idea, everyone has bad ideas from time to time, but how people surrounding them thing this makes sense. Make a poll and you would get like 3% of people agreeing with you that Desktop is an app. Microsoft just dont realise it or get it. They are much of time, not always of course, but from behind. They just cant figure it what the market will follow. They just react. IPhone -> Windows Phone (great product, but far back on time, against Android WP is too small because of time and also availabitily, but mostly because of time. IPAD-> Metro Windows 8 tablet. Far behind in time. The thing is MS is also trying to apply Metro context on Windows Desktop which doesn't make sense. At least as it is now. I think glorious the idea that you can switch from context to context whenever you want, like having a laptop (touch-screen) device that can transform, if you are using touch of mouse-keyboard. But not by reducing previous funcionality that worked fine on Desktop and having to switch context just on simple searches. In future it would make MS back even further. MS will realise this model wont work, and have to adapt it. I fimrly believe that Windows 8 will not be widely accepted because of this schizrophenic context. At Windows 9 time, MS will understand and make context more separate, or at least being able to live in one and only having to switch when the user wants. I dont know the motifs of why MS wants thing to work this way. I might suspect that to make people buy more 30% apps store revenue. Maybe is just pure stubberness of Windows design team, i dont know. Whatever, this telemettry doesn't cover the all thing. Just what you want it to see. You get just some data and use as you will. Clearly whatever motif, MS isn't aiming to users needs/easing. The level of satisfing of the product is only going one way, down. People will have to workaround to make things work as they want. Windows 8 as great new things on the Desktop and on Tablet side, but not how they merge on switching all the time. Again Desktop is NOT an app. Desktop idea absurdity as an app can only be understood as an way of trying to explain how things work now. But ironically on the other side also just reveals itself the all absurdity of this current model. In the end this would 'work'. Windows 8 will be possible to use it. But not on the most elegant and efficiently way. My question is, as intelligent and a wise person Steven seems to me. Does he agree with this model and is one of the main backup support or he just can change it, and is waiting for an official bad response from users to an i told you so, to the responsible person being Ballmer or whatever? All you people who say you do not like the new Start Screen/Menu/Search “in your face Metro UI”, you are wrong. The telemetry data says you WILL like it in the future. Also the telemetry data has proven beyond any doubt that the Tooth Fairy exists as well as the Easter Bunny. If you continue refusing to accept all these “improvements” in the desktop space, you will have to go through even more telemetry data. The choice is yours… Say hello to the new era were statistics are driving the UI development 99.9% of the time. At least one company believes that this is the right way of doing things. And if you disagree with that, then you are wrong, because they have the telemetry data to prove telemetry can design better UIs than common sense. @Mil_ The problem is, these are developers who are doing all of the UI work. they aren't designers or artists, they are developers, who have no reason at all to be in the UI. they need to hire a group of Industrial Designers (like i will be) and hammer this *** out. I don't understand why you have to press the down arrow twice to switch to the settings search. Reading these blog posts from Microsoft is growing frustrating, I want to continue to be a MS fanboy and I want Win8 to be a great OS.But there are a lot of valid, insightful criticisms being made on these posts that seem ignored. When MS decides to address an issue it's generally tangential. Why keep avoiding the big criticisms? The way it looks to me is that all the major complaints about desktop usability and efficiency all flow out of the same single bad design decision – to separate the desktop from the Metro. I disagree with the naysayers who feel that having one OS for desktop and tablet is undoable. It's possible but you just haven't achieved it yet. Find a way to make going into desktop mode a way of suping up the metro interface in a manner that allows all traditional Windows functionality (the taskbar, start menu and effing WINDOWS) to be employed in addition to the start screen and you can have it all. This jumping from desktop to a disruptive full-screen metro thing is just plain wrong. Bad UI, ugly, and disruptive, inefficient and not friendly to users who dislike navigating their os by keyboard commands. @BumbleBritches57: Very kind of you to give this excuse to their design and I wish it was true, so in that case they will just fix it by calling in the “designers”. And I may have agreed with your statement if I wasn’t a developer myself who has worked on a number UI designs. But believe me the one thing I always keep in mind is “respect the user’s desktop space”. I am not saying that a UI designer would not do a better job, I am just saying that even a good developer would not, ever, propose a full screen switching to a desktop app for a simple feature like the Search Screen and I am sure Microsoft has a lot of good designers too. The people in control here are those in the marketing department. Only those people can come up with these crazy designs and then ask the poor people in the development and design teams to try to implement them. The end result is a “fantastic” job like the one we are witnessing in Windows 8 Metro UI for the desktop. It is so incomprehensible that I bet you it will feature in all future literature of Universities about software development and UI design on how NOT to do things. Now the real question is, since Mr Steven seems to be a clever guy what is he doing drumming up the Metro madness on the desktop? Is he just waiting for some other bosses to fail miserably and then he can get more control and sort things out? Only time will tell, but for sure I am enjoying a lot the latest Windows soap opera. Windows 8… re-invent the wheel again… Microsoft shooting themselves in the foot again… Stupid consumers buying this load of horse #hit again… This OS is going to rewrite everything.. eagerly waiting..… It's called a Tick-Tock cycle bro. a simple release for bug fixes, and a major version for big feautees, overhauls. a little paranoid are we? @Microsoft If you want to turn down the noise and the crazy level on this blog, you might want to disable anonymous comments. Just require LiveID to post anything. Yes it might cut out some people that want to have a real useful voice, but they don't want to create a LiveID. Hell, you could even implement the new OpenID and allow for various authentication sources! 🙂 It would make it a lot easier to find helpful comments, be they good/bad in respect to views of the product. I haven't even read the article yet and I'm already mad. How about it if the Windows 8 team throws their statistics in the garbage and just sits down and improves upon an already really nice system. I'm really sick of reading how statistics are justifying this or that human decision. Windows 7 has a great start screen. Yes it can be improved on without destroying it. No it doesn't need to become giant green squares. Don't know if it was mentioned already but it would be cool if the search could be extended by such useful things as quick calculation results (like in Mac Spotlight) and things like search queries that voice recognition tools like Siri can answer. I agree, Open ID should be supported…. it won't tho, because Microsoft is a whiny *** who forces everyone into locking in their own ***. can't wait for PS4. i won't be getting an Xbox again. that's for sure 🙂 About all these start menu/screen and search improvements I am still missing a good history function. Yesterday I had to save a file two times to a folder deep in the filesystem. I need this folder three times a month. Now I have to save something a third time to this folder, but its not in the last used folders in the file save dialog :(( grrrr #!§$ I always use search but I hate Indexing service :S. Too slow and heavy ¬_¬ The Search in Windows 7 was amazingly fast. I never clicked All Programs and opened any program manually. Just pressing Win key and typing program name and pressing enter was cool. And I am excited that this feature is getting even better in Windows 8. I think the metro UI is brilliant. And The Start Screen should include Computer, User Documents, Control Panel, Recycle Bin icons or tiles and the desktop interface should be removed. Metro is amazing and who would want to return to the desktop mode…. One thing I would love to see is that ability to have "plug-ins" to other applications for Search such as Outlook, and SharePoiint. That way, you can unify searches. I like how it it is broken down in the screen shots where you have basically one icon for apps, one for files, and one for control panel. I can envision having an icon for Outlook and SharePoint on that list. Is there any chance that you could implement "natural language" support in search? AQS seems really useful and certainly adds a great deal of functionality, but it would be useful for a lot more people if we could use the examples from the left column rather than the ones on the right. Especially with apps like Siri capturing people's attention, adding the ability to search as we speak would be a huge addition of value for the Windows environment. I'm enjoying the articles and really looking forward to Windows 8. I appreciate the bold new direction that Metro represents, and I'm glad you're sticking to your guns on its implementation. Major changes are always resisted, but I think that time will show that this was a worthwhile change. Designs by committee creates bad designs Either embrace geeks and other high-end users or make it simple. Instead Microsoft is does neither here. Window 7 and Vista search is simple. This is not, nor is it feature-rich enough to allow for pinpoint searching. I find it funny that people are so up in arms over software that is not even beta. These posts were meant to give users an insight into their design process and thinking behind the new version of windows. Once beta hits with tons more features and improvements (that they are already working on and probably finished with a great deal) people can then judge the product since it will be mostly feature complete at that time. @Steve981: So, what point will there be exactly in complaining after it hits beta, when its feature complete and nothing will be changed? Of course we want microsoft to give the CHOICE of disabling (or somehow avoiding) metro completely on the desktop, and now is the time to let it be known. – Please add 'Date Modified' to all results for Files search (before hover). You can put it beside the file size. Date applies to all files, and is more important than size very often. – WinKey + W is harder to type than just WinKey. I'm still holding out for an aggregated 'All' view with grouping like the Windows 7 Start Menu. I'll take the supposed performance hit. Note that the two keystrokes of WinKey and W take more cognitive effort than the two keystrokes of tapping the Down arrow twice -Tab to switch panes before tapping down is confusing. Results of any type shouldn't be in the right pane – How do I achieve this Start Menu process in the new Start Screen? Start -> User -> FolderUnderUser -> FileUnderThatFolder.file -> Click and open my file without having to navigate through Explorer? This is not possible in the Start Screen. – Launchy and the like are beloved for a reason. I always thought you guys would make something to emulate that. Center of screen, no loss of focus, quick keyboard launching. Please do that. I like the posibilities this new search offers but the implementation is still poor…some things that could be improved: 1. Transitions betwen search and desktop … you could smooth over the effects, add some transparency or something… 2. Screen real state vs Informational context … I agree thah more screen space means more information to display; but there is no gain in hidding the task bar … even less if its replaced with an uninformative green space (or whatever color you choose) 3. Graphical Layout – even if the Saint Patrick theme it's temporal the tiles, files names and prperties, are missing something… doesn feel right. 4. Keyboard+ mouse navigation – Search as it is right now seems optimaced for touch (as important thing wolud beon the sides where most likely your thumbs would be) but i dont think that having to scrolls the mouse from one corner to the other and back its an efficent and mouse friendly search… 5. Advanced Query Syntax – Really????? are you asking your users to learn the equivalent of a programing syntax instead of puting user friendly filters, chechkboxes, dropdown menus ans sliders…. 6. File search – Again with so much screen reals state you couldt find a space to add filters,sliders and so on… if the Files Search is going to be so poor …maybe would be better take it out of start seacrh and make the Windos+F take you directly to Windows Explorer Search 7. Improved funcionality – As many had said why not add some extra functions like: -basic math operations type "Win 9+5" get 9+15 is 14 -measure convertions type "Win 3 meters to yards" get "3 meters equals 3,2808399 yards" , -or even web search "W:goo" and go "" with your default browser Just some ideas @Steve981 I agree that just complaining about a hafl baked product it's silly but another thing is given toughfull feedback, even before hits beta … the sooner you start aporting the more chances you would be listened (i think). Searching by acronym would be a good way to save keystrokes. For example, if I have Microsoft Visual Studio 2010 installed, I'd like to be able to type "vs" (for <b>V</b>isual <b>S</b>tudio). Similarly, a search for "mw" could return <b>M</b>icrosoft <b>W</b>ord and <b>M</b>ySQL <b>W</b>orkbench as results. Code completion in some IDEs works on this principle, and I find it to be a huge time saver. @mil "All you people who say you do not like the new Start Screen/Menu/Search 'in your face Metro UI', you are wrong. The telemetry data says you WILL like it in the future." Very well put! As I said in the "Microsoft rolls out the Chewbacca defense" discussion, the contrast between how Apple and Microsoft sells their products is stunning. You don't see Apple using telemetric data or complicated math formulas to justify their UI. Instead, Apple just shows off their UI and it sells itself. social.msdn.microsoft.com/…/0219857e-d032-433d-a00a-1230af17fa78 Where is my good old Win+F?: How do you return to the search results? …or do you expect me to redo the search if I picked the wrong file from the results? What if I want to have two (unrelated) search results? (Pressing Win+F twice in Win95…7) What if I need to look at a document/website while performing the search? What about the normal context menu for the results? (IContextmenu used by shell extensions) When I search for files, I might need to sort by size/date etc. I don't work with apps, I work with files! Sometimes I want to open a file in the default image viewer, sometimes in Photoshop, why are you making this so hard? FILE search was perfect in Win2000… @Steven: Part of the problem you're having here is Microsoft's apparent refusal to acknowledge or address our feedback. You seem to have lost sight that the point of this blog was to enter into a *discussion* with us. Can you imagine our frustration where you refuse to acknowledge or address what we're saying? @I-DotNET blogs.msdn.com/…/reflecting-on-your-comments-on-the-start-screen.aspx @NotExactly I don't believe Microsoft has addressed the issue of the two use cases about how desktops and tablets are used. For more: social.msdn.microsoft.com/…/0219857e-d032-433d-a00a-1230af17fa78 If someone wants to try and prove the interest level in needing the features of the old shell, how about creating a poll with various questions along those lines. Let the people respond and vote if they care about needing these choices. Let the actual numbers speak for how important it really is to the community as a whole. If the data proves it to be at least close to 50/50 or even 60/40 in either direction, that should be enough to make it an optional choice. If 5 people out of 1,000 actually care, then that will speak for itself too. To put it another way, all of the people shouting about it are probably getting overlooked as a minority. Besides, why not respond back to the telemetry data, with actual user preference opinion data? I dont like it. It is not frontcenter on the desktop, and search is something you want right in front of you with all your documents and notes and sometimes you are sitting in a webcall with another person. i think that only search on the startscreen is a bummer. Not that many customers will be happy about, if they are working on the desktop only. Microsoft need to have search both on the desktop and on the startscreen. Hope microsoft will change it @Stephen Kellett I am not sure your description of search matches older Windows or Windows 8. it feels like you have an optimal v degenerative example but the step by steps don't quit match either UI. just want to be sure we understand the examples where we are taking more keystrokes to see the general case. Why isn't there any context menu supported on files in the Start Screen either? What if after searching to a file, I want it to open with another program, or ZIP it? You recommend only Explorer search for that? Coming to Explorer search (sorry for going off-topic as Explorer search is not the focus of this post), but Explorer search by default searches only the current location. Searching is no longer as useful or as effective as earlier versions of Windows (2000 and XP). Indexed search is fast and the indexer may now be consuming low resources but real-time non-indexed location search is shockingly slow and the GUI even with the ribbon is not right. In the Developer Preview with the "search tools" ribbon, I could not find an easy way to specify multiple search locations separated by a semicolon or pipe like Windows XP search. Search terms and search locations are two criteria that you need to make far more easier for multiple values. I almost always want to search in multiple locations not indexed by Windows Search and enter multiple search terms. 'name:filename1 OR name:filename2 AND folderpath:C: OR folderpath:D:' is far from intuitive. Plus, you need to give an option to start search after we define all the parameters, not start searching the moment the user specifies one filter. The Windows Search platform itself is efficient, allows searching with iFilters, and the Advanced Query Syntax (AQS) is very powerful but requires too much remembering. It's the remembering aspect that MS hasn't quite got right and the UI is too minimal or badly done that it's the reason why users aren't able to find their files. I believe the Ribbon GUI containing the following fields should be very easy to do: 1. Search terms with ability to specify multiple search terms separated by semicolon or pipe 2. Containing text field (for searching inside files using iFilters). I know Windows Search already searches both file names as well as contents but this is unnecessary when the user only wants to search for file names. 3. Path field with autocomplete is very important, as well as environment variable and separator support, an option whether or not to search subfolders (currently, searching C: AND D: in a single query is very hard with Windows Search) 4. File extension(s), file type and/or file kind fields 5. Size field to specify size in KB, MB or GB 6. Date modified and Date created fields 7. Options like search inside compressed files, system and hidden folders 8. Start search button that begins searching after we have defined the above 7 criteria i.e. search begins only after fully customizing it and Start is clicked 9. Very important and missing option in the Ribbon GUI to search without using the index temporarily. The Ribbon is better than Windows 7's extremely minimalist approach but you can still improve the GUI much more to make like Windows XP search (for example, folderpath: doesn't accept environment variables? whereas XP search does). Currently the Ribbon search tools GUI does have some of these but it does not have a separate field to enter each value, it just builds the search in the Ctrl-E filter box. Off-topic: Are you thinking about changes in file system? We need a native solution that implements "zero page reclaim" in NTFS… This is very important to PAAS where the providers are using storage with thin provisioning. I too hope to hear about any NTFS improvements that might be coming our way. The 64 volume shadow copy limit per volume is a real killer when using previous versions, if this was significantly increased previous versions would be a heck of a lot more powerful and only limited by the HD space. Hopefully upcoming blogs will start to deviate a bit – the Metro fire is going to keep burning, and these "explanations" only seem to stoke it. There are some guys on blogs saying to MS, that hire them to develop and improve windows. but they are not posting any new ideas or logic's for Win OS. So i also doesn't want to loose my chance to say MS to hire me (Give a good job) to MS. I will definitely do my best to improve MS and Win OS. I am a student of Computer Science and i already posted my great ideas in blogs to make Win OS better. Like i said about to include facility like Macs airdrop to easily share file through Bluetooth or WiFi network. MS may name the feature Push to Share for Windows. So user can easily share files between windows PCs and windows phones and all other supported devices. And i will continue giving more suggestions to make Windows better Having a good app search experience is critical. Note that in my case I use search many time when I don't quite remember exactly what the file name is, and sometimes the existing Windows 7 search in the start menu is sub-optimal (although not bad). If there was a vendor provided or user provided free text description attached to an app then app search could become even more productive than it is already. Note that for best results this facility should work even if the Windows Search service is off. Windows Search is off on several of my machines due to the fact that it can kill your performance. It seems that the windows kernel does not know how to prioritize processes based on IO utilization and IO wait time (disk IO). I can make CPU hogs take lower priority, but often what kills performance is IO wait time or throughput on a specific disk (especially if it's the system disk). Windows Search can slow a machine down to a crawl by hogging disk IO (often on wait time rather than throughput) – therefore – it gets killed or disabled. This should not make the app search not function or make it slow. Anything involved in app search it a tiny amount of data and should not depend on the Windows Search service (or dis-service) @sokheang Learn to use alt+tab, it's great. @R.Johnston Using the keyboard results in faster use of the computer. If only Windows did a better job of informing users what the keyboard shortcuts were (especially Media Center). @Robbo Ever hear of the squeaky wheel getting the oil? They use the telementary data because it does a better job of reflecting what everyone is doing, versus extra whiny people who yell really loudly. @Xpclient Recent Items went away in Win 7 and were replaced by jump lists. But you can always create your own. Create a search for recent items and save it as a favorite. @Stephen Kellett I for one don't want search like what existed in XP. It never worked for me. It was so bad Google Desktop became the premium application that everyone installed for a few years. I don't know of anyone who's installed Google Desktop on Vista/7, because it's not needed. In "Reflecting on your comments on the Start screen" there are the heat maps showing mouse movements. If the user moves the mouse to the bottom left of the screen to click on the windows button, with the current layout don't they then have to move the mouse to the top right to change if they're searching for files or settings? Oh, and thank you for focusing on Searching without needing the mouse. Search in the start menu has been the single most useful change to the Windows OS. Now if only more of Windows would help users be more efficient with their keyboards. Hi Steve, AQS can be a very handy tool for an advanced user, but too many options to remember for a generic user. You can probably double check how many users actually used more than couple of tags out of hundreds available AQS tags. Do you have any plans to provide an UI to construct advanced search queries? similar to advanced search in forums. That should allow the user to select a type of file, and allow them to select appropriate advanced searchable parameters. E.g. once you select Image as file type, you should get options to add search criteria like "f-number:", flash etc.. If the value can be one of pre-defined set of values (like flash) even the value box should be a drop-down. user should be able to define a logical operator and add several such criteria. The options should be appropriate for the file type, so a music may give options to filter on composer, band, genre etc. @Poll — I think the folks that believe we do not correctly apply telemetry data would have to concede that using a poll to make decisions for us would be the equivalent of a "marketing based focus group design by committee approach". That's the furthest from our approach we could get. As we've previously talked about (and also in the Windows 7 blog) telemetry is not a tool we use to come up with answers for the product or justifications. It is one of many tools that inform our own choices in the design process. We share the telemetry on the blog to provide a shared context for the choices we make that we think is a unique contribution to the dialog–you don't see this elsewhere and certainly not for a product as widely used and diverse as Windows (though I promise every product you use and site you visit has telemetry they apply). Telemetry is not a substitute for thinking any more than a poll would be. The primary difference between the telemetry and a poll or survey is that the telemetry is millions upon millions of data points approaching a full census without any inherent bias. You would likely see many questions about the methodology if we did a survey. A survey would be subject to a significant debate about the very questions being asked, wording, the descriptions, and of course would be limited to the readers of the blog or an internet site (and subject to all sorts of limitations of internet surveys). We use telemetry to settle arguments over how a feature is used. We find it is better to look at the telemetry (sliced by product edition, hardware used, country, or other aggregate and anonymous points) and talk about how something is actually used as a fact, rather than an assertion. This allows us to form views of how to do new designs that take into account actual usage. At the same time we're of course fully aware that limitations in the current product might drive usage patterns in certain ways. Yet one must also recognize the age old challenges of forward design usually referred to as "Henry Ford said people would ask for a faster horse". We see all of these dynamics in play in this dialog. @Steven: Let me point you to a post someone else made in the Win8 forums: "Is Microsoft Really Getting A Representative Sample from All of this Telemetry Data? "It seems clear from the Building Windows 8 entries that a great deal of the design of Windows 8 is coming from telemetry data collected from Windows 7 users. However, it seems to me that there is no way this would be a good representative sample. "If you're trying to see if someone is using an advanced feature, and get a response that nobody is, is that really accurate? I mean, every basic computer user is going to leave the data collection enabled since they don't even know it's there, or how to turn it off. Of course these people aren't using an advanced feature. Advanced users, on the other hand, are much more likely to turn off these data collection options, which means that the process itself is filtering out the very users who would be helpful to have the opinion of." social.msdn.microsoft.com/…/94811a50-0687-4985-a3ac-579f6842c4a7 @jader3rd, no Recent Items did not go away in Windows 7. It can be easily added to the Start Menu and it gives a combined view of all recently opened documents including documents for apps you do not have running or pinned in the Taskbar or Start Menu whereas jump lists only give you recent documents on a per-app basis. Anyways, my point was that the special folder locations in the Start Menu right column (Libraries, user folder, Network Connections, etc.) are there for 1-click access, plus they still can expand like menus. They seem to have gone away too in the Start Screen. @Stephen Kellett here I thought I was the only one who hated how Search changed since XP. I hardly use it now on 7. It's just too onerous to do those kind of searches anymore. I get that MS wants to move away from checkboxes and rollouts and all those cludgy looking paramerters and move to a cleaner looking UI. But if the functionality you seek is buried so deep that you have to jump through hoops in the "clean" UI to get them, what's the point? This is why I never fell in love with the Mac OS. I'm keeping an open mind on Metro. This is a course correction MS has to make at some point otherwise they'll get knocked out by Android and iOS. We're in the middle of an evolution in how computing functions for the vast majority of the popultation and MS is trying to put out something that to me appears to be an operating system that's attempting to bridge the divide between what was and what will be. I agree that there are concerns about the whole "one size fits all" aspect and how tablet computing and PC computing don't always match up. But I'm willing to wait and see what MS comes up with before damning it…and this version isn't designed for that kind of analysis. In any case, if Windows 8 turns out to be the half baked idea that a lot of the detractors here claim it is based on a Developer Preview, then I'll just stick with 7, skip 8, and wait for 9. Just as I did with XP when Vista came out. With an easy tweak in Windows 2000 and XP You can search for all filetypes. This is a really bad UX. I'm sure this has to have been mentioned before, but oh my god, why on earth are you switching off the entire screen!? What if I have a webpage open that says: "open your _______ application", and I hit Win to find it… now because of this obnoxious window covering my browser window, I just forgot what I was looking for. Or maybe I want to open a couple of things. I'm going to get nauseous switching back and forth between windows. Why does this UX have to be so involved? What is wrong with simply displaying a small popover like the Start Menu does in Win7? @Steven: All we asked for is to go for horse riding and you are preparing for us a Hummer. I don’t mean to be disrespectful I am just referring to the full screen operation of all the Metro technology you have demoed so far. It may be fine for the tablets, but it is not acceptable for the desktop. The telemetry data cannot really be used to settle this argument because all it shows is that you can display more information when you use the whole screen. My personal “problem” with the new design is quite obvious, full screen start menu/search is not something my 30” monitor is meant for. Even on my 18” laptop is quite annoying, maybe on my 11” HP DM1 would fine and on my Iconia W500 would be great. What this paradigm would be perfect for is the Dell Inspiron Duo Tablet changing from desktop to Metro UI when I flip the monitor to tablet mode. On any desktop type arrangement this full screen mode is counterproductive and unacceptable. It is not an argument of wanting change or not, I do want a new Windows version every year if possible, I love all versions so far (even Vista had a lot of great features and I did prefer it than Windows XP) but if the “new” thing is going to make me less productive is not something I will invest money on. There is one thing to be progressive, and another to be just different for the sake of it. Finally i got my Windows 7 act as a Windows, and with the classic startmenu. As someone else stated i havem as an advanced user, turned off all of this datacollecting in Windows 7. Why do You have to do with what i do on my computer ? Why do You not inform about this in a very clear way at the first start of Windows that You collect data ? Why can't i be asked to have all collecting turned on or off ? It seem not to be only CEIP but also a lot off stuff is running in the taskscheduler. I feel like someone spy on me what i am doing. I might be a bit paranoid but i even clean up all log-files now and then. You don't have to do anything on my computer at all, if You don't ask for my permission first ! A search.EXE would be nice. If I get a virus, it would be cool to SEARCH all new .exe files added to the system by date. Erasing new bad processes would be allot easier. I want to say one thing again, said by many here: LISTEN TO YOUR USERS ! But for some reason I did not like the green background with semi-green foreground. I would prefer black background with bright green foreground. Isn't that a IBM R51? @Steven Sinofsky Katie Price wrote:"Maximum 50 dollars for "Windows 8 Home Premium" upgrade from Windows 7 is OK for me.". To me Microsoft have to pay to get me to use Windows 8….Windows 8 is not an operatingsystem, it is an annoyance ! By the way, in USA will Windows 8 be far cheaper than in the rest of the modern world. Another reason why it will be cracked before it is released. @I-DotNET – Just asserting this doesn't make it the case. This is something we hear from folks who disagree with whether or not the data reflects their individual usage in a proportion they believe represents their view of how common a pattern is. All we can do is continue to share the data. There isn't a better source of data in aggregate. We're not claiming that the data represents any single person or any narrowly defined "group" (defined however you would like to define a group of hundreds or thousands), but that it does reliably and effectively represent the aggregate usage of hundreds of millions. This emphasis on searching to find an app implies that you know what the app is called. There are so many times I know I have a utility to do such-and-such but don't know the name of it. It's easy to find looking through folders. Having every single application on my computer listed on a single screen won't help me find it. I like the Metro screen but for most things I do the good old Start Menu will be much more convenient. Really, how hard would it be to give us both choices if that's what we want? Ok let’s assume we all agree that the data is correct and this new UI paradigm improves everything it set to improve upon. The only question remaining is “at what cost?”. The analogy here is that “yes you can have a swimming pool instead of a bath tab in your house, but you have to lose two bedrooms and the living room”. I rather stick with the extra rooms and forego the swimming pool for the time being until you come up with a better offer. In the meantime there are going to be a lot of people that prefer to have the swimming pool, I can accept that. Only time will tell if this is the right decision for the majority of users. @WindowsFan My public display name is actually WindowsVista567. The numbers go in order and are designed to match up with different Windows releases (5 for Windows 2000/XP, 6 for Windows Vista, and 7 for Windows 7 even though it's really 6.1). Thanks for supporting my comment! @Steven Sinofsky Do you read the tech news for information about the public's reaction to Windows 8? It seems that now that the BUILD buzz has died down, I keep seeing less and less good things about Windows 8 and a lot more bad ones. This link (…/windows-weekly-230-start-menu-lie-140912) contains a video with a discussion about Windows 8, which starts around 36:10. Despite the opinion that the Metro experience will improve when better apps exist, how is the Metro approach any better than the old one? Talking about full-screen apps in OS X, Tom Meritt says "I hate that stuff." If I don't want to run Internet Explorer full-screen, why would I want Metro? Please do a post about the entire platforn and the potential benefits of it, not just the Start screen. I like the title of this video: "The Start Menu is a Lie." Mary Jo Foley is right when she says that you need to answer the questions we have been asking. . Now I am officially protogonist lol, yesterday I installed windows 8 in ntfs formatted partition and with exactly same configuration PC this time I installed with protogon file system. The result was quite surprising. windows 8 with protogon file system way faster than ntfs formatted hard disk. I think this is huge achievement. @Brian Uphoff Two tiny and simple ideas for improving efficiency in Figure 12: 1. In Start Screen, when user searches something and there are no results for Apps, Windows should automatically switch to a system group that has results. But instead of this, Windows Force us to use a arrow key or mouse or finger to go to a group that contains some results. 2. When there are no results, instead of showing a blank page, clearly tell user that Windows couldn't find anything. Love what you're doing here. So glad the start button will actually have a usable function for me. Love the style, love the functionality, love the simplicity. It's going to be simple for beginners while supplying plenty of efficiencies and shortcuts for advanced users. Keep it up! your strategy in windows 8 is not to allow flash on the Full Screen IE9 app. But what is the alternative out there that I can use to be able to play video content using the IE9 app? Is there a way to change the metro interface color??? I'm not sure if you're aware of the Launchy search app for windows, which is a derivative of what was a great search app in OS X – QuickSilver. Its simplicity was in that you can have a quick keystroke to launch a search box right in the middle and then type away and then the search was gone. Your method seems overly complicated and jarring for the average user. Can't you imitate a simple method like that? Also, for those saying chill out, this is alpha, that's exactly why critical comments are valuable, to make sure things get refined and not left there when it goes into production. @Joao M Correia There would still be time to make minor changes before RTM. If there is not time then it can be released in a later service pack Microsoft's approach to Windows 8 features isn't much different than the approach to previous versions of Windows. They'll meet the vast majority of users needs (the 'sweet spot') and the little nit-picky things you don't like will be handled by 3rd parties. Or you can just adapt to Windows 8's subtleties and allow them to quickly become 2nd nature. MS will make some concessions but they won't go back. With the tooltip, no preview of content? Let a second or two of the video play or the audio file. OtherwiseI like the improvments! They just though add to the one issue I have. I use multi-window multitaksing on a large (>30") Full HD screen, how will you make it that multiple workspaces will be available in the metro interface with a mouse and keyboard? From what was shown, it could clearly do a bit of multitasking with the extra bits on the side, but haven't been able to do it with anything other than share. Possibly make a grid possible with four blocks which can have different apps swapped in and out when need be? They will simply be 4 windows running metro apps, shortcuts to zoom in on specific ones would be helpful as well, but being able to interface with 4 windows at once will be a step up from only one window constantly. First I want to thank you for this Blog and the way you communicate with us. I'm looking forward to what you are doing with Windows as a Touch-friedly Platform. You're doing great work there, but I think you should really think about what you are doing to the standard non-touch desktop experience. You talk about a touch-first design with no compromise, and a seamless experience, and that we don't ever have to see the standard Windows explorer if we don't want to and we can have a metro-only experience. Well, that's great for touch users, but what about the desktop user? How did we become second-class citizens of the Windows world? Why don't we get a seamless experience? Why do we have to make compromises? I understand that you are reaching for new platforms and new Users, but don't forget about the 350+ million existing Win7 users. I'm not saying that you should keep the old Search function. It worked fine for me, but as you pointed out there are ways to improve it. So go ahead and improve it, but do it in a way you would do it on a desktop platform. Windows 7 is so great, because it took all the good things from earlier windows version, got rid off the bad ones, and presents it all with a really nice and user-friendly interface that is a joy to use. Think about how you could patch-in a better search experience into Windows 7 and start from there. Why not just keep the basic functionality of the start menu, and when you start a search the width of the menu doubles, and there you have all the great things you came up with for the metro-search presented in an "Aero" style. So you would have all the benefit of the new search, but not break the experience for the Dektop user! To conclude my statement: Give the dektop users a SEAMLESS experience. Improve the search functionality, but keep the (option for) Aero design for non-touch devices. again lost my comment :C… ???? @johnd126 — my assumption is (and I hope I'm right) is that you don't need to know the exact literal name in order for search to work to find an application. There will be metadata that gets searched as well, including company name, suite name, and maybe other things. So if I search for "Microsoft", I'd expect Word, Excel, PowerPoint, Outlook, etc to pop up, along with all the other "Microsoft" apps I have installed. If this isn't true, then your point is very valid and a concern. But I think current search doesn't always require exact filename matches already, so I think it's pretty safe to say that you won't need to know the file name or "app name" to find your app. The folder or path info should probably be part of the searched metadata. I do think that the ability for apps to provide additional metadata to use for searching, so that the app can help control how discoverable it is, would be a good thing. @Microsoft Alvaro is right. We need to have a true discussion about Windows 8 rather than talking about whether or not the telemetry is correct. I am also curious to hear what you think of our suggestions. Yes, definitions, math, unit conversion, and emoji support in search. my friends like to use new emoticons on me, and Wikipedia is a pain in the ass to read that table. let my just type >.< in search, and have it pop up with cat face. 🙂 there is a *** ton of work to be done in Windows 8. if it ships like this, with less bugs, i won't use it, and just watch even more developers make games for iOS/Mac OS @ Alvaro (per SInofsky's keynote) in Windows 8, the desktop is treated like just another app. In my opinion, pulling up the Start screen will always be jarring until we get used to it, which for me, took about a week of using Windows 8 as my primary OS. Many have argued the addition of robust Metro style apps via the Windows Store will also ease the shock because we'll spend more time in a "Metro" environment. This makes sense. Switching from the Desktop to the Start screen will be just like switching from Metro IE10 or the forthcoming Mail/Calendar/Contacts Metro style apps etc to the Start screen. I doubt there's much MS can do to make such a big change seem like it isn't a big change. When IE9 got rid of the separate search box, I was upset and made it known on the IEBlog. I still want my separate search box back. The reason is that it provided a consistent context while browsing through results and following links, that allowed me to 1) know where I was, and 2) get back to the 'start' with one click, and 3) try the same search in another search engine with one click (well, click, drag, release). It also didn't pollute my address drop-down bar with transient search queries, pushing out other sites that I tended to rely on being there. Many of the complaints about the Start Screen seem to be in the same vein: loss of context. And this is loss of context in both directions. As noted, if you're trying to search for something you've been prompted to do on a web page, the moment you click search, suddenly you can't see the page to read off of it… you've lost context. And then once you've searched and clicked on something, you can't go back and refine the search or just click a new category, or whatever… the query and the results are lost. You start fresh each time. Again, loss of context. I think this is what people are actually referring to when talking about a 'jarring' experience and a 'loss of productivity'. Not the number of keystrokes required, but the loss of context and the cost of context switching (especially on bigger monitors). Some users might be 'freaked out' that their desktop is suddenly gone at first, while others might forget what they wanted or needed the moment it's out of sight. There are also minor "discoverability" issues. There are also siginfiicant "mouse-travel" issues, that go double for track-pad users. Initiating an experience in the lower-left corner that requires a focus-shift to the upper-right corner is just not going to fly for those users. It's fine for touch users, because the action is initiated on the right, and stays on the right. For keyboard users, it's less of an issue becasue there is no 'travel'. But mouse/track-pad users have a legitimate gripe here. So rather than concentrating on telemetry and heat-maps and click-counts in the next blog about this topic, how about concentrating on context, and on usage via the mouse and track-pad. You are a foul-mouthed ruthless kid. Need to learn some ethics how to talk in public. Stop barking and GTFOH. You don't like Windows, Xbox or anything made by Microsoft, then WTF you are doing here you miserable troll. B.I.T.C.H! BumbleBritches57, you better watch your tone before commenting. This is a common place to extend your suggestions and comments. You must respect the other audience and visitors of blogs and try to be civil. Though it seems you need to try very hard to reflect some good manners but it's mandatory for survival. LOL. watch my tone before commenting. you mean kiss MS's ass, and tell them they did a good job when they didn't do ***? lol. no. What is everybody complaining about? Windows 8 is looking great and the new Start Screen is beautiful and elegant. I can't wait to play minesweeper on it. @jimbrowski you're right Desktop it's now just an App; and if you don't invoke it the code wont be even loaded …. but you must agree with me that with the current software ecosystem; and the productivity programs that i don't imagine in Merto UI (Adobe Photoshop, Autocad; MATLab , Office, Custom Software; you name it) people will still be working on Desktop A LOT so there will be the case when you need launch Desktop and search together.. an hence the lost of context (jarring effect) Just try to be civil while commenting about the subject in hand. If you have some personal grudges, don't plague in here. @Microsoft, what's the ETA on Microsoft flight game? It's being a while. Kick some lazy aasses there. Also, please release the game on WP7! Would be fun windowsphone.uservoice.com/…/2296772-microsoft-flight-game-. Please provide us with a "Create Download" button. P.S. The idea of batch-files download option is inferred from Free Download Manager – FDM. IMO, it would be great to integrate the complete set of basic features of a download manager in IE (perhaps some advanced features like; download categories & P2P torrent support as well). Sorry, after using it for about week, I still don't like the start screen, and I returned to Windows 7. I don't like that you separated the "setting" and the "app" searches. I don't want to have to remember if an item is an app or a setting. I don't care what it is, I just want to launch the thing. Now, if I want to use Windows Update, I have to ask myself, is it a setting or an app? Then, I have to remember that I have to use Win+W to search it because it's a setting, then after pressing Win+W the desktop is replaced by the full screen thingy, then I can finally do the search, press enter, and instead of returning to the desktop where I have all my work, now the desktop is still hidden, and the Metro control panel is full screen, so I can't see any important changes on the desktop while there. Then realize that the Metro Windows Update is not powerful enough, so instead of having a link to the Desktop Windows Update on the Metro Windows Update, I have to scroll to the bottom of the Metro Control Panel, select More Settings, I am finally returned to the desktop, I am presented with the Desktop Control Panel, were you cannot find anything, because the Vista/Windows 7/Windows 8 Desktop control panel is not organized in a way that makes any sense. After about a minute you find the Desktop Windows Update under "System and Security", and you can finally launch it. How did this work in Windows 7? Press "Win", type "update", wait a few seconds, press down arrow 3 times to select "Windows Update" from the search results, press enter. No full screen transitions. It just works. It's beautiful. How could you redesign the Task Manager to make it so much better than the old one, then got it so wrong with the Metro Start Screen replacing the Desktop Start Menu? @ pmbAustin, you can just pull up the search charm in the desktop and you won't lose any context. in the Dev Preview hover in the left corner and click search or click Windows+c and choose search. A universal contact system that has a nice API for other programs to use would be a big deal for regular users. Using my iPad and my WP7, the two things I search for directly are Apps and Contacts. I don't generally search for e-mail, but contacts I search for all of the time on both WP7 and iPad. Just because i don't search for contacts on Win 7 doesn't mean that I don't want to. It is just that Win7 does not have a usable contacts system that is integrated into the applications I use (e.g. Thunderbird). Don't think, oh people don't use that, think "what if people and applications had access to a decent contacts system, would they search then?" or "If applications could integrate into search, one option would be contact management from different vendors." I assume MS is aware of this issue, but since I have time to spare… There's some odd behavior when launching a desktop control panel (settings) shortcut application after search. In fact, it may be solely "Settings" shortcuts that cause this. Clicking on a result prompts the desktop to "wipe in" on top of the previous state of the desktop. For example, I currently have my browser maximized with the taskbar at the bottom. After searching for "desk" and choosing "Change Desktop Background" I will briefly see a shot of my browser maximized in the background while another shot of my browser, taskbar, and the "Change Desktop Background" window all "wipe in." It's a bit messy. A lot of people are complaining about the Start Screen. I don't mind it, but I do have an issue with its implementation. I perceive most of my Win8 work would be done with desktop apps, not metro apps, with a lot of emphasis being switching between apps – something which I imagine will be common with other IT Pros and Devs. However, as soon as I click Start to launch a new program, it does an annoying animation and switches to the full screen Start Screen. This immediatly disctracts me from my current task and takes my entire world to the Start Screen. Then when I launch an app related to what I'm doing, it does another animation to get back to the desktop with the new app I launched. This is very distracting for my mental process. I think the full screen Start Screen is important for some scenarios (tablets, a large number of consumers), but expert users need a slightly different implementation. I'm not advcating having an option to revert to the legacy Start Menu, but some hybrid option. E.g. when in desktop and click Start, the Start Screen appears as a large window, leaving the taskbar visible and without distracting full screen animations (a bit like a very large Start Menu I spose). This allows the benefits of the Start Screen and live tiles, but would provide a better user interface transiition for expert Windows users who won't rely on Metro apps so much. @WindowsVista567 (fake, gray letters) I've had enough. Who do you think you are, anyway? Actually, I think in some cases I would prefer an invisible (100% transparency) Desktop Start Menu, instead of the Metro Start Screen. At least that would spare me of the full screen transitions. I could blindly type [Win],calc,[enter], and start a calculator without switching needlessly to a green screen. That's what I do anyway in Windows 7 for familiar applications. Mostly, I don't even look at the start menu anymore when I launch them with the keyboard. Furthermore, the new start screen is almost useless if I want to start multiple instances of an application, for example I sometimes need to make multiple screenshots for a web application. In windows 7 with my browser active I type [print screen],[win],mspaint,[Ctrl+V] to take the screenshot then[Alt+Tab] to return to the browser, click something in the web aplication, use again [print screen],[win],mspaint,[Ctrl+V],[Alt+Tab] to obtain a new screenshot in a new Paint instance, rinse and repeat. Then at the end I crop and save each screenshot. If I try the same in Windows 8, it works fine. But if I search it with "paint", instead of "mspaint", instead of opening multiple instances after each search/[enter], it just selects the existing paint instance from the previous launch. Why? Most people will search "paint", not "mspaint", and will not be able to open multiple instances. For other applications: if you search "notepad" [enter] it will just select an existing instance. If instead I search "notepad.exe" [enter] it will create a new instance at each search. And the same for "calc" vs "calc.exe". I don't like this. I want the default behaviour to be "open a new instance every time", like before. I wonder if this behaviour is by design or an accident 🙂 I know if I right click on the search result, select "advanced" then "run", it will always start a new instance, but I think this should be the default behaviour. I like that our feedback is read by MS, and sometimes changes are even made base on it (for example programs grouped in the Apps screen, or as MS put it "suites of apps are now organized in groups"). But until we are given the option to use the old Start Menu for the Deskop I think my Hitler video is still relevant: @Fake WindowsVista567 How could you possibly play Minesweeper on Windows Metro? Your comments continue to confuse me. Windows 8 is super! I love my mom, my dad and Microsoft to create the Windows 8. Please release it NAW! Time to watch spiderman (cartoon) Yay! I want some MOAR! the be unemployed after the release ? @Fake Commentator There's no room for comments like yours on this blog. Edited: WE be unemployed after the release ? spiderman cartoon? r u a 11yrs old kid? lololol!!! @one-way: how to revolutionize IE, this is an interesting idea. I hope they implement this feature so we don't need to use third party download manager apps. Moreover, @IETeam please make IE10 super duper so I dont need to install multiple browsers! @ C_barth Thanks for your feedback. Desktop apps have a slightly different visual treatment than Metro-Style apps. Desktop apps (e.g. Windows Explorer or Calc) have an app tile that uses the color of the Start Screen background. Metro-style apps have full-bleed photos, bigger icons on various color plates, and often show updates. Also, you can group apps however you like in the Start Screen. For example, you could move all of your desktop apps to one group. Why isn't it more like Spotlight? Why do I have to select Files, Settings, or Programs? Why doesn't it know what I want just straight up. Spotlight works so well at knowing that I mean a mouse setting if I type mouse and knowing that I want search for multisim in an engineering report for a class. Windows Search would be more powerful than Spotlight if it attempted to do what Spotlight does then can be quickly and optionally broken down into Files, Settings, or Programs if it's best guess isn't correct. Right now, you guys could learn a lot from Spotlight in OS X. First, I want to say that I love the work you all are doing with Windows 8 and can’t wait to see what the beta will be like. As with most things (especially a developer preview!), there is still much to be desired. All of this talk about the search charm got me thinking about the whole idea of two separate desktops and how they function differently, especially the search. I think the classic desktop and Start screen can co-exist together in a much smoother fashion by combing the two separate experiences into one. The main concept from the desktop that does not currently integrate with the Start screen is the taskbar, but I do not see this as much of an obstacle. In fact, combing some version of the taskbar could double as a way to close Metro-style applications. Here is a link to a picture of the Start screen that I have modified showing how a Windows 8 Metro-style taskbar and charms might appear:…/photostream The Start button is in the same position as Windows 7 and earlier versions so the user is immediately aware of what it does. In “desktop” mode, the taskbar and charms could stay permanently on the Start screen, while in “tablet” mode, they would only appear when swiped from the edge of the screen. Windows functions would use the bottom and left edge of the screen, while programs would use the right and top edges. When a desktop application is launched, the Start screen could fade out (or the tiles could disappear), leaving the taskbar and program as the center of attention.…/photostream Metro apps, being full screen, would not show the taskbar. When the user hovers the mouse over the start button, the charms menu appears.…/photostream Clicking the start button goes right back to the Start screen. Of course, many desktop applications could be open and function just as they do in Windows 7 with the Metro taskbar and faded Start screen (or maybe the tiles would just disappear). This effectively combines the classic desktop and metro style without a jarring transition between the two. As a bonus, Microsoft could even allow Metro apps to function in a windowed mode and display similar to the desktop apps, or allow users to pin their favorite apps to the taskbar permanently I hope you like my ideas. Thanks from reading. It is kind of fun to see how the dev team continue to push for MetroUI. In Sweden on many forums admins in large corporations reject the whole idea of Windows 8; MetroUI and ribbons. They don't want it, on either servers or clients. They do also say that if Windows 8 are shipped with the MetroUI they will not allow any upgrade to Windows 8, They will wait for Windows 9 to see if You have learned from Your failure with Windows 8. Maybe the dev team should start to look for another job, i doubt You will have any if You don't listen to Your customers. Why is it so hard to meet Your customers demands ? @xpclient, Hey what do you know, Recent Items is still there. It's not on by default though (not on any system I've used). I still think it's way more useful to add a search query for items modified today to the Explorer favorites. Jump lists are still more useful too. I really hope that Metro can be disabled completely. I have been loyal Windows user since 3.1, but it seems that Windows 7 will be last. @WindowsVista567 Please stop feeding the troll. We all know that he is not you. You are keeping him here by paying attention to him. Ignore him, and he'll go away. Speaking of search. Does it actually WORK? Windows vista and 7 has many many times given me "no items match your search" when i know that the search-phrase exists in a search-able file in an indexed location. I don't trust it at all anymore. I've set up a uservoice forum for expanding on the discussion here. Its at If you've got suggestions for improvements, post them there and see what others think. I think you have started out with the premise that reducing the number of keystrokes to perform a task is the goal for many Windows 8 tasks. I think this is a misguided approach. We could go back to Wordstar days where every function was just Ctrl+ 2 keys away, but was this easy, memorable or preferable to what we have today? Introducing more Winkey + combinations for the user is also just going to mean that those functions invoked by the users will be harder to remember and access and the 'simple' route to using them will not be used. Winkey + F for find is memorable. Winkey + (one of three options) is not memorable, especially by a layman trying to use Windows 8. I expect if you look at your telemetry on Winkey use maybe 2 or 3 of the combinations are used, out of how many possibilities, 20? Such a shame that email search has been removed as well. I often have written a note on something, say "banking" and can't remember where I stored it. Was it a banking.txt, in a folder called banking or stored as a draft email with the word banking in. Currently to find that I'd click start (well, middle click I use Classic Shell), type "banki", find the document I'm after in my email drafts. Anyway, about Windows 8 Aero. you guys should really look at Cloud7. i love it. because it's simple, and minimalist th05.deviantart.net/…/cloud7_2_9_6_by_bumblebritches57-d2v00o4.jpg @Jari, windowkey+d or clicking desktop-tile brings the desktop. Adding a key combo make you so annoy that you will leave using windows! This is insane.. Microsoft should give the option to turn it off but seriously you guys are too much. Current version of metro has number of shortcomings from accessibility perspective (especially for Keyboard+Mouse users). IMO, metro should be worked in such a way that it addresses the major concerns of most people rather than dropping the whole idea. Not even 1% of windows consumers are representing their comments about Metro thus far. But what power users? Would they appreciate this idea? Yet power-users also are the stakeholders of the ecosystem and their feedback should be incorporated. But why turning off the Metro is the only way? Why not make the metro versatile and so everyone become happy? Making lot of people happy is already done by introducing Metro and telling that its not even half cooked and more improvements are coming forth. But making everyone happy is impossibility because some people are blatantly trolling and some are single-bit they have fixed their mind on "Metro is bad" and will be that way even Microsoft evolves metro to a level where it meets all the usability and accessibility concerns. @Microsoft, choice is yours. Neutral people, who are not stunned by Apple or Google, welcomes the new ideas. But please make the metro more evolved to address usability and accessibility concerns which you will find in many valuable comments. –Summary of this post: The current version of metro is unacceptable. Microsoft can either give the option to turn off the metro OR make the metro in such a way that we don’t have the need of startmenu anymore. Either way most users will become happy. I feel sorry for trolls, single-bit or mindless people who don’t even have any tangible opinion. @Steven Sinofsky " The primary difference between the telemetry and a poll or survey is that the telemetry is millions upon millions of data points approaching a full census without any inherent bias." Not true. As has been pointed out to you MANY times, enterprise and business users are the Very groups likely to turn off your statistical reporting. You cannot rely on telemetry to support any of these decisions. Why do you think we are rejecting your work so strongly? Because we want to remain productive and this new search is anything but. All of your use cases do not come close to how I use search. I never use it find a program to launch, I use it to find files, and I want to view the results in the context of the programs I use, and I want multiple searches open at once, with the results displayed on the monitor of my choice in a window resized and positioned as I see fit. How does your start screen search fulfill any of those criteria? I can do all of the above trivially in XP and with a bit more effort in Vista/7 and its impossible in Windows 8 (Explorer windows do not count, I want the proper full blown search experience that you get from the Start Menu, not that the awful search you've implemented in Windows 8 Explorer). If you'd just drop this ridiculous Start Screen Metro nonesense all of these problems will go away. "We use telemetry to settle arguments over how a feature is used. " Apparently I'm the only person that uses search the way I describe? Not according to the feedback on this blog. Do you care about your business customers? Do you understand that Windows and Office are the two Microsoft cash cows and what business users like counts? " talk about how something is actually used as a fact, rather than an assertion." We've been giving you facts and clear decsriptions of how we use search (and the start menu) and I have not seen any of those (by any commentor) get acknowledged unless they say "Metro is great". We DO NOT WANT what you are offering. We are your customers. Are you listening? Do you understand? "Henry Ford said people would ask for a faster horse". Indeed, but with Windows 8 Developer Preview you are giving us a dumbed down, slower donkey. We want an improvement (if possible) to the very nice business saloon car that is Windows 7. Stephen Kellett post in on the money. Telemetry is failing miserably. Microsoft isnt addressing enterprise concerns on the Windows 8 UI. This is now the fourth (?) blog article on the Startscreen-Tile. Microsoft representatives have yet failed to address the most commom asked question. Will there be an easy way, official way, to disable the Metro UI entirely? Includin the Startscreen-tile? @Steven I ask you directly this 2 questions: 1 – Is there a way to Disable Metro UI entirely? Yes/No/I can't say now 2 – Is there a way to make the Start Menu not full screen or use the old Start Menu even if Metro is not disable? Yes/No/I can't say now will you answers the questions that all people want to listen, not some secondary question you are always using as an escape? You can keep answers to other questions, but almost all posts and further questions are a consequence of this 2 questions. You can even make more posts about the start menu, but the ultimate question to the user remains…. @jader3rd, I am talking about the Start Screen, which Microsoft is touting as the replacement for the Start Menu. Recent Items is only there in the Start Menu, not in the Start Screen. Or do you not understand the difference between the Start Menu and the Start Screen? @ Impar "Will there be an easy way, official way, to disable the Metro UI entirely? Including the Startscreen-tile?" that's the wrong question, I think. When push comes to shove MS may (for the short term) provide some customers the ability to disable Metro tiles and such things but there really is a lot of savvy to MS's basic decision to create an OS that can unify people's computing experience across new form factors (phone and tablet) with their desktop and laptop environment. I think that should be accepted by even people who dislike the Metro experience and instead of clamoring for its utter removal (MS can't ultimately do this because Metro is their best bet for winning the future) they should focus energy on how to make Win 8 a more productive OS. As I've said in several posts unifying the desktop with the Metro seems like a surefire approach. I think, from a memory and resources management perspective there's a need for having an architectural distinction between working in Metro vs desktop (people on a tablet can stay in Metro, not use any chrome apps and preserve loads of battery) but the move into desktop and back needn't be so jarring. So far the best mockup of how to accomplish this, I think, is described just a few posts above by Jerue: blogs.msdn.com/…/designing-search-for-the-start-screen.aspx That looks about exactly like the OS I imagine we need. Forward-looking, flexible enough to span all the devices, and yet without jarring jumps between computing modes with an easy way to provide most or even ALL of the functionality that we love in windows, like WINDOWS and taskbar and maybe even the full start menu atop the start screen, less need for this necessity of keyboard commands for even basic navigation, all of which would make it a productive environment and one that would require far less retraining. Pretty brilliant looking to me, kudos Jerue! That would really be "no compromises" by providing *everything* we love about the past windows perfectly integrated with the advances proposed in the metro interface. As a way to quickly jump to other searches, can users customize other shortcuts like Win+G to do a google search straight from windows search? or Ctrl+Alt+F to do a Facebook Search? Or, is there a way that we could use the search expressions to jump to facebook. For instance, if I wanted to search for a friend on facebook, it would be nice to just hit Win, and then start typing face:FriendName; or google:MSDNAA; or twitter:#SYTYCD; or even using the seraches already there– file:presentation.doc; or setting:power. For the love of god STOP CALLING IT APPS! I VOMIT AT THAT WORD!, IT'S AN UNPROFESSIONAL AND CHILDISH WORD! And btw worst idea to have the search field fill the whole screen, it will eat my RAM, so overall this is a BIG step in the wrong way! @ John Your comments are very "professional" and not "childish," at all. The use of all caps and exclamation marks after every sentence truly exemplify proper posting etiquette. /sarcasm Time for Sinofsky to lock down the comments on this one. @jimbrowski: Go play the "moderator" game somewhere else, John has a very valid point. All this silly language used is rather annoying. And the new Start In Your Face Menu/Search is totally childish and wrong. People better complain everything about Windows 8 right now! When it is still in pre-beta stage. Once it hits beta, Microsoft WILL NOT add any new features!! SAY RIGHT NOW, PEOPLE!! Thank you for making these blog posts. I completely disagree with the direction you're going, but it's a fascinating discussion, and I'm sure the Windows team is working very hard on this awful UI it intends to force on everyone (I mean that sincerely). Now, to the complaints: 1) I have a large, high-resolution monitor. This full-screen search shows a lot of results (if there are a lot of results), spread all across the screen and beyond. If what I want is buried in the middle, it takes my poor eyes a long time to scan the screen and find it. Is this a problem you recognize and intend to work on, or can I expect the usual "our telemetry supports this, it's the future, get used to it" response? 2) And speaking of full screen search, did I mention I have a large monitor? The only things I want fullscreen on it are movies and games, and half the time I don't want those to be fullscreen. What does your telemetry tell you to do about that? 3) What fool decided to show a screen of nothing when their are no app results for a search? lifehacker.com/…/windows-8s-metro-ui-isnt-very-good-without-touch-but-it-doesnt-really-matter…/mailbag-windows-8-developer-preview-140659 Why 90% of people know that I have a registry? 90% of people can not be software developers. I do not understand why people speak ill of my registry. I am very sad that all the progress I make are obscured by the complaints on my registry. My registry does not have anything that works but everyone complains about. All can be filled with garbage and everyone can build software to wipe. 90% of people install CCleaner which increases the number of my keys to let people delete other keys. The keys are my treasure and I want them all to me. The simplicity and cleanliness are not part of my logic. All this and out of my logic, but all this is possible. Why not allow people to provide feedback on my registry? and I use windows and I want to talk about my registry with the users of this site. @fake WindowsVista567 "Windows 8 is super! I love my mom, my dad and Microsoft to create the Windows 8. Please release it NAW! Time to watch spiderman (cartoon) Yay! I want some MOAR!" I'd just like to point out that I (the original WindowsVista567) did not post this. I'd appreciate it if you came up with your own name and didnt sully my good name and street reputation. Now back to some grandtheftauto and 50 cent. I ask all users to provide feedback on my registry or say their experience or thought. The Win8's new searching option is gonna rock the OS.. Each feature is enhancing its beauty.. developers rockzz All the kids wailing, whining & crying here about the new startscreen were the ones who cried, wailed & tugged at their parents on their first day to school. It took them time some time to realise that school was good, fun & for the better in the long run. This resistance to change is a sickness which is self-imposed & irrational & detrimental to mankind. I'm a power user, with POWER in C.A.P.S. I run applications (professionally) & games ranging from fruity loops to Visual studio, from Illustrator to Hex/Resource editors, from Crysis 2 to dangerous dave, from 3DS max to ms paint. I work with the registry, with theming, with development, with websites, with game design, with phone apps, with brand development, with video authoring, with analytical solutions & what not. & I love metro to its core. with all my heart. I'm just waiting for the brushing & polishing before it is unveiled me its full glory. It'll be like watching kelly brook on a beach rising out of the water in a great bikini. So, "a beautiful mind", care to address any of the actual criticisms? Your post contained nothing of substance and just served to call anyone who's actually taken the time to detail how the new Start Screen negatively impacts their workflow "children". Seems like you could do with a little more time past pubery yourself. @Steven Sinofsky I hope you guys are still reading these comments even though the article is a couple of days old. I love the direction Windows 8 is heading. That said, I have 2 suggestions for how to deal with the change-averse crowd. 1) Allow users to right-click the Start button to give them their precious classic Start Menu. 2) Allow users to adjust and set a default transparency to the Start Screen background. That way, a 100% transparency would be more of an overlay of tiles that would still allow some focus on what is at hand. Please reject any calls for the Start Menu to be inside a window. Windows are ugly to be honest, and a full screen app (or program for the sensitive) like Zune is beautiful. I want my computer to be efficient and powerful. I also want my computer and its programs to be beautiful. If I have to look at this thing all day long, I want it to be as pleasant as possible, and the more efficient you make things, the less time I have to spend looking at it. Please keep up the good work, and ignore the calls from anyone who classifies these changes as "dumbing down" the OS. Know that reasonable people understand that this process is making the experience better and faster for the vast majority of people. Continue your progress, and just remember to keep power users in mind with as much customization options as possible. @Fake WindowsVista567 What's wrong with you? Do you have that much fun spamming every post with fake comments in my name? Not only did I not post the Spider-Man comment, I also did not post the WindowsVista567 comment with gray letters that responded to it. The gray letters without the Windows Desktop picture and the references to "street reputation," "grandteftauto," and "50 cent" prove that that comment didn't come from me. My Windows Live account serves as authentication for this comment, and every WindowsVista567 comment not from this account is fake. @taboolexicon: I think your post says it all in respect to who they are targeting with the new Metro Full Screen UI: A user that wants a powerful computer but not more than one Window visible at the same time (?) A user that wants his UI to look beautiful so he does not have to spend too much time looking at it (?) A user who thinks all these new features are adding to the OS when all they give you are rectangles on a big flat full screen window (?) A user that cannot cope with the complexity of the current Windows but wants as much customization options as possible (?) Sorry but I don’t get it, are you having an argument with yourself or something? Anyway, I think that Microsoft has the same way of thinking as you lately, so you may have more chances of getting through to them than any of us. Please enhance Media Player by providing the audio boost and managing the subtitle web services so we can download subtitles within the player. Both of these features are available in k-lite media player classic. Also, I understand there are licensing issues with codecs but would be wonderful if you provide link to codecs catalog within the player, so people use your player rather than download those players which are bundled with the codec pack.. Finally, (like QuickTime) in Windows Live Movie Maker, please provide us frame level access while editing the video, so I can extract, delete and replace a frame from movie and besides WMV there must be other video formats while saving videos. (asf, avi, mpg… and since so forth!). Why can't some people here accept that all people DON'T like Windows 8 ? You are probably not involved in corporations where every single minute, or even second, are valuable money. Where productivity comes first. Stop whine about us who don't like what we see in Windows 8. We have the F same right to comment here as You have. Accept it or just get lost ! And to the Windows 8 team, why don't You answer us who don't agree with You ? Since some people seem to be having some issues posting proper comments, I'd like to remind everybody of the rules this blog has for posting good comments: blogs.msdn.com/…/556340.aspx blogs.msdn.com/…/about-this-blog-and-your-comments.aspx To the person who has posted multiple comments with my display name, let me remind you of two important parts of the second post: "We reserve the right to delete comments or otherwise edit what has been said. Things that will get comments edited or deleted: •Offensive or abusive language or behavior as determined by a community standard •Misrepresentation (i.e., claiming to be somebody you're not) — if you don't want to use your real name, that's fine, as long as your profile name isn't offensive, abusive, or misrepresentative" To the fake WindowsVista567, this applies to you, me, and everyone else who posts comments here. @Steven Sinofsky Are there any other Windows 8 blogs out there that I could read? Will there be a way to disable MetroUI entirely ? YES or NO 2nd try to add this comment ! Commenting here suck…. @Stefan this is a good question, and the answer should be yes, but then again this is the new Microsoft, where choice is a foreign language. Metro is god awful and I don't want any part of it on my DESKTOP PC. If I had a Tablet, then yes I could see this UI making sense. @WindowsVista567: Don’t ask for another blog from the same people, you will just get another story about telemetry driven rectangles in full screen mode. But if you insist, here is another more interesting blog: blogs.technet.com/…/microsoft-research-shows-some-fresh-thinking-on-nui-and-touch-interface.aspx I guess I will have to pass on the Windows 8 (Rectangle Edition) and wait for the Windows X (Balls Edition). Seriously now, these guys are demoing some very cool/amazing stuff, it is worth watching the video. Back to the main point though, I still want my “old” Windows as well as my “old” keyboard and “old” mouse when I am working…but hey these guys are creating something new, not just rectangles, so I would be willing to experiment with what they come up next. @mil I’m sorry you are having trouble understanding my post. I’ll see if I can help. 1) I’m in front of my computer for about 6 hours a day. 2) If I have to look at my computer all day, I want it to look nice. 3) I’d rather not look at my computer for 6 hours, so if making the OS more efficient can make my productivity increase, I may be able to shave minutes (or more) off of my time spent in front of it. The “no compromise” approach as I understand it would benefit the power user and the casual user in different ways. A power user should have a vast array of customization options available to him (now go back and read my two numbered requests). A casual user should not have to spend a lot of time trying to make his computer work. Windows 8 appears to be making a brilliant attempt at satisfying both user groups. You can have qualms with the Metro styling, and I’d say that everyone has his own personal style preferences, and I can understand why a person might not like it. Personally, I love the style of it. More than style, though, I can see that the Start Screen already gives me more functionality than the Start button does (for my usage). I have faster access to what I use most, quick search, and live tiles for information at a glance. I’m sure there’s more, but these are the things that are instant advantages to me over Windows 7. Again, I know that every user will not be satisfied with every change. That’s kinda how life works. I do, though, see a lot of hard work going into this OS, and from what I’ve seen so far, it looks like ti will be great. I can use it and customize it to my needs; the suggestions I recommended would help solve some of the major concerns from “power” users; and my parents could pick it up and use it more comfortably than they use a PC now. I hope this has helped you to understand my thoughts on the progress of this OS. @mil_ Stop complaining about the telemetry. It can be put to good use. Look at: blogs.msdn.com/jensenh for an example of what I want to see in a Windows 8 blog. @WindowsVista567: It was a joke m8, chill out 😉 @taboolexicon: I respect your thoughts and desires, but I found them conflicting. Anyway, I am in for change and I consider myself a power user since I do program on Windows for the past 20 years and I switched to the new version of Windows with every beta version. The problem I have is that I find Windows 8 useless on the desktop as long as it steals one of my monitors for the silly start menu/search. I find the whole unification of desktop and tablets effort to be a futile and it will damage Windows 8 sales. I have done my research by asking all users I can find, in my work, they all agree it is not the right answer, but I respect it may be the one for you. If they do not include the option to avoid this “new” Start Menu I will have to wait for Windows 9 or when they get it right, or just switch to another OS. @mil_ The "stop compaining about telemetry" part was really aimed at the entire set of commentators. I don't like Metro, but at the same time, I'm not the one starting these arguments about how "bad" Microsoft's telemetry is (and I really don't see anything wrong with the telemetry). Actually, I think that Windows 8 needs a UI blog from Jensen Harris. I liked the Office User Interface Blog because it was the thing that convinced me to buy Microsoft Office 2007. That, and the Story of the Ribbon, which Harris presented about a year after Office 2007 came out, really convinced me that the Ribbon was the best UI for programs like Microsoft Word. If there's anyone who could put these Windows 8 UI problems to rest, I think it would be him who would have that abiliy. In some ways, he seems like the Steve Jobs of Microsoft UI design. He always seems to know what's best for consumers, more than most designers (look at Corel Home Office's version of the Ribbon). The Office 2007 UI blog is clear, well-focused, and contains tons of information about the Office UI. Plus, that blog is specifically focused on the UI so there's less chance that, with that format, you will be eagerly waiting for the next UI post and find the title of the newest post to be "Reducing Runtime Memory in Windows 8," which has nothing to do with anything anyone's talking about for Windows 8. Plus, the Office 2007 UI blog feels like it was written by a person who really cares about what they do. This blog, by contrast, feels like the official Windows 8 news channel, with a different author for every post. I'd like to see the old Microsoft design mentality come back. @Steven Sinofsky: Thank you for responding to one of my comments. Unfortunately, it was one of my minor points. I’d rather look at the bigger issues. First, let me assuage you of any fears that I am adverse to change. I am an early adopter. For example, ten years ago, I switched from VB6 to .NET when .NET 1.0 was still in beta. Flash forward to something more recent, I switched from Windows Mobile to the iPhone as soon as I could, waited in line to get an iPad, and bought a Windows Phone 7 the day it came out. If anyone would have told me ten years ago (or even 5 years ago) that I would be waiting in line to buy an Apple product, I would have told them they were crazy. In any case, I can handle change just fine. That's not the issue. Second, it's not that I don't like Metro. I've been using my Samsung Focus for a year now and think Metro works great on a phone. Microsoft could have come out with a smart phone UI that simply copied Apple's iOS the way Google did with Android, but they didn't. Live Tiles are a great idea and Microsoft should be applauded for coming out with a UI that sets itself apart from its competitors. Third, it's not that I don't like Metro on a tablet. When I first saw the video by Jensen Harris back in June, I was blown away. I said to myself that my iPad was going to be the last Apple product I would buy, and proudly e-mailed links to the video to my friends, family and colleagues. For months, I waited in eager anticipation for the BUILD conference. I couldn't wait to get a hold of the development tools so I could start writing Win8 apps. But I'm not writing any. And I've stopped bragging to everyone about how great Windows 8 is. What happened? After the start of BUILD, it took about a week or so for reality to set in. Win8's Metro UI isn't just for tablets. Microsoft (whether they've said this directly or not) envisions Metro as the future of Windows on the desktop. This is a mistake and please allow me to explain why. I use my iPad for casual computing: surfing the web, checking my Facebook news feed, watching movies, etc. Touch screen UIs excel at the consumption of content. But whenever I want to do any real work – create content – I put down my iPad and use a desktop computer. Virtual keyboards are great for typing a short e-mail, but I wouldn't want to write a term paper on it. For that, I want a real keyboard and mouse. You don't have to take my word for it. Here's a pretty nice article on the difference between the consumption of content versus the creation of content. Steven, do you think you can take a few minutes to read it, please?…/can-an-ipad-replace-a-laptop-2011-edition I think that Microsoft has misunderstood the tablet market and why the touch-screen UI has been so successful.. For years, Microsoft made the mistake of selling tablets that used a UI optimized for a desktop. They sold poorly and it wasn’t until the iPad came out that tablets finally started selling. Today, Microsoft is making the same mistake but only in reverse. Instead of forcing a desktop UI onto a tablet, Microsoft is forcing a tablet UI onto a desktop. UIs optimized for touch screens don't replace UIs optimized for the keyboard and mouse any more than airplanes replaced automobiles. They both have their place. This is why so many of your customers are complaining. It’s not that we don’t like change. It’s because you’re putting a tablet UI where it doesn’t belong. Fortunately, what many of us are asking for shouldn’t be too difficult to implement from a technical standpoint. It’s really more of a question of will on the part of Microsoft. Yes, we can have one core OS for desktops and tablets, but the shells need to be different: – Metro UI for tablets – Aero UI for desktops Let those be the defaults and let users switch back and forth if they like. But they both need to be first-class citizens. A suggestion – try and experiment with turning the Apps list into formal Start Menus and implement them to be virtual Start Menu's. Could be likes this: An "apps folder" concept (better coupling with the Metro UI or tiles – instead of the current hybrid of old and new). A user. More details: Virtual Start Menu's – Turn the Apps list into supporting something like using tiles or a more first class part of the Metro UI – which may be in effect would mean virtual Start Menu's (however more secondary when on the formal list called Apps – while Start Menu remains primary). I think my comment about the portrant and landscape stuff fit better here – especially the last part reconsidering the Apps list – the result of going direct Search > Apps > [list] The Metro UI: Great work! Especially the automation of the layout. I'm looking forward to try and convey information through the titles too. A great property of the Metro UI. The shape of the titles almost makes them imaginary (no margens). Regarding the topic about "Designing the start menu" I think we need the new start menu and Metro UI (I think my comments on that topic concentrated on the deployment of programs and organization). Apps list or search (Apps information retrieval): term should go away and focus on the Metro UI instead … that is the tiles or visuals. May be the apps list should follow a similar idea as in the start menu to using tilesto present the more full complexity of what (apps) are formally available for the user – while the start screen then holds whats actually (virtually) available? May be the start screen with Metro UI versus apps list with Text holds a kind of impedeance mismatch (coupling problem) between old and new – i.e. the app launch system in Windows 8 preview is right now a hybrid with Start Screen (new Metro UI – note: the tiles) and then the Apps list with the legacy text stuff + grouping stuff. May be the Apps list should just go complete new of use tiles as well. No apps legacy list (text) – but something proposing tiles there as well. Like clusters of tiles that can be sorted or filtered (like stacked) differently i.e. depending on what somebody suggested as tags. The you could do your own like "domain" thing of tiles and just say uninstall to the lot of them. And gone they are – delegated to an uninstall process in the system. That would support the touch stuff as well nicely? The tile view could just be an alternate view to the current text suggestion in "Designing the Start Menu" with some grouping now kind of matching the legacy folder presentation. That could be the initial view but with added flexibility those tiles could be stacked, the stacks remembered and then you can just go an actually unfold … meaning ehhh … virtual Start Menu's? Then you could always "pin" a formal stack or formal Start Menu as primary … much similar too what you can do with multidisplay today – switching your primary display. I.e. when closing Visual Studio in a developer stack of programs the virtualisation of the Start Menu could fallback to the default display – either factory or user reset . It could be more advanced like having one program pinned in several stacks. So if I i.e. opened Word from a consumer stack or office stack of pinned programs that stack would become the Start Menu (if qualified, i.e. marked as something that have precendence or can be promoted to Start Menu) – and if I then start Visual Studio (and it has Word pinned as well and its container stack can be qualified to Start Menu) then i.e. a Dev stack be comes Start Menu. Or it could just be more virtual … like having Visual Studio or some other virtual Start Menu trigger as pinned on the default Start Menu – and when used its stack of tiles will be triggered to fill the Start Menu space from left to right – and filter everything out except activated (and suspended) processes. So an apps folder. The apps can be pinned in several stacks and the virtual Start Menu will always try and mix the screen according to the customization. Of course manual overrides – like positioning, marking forcing a tile to always be represented on the Start Menu … and so on. In the video the view keeps flashing between the desktop and entirely different start screen. It's dreadful the way you're completely taken out of the desktop and it's like you're using two different operating systems at the same time. The traditional start menu is far better because it keeps the user in the desktop at all times instead of having him switching rapidly between wildly different UIs. @Windows 8 Team, -I personally prefer Windows XP built-in search behaviour compared to Windows Vista or Windows 7, or even Windows Desktop Search 4.0 for XP. -In Windows XP, like other commenter(s) said, you could specify filters/options and then search right away. I always use "Advanced File Search" instead of that task-based/wizard-guided search, and of course, without that Search Assistant. -My favourite (and most important) feature is the content's search ("A word or phrase in the file"). It will search the given string within *ANY* file that is could parses, be it DOC, XLS, PPT, or VCF, VMG or even EXE or COM! This is available without the need for any specific iFilter installed. Windows Vista nor 7 cannot do this (disclaimer: DOCX/XLSX/PPTS is zip-compressed, hence cannot). I really missed this on my Vista Business x64 (I stores my contacts and messages from my good old Nokia 3120 in VCF and VMG formats respectively). -My point #1: STRING SEARCH within ANY file. Please make this available once again in Windows 8, or better, backport to Windows Vista/7. -Also, XP built-n search is FASTER compared to Vista (maybe even 7) for non-indexed items. Yes, default "Indexing Service" in XP is slower, but non-indexed search is always faster. We cannot index everything, can we? E.g. disk drives that aren't ours that are given/obtained for a short time. -My point #2: please make NON-INDEXED search faster, like it was in XP. -Another thing (point #3): please make the search automatically include partial name search, like in XP. In Windows Vista/7, we HAVE to put asterisk (*) in front of the subject/input string. -Anyway, keep up your good work and don't forget to reply my comment. 🙂 Regards. BTW Including support for a managed approach – Optimizing the APPX deployment descriptor to support consumption from the App Store The same goes for the lack of the deployment descriptor in the APPX Package format … coupling problem with reference to the intention of just pressing the Start Menu button and get as close to an actual view of what's relevant (including the intention of tiles converying data to info on the display). Introducing the classifcation in the deployment descriptor can help instrumentation in the system to infer which virtual Start menu or user concept the app should go to rather than cluttering the display (i.e quality over visibility/popularity … quality of "search"). The user could remap locations himself it he decides to use such a feature. Such builtin management could also help support distribution of programs … I guess a "business or consumer problem" can emerge and a bound on what you would install to prevent your single Start Menu or rather your usable display (what the new Start menu promotes) from being cluttered. That could be- despite every program in WinRT will be sandboxed technically for technical reliability. We also need the use case "reliability" in the distribution. I don't think users will fill their only display with a lot, lot of programs? But if virtual and support for kind of automated insertions it would become a lot easier to just research the App Store and go try – then you can always go back and test – and now, with classification, you would know what you downloaded (the taxonomy system would be a facility for automated user concepts instead of users having to switch their attention away from the App Store to organize, organize programs as they go. You can workflow the AppStore … just grapping all those Apps to try them out quickly. New Apps could go in a New Apps stack with respect to the suggestion on the Apps List. From here they could expire manually or automated on timeout either to be preserved or uninstalled. It would help collaborating with a lot of apps in the App Store. Right now it seems there is just going to be one single Start Menu for which all Apps will compete for visbility … A potent Windows 8 "Google" visibility over quality problem directly in the display (if you just consume programs – you will need to manage that in one single flat Start Menu – and flat equals complex if you consume to much in this case) @Ben H [MSFT] 18 Oct 2011 12:27 PM Wow, Windows 8 brings back the good old time, when we had to use the command line and a long list of key combinations below our keyboard. When will we get back this black screen ? Ctrl+Alt+Del is for Task Manager and most people have never used it or know about it. …. an additional comment on automation of apps classification in the UI: there may be indrect support through some technical properties to local resources in the AppX package format to interpret and infer matching user concepts (suggestion: virtual Start Menu's). But the functionality would still have to be implemeted. Still those properties do not refer directly to the application type ifself in the Cloud or whatever but local resources like global folder objects, file types or devices … and you can not be sure intentional user application type or category is fully reflected by such means or lack of declaration (i.e. no local resouces or just a printer capability). Cloud is network and different from local resource capability. So still lack of classification from my point of view. Please tell me if there is anything in that AppX format I have overlooked for such classification possibilities … I've looked here again: msdn.microsoft.com/…/br211473(v=VS.85).aspx At least the potential for application classification should be reservered in the new deployment format … i.e. as part of the idenity … the apps should not only have a "phenotype" or individual indentity but also one for feature similarity (genotype) … "a or more types" – i.e. hybrid or present in several categories in the AppStore. Those categories could be mapped directly to Players, News, Entertainment, Dev, Administration to keep it rather simple – and may be additionally Tool (if app just promoting one feature or less feature complete) Anyway may be new apps suites will become virtual through the WinRT share facilities making evering just a tool – but then – becomes the Start Menu just a big horisontally complicated menu of everything like and endless menu in Word for everything. Eh, I just installed a new feature only. What's a good way of organizing features on a display – an icon or tile for all features? This kind of goes back to smartphones as special purpose messaging devices constrating the number of features people will install. The answer: Must be virtualization in the Start Menu of all that stuff – the Start Menu becomes the general application like a stack of tiles (features?) for Java development. First of all to M$ keep up the good work. And dont listen to the people saying XP was better they are just Type S personalities who do not want to change. I have used every M$ product and between XP and windows 7 there is no contest for speed and efficiency more gets done faster in 7. Sure a couple things became harder but the overall improvements were very much in the positive direction. Anyhow the point here is how can we make the metro start menu be a no brainer win that is the goal isnt it. I am open to new things but I can also tell you when something is needed to make a new thing as good or better than the old thing. From using windows 8 this is what I miss. My problem with search in windows 8 and alot of stuff is that it is off to the right of the screen when the start menu is on the left. For most people this is just a huge travel distance that is less efficient. In windows 7 and vista search was the first thing closest to the start button now it is the furthest. I think by default they need to flip all that stuff to the other side of the screen. I think this would also make it easier for people to transition to windows 8 sinse it would almost seem like you were opening the start menu if you hit search or something. I also think when M$ releases windows 8 when you install it they need to ask you if you are using a touch screen tablet where primary input is fingers or a mouse and keyboard. Then they need to ask you if you prefer the start button on the left or right. Then this info is used to customize it per personal situation. Most people myself included are right handed and with small devices like phones and tablets it would make more sense to have the start menu on the right bottom corner and have all tiles mirrored along the vertical axis. In fact everything should flip I think. Also as others said I want to see the new start menu be able to show me which programs are open. I imagine it working similar to the windows 7 task bar except now it is 2D instead of 1D. Programs that are open have highlighted or raised tiles. And those tiles indicate how many windows are open. And if more than 1 is open then when you click the tile you get previews like windows 7 but they spread out in 2D instead of a single row. @ Steven Sinofsky, @ Brian If I am video chatting with someone on Skype and want to search for a file on my computer that I want to send him, I will have to leave the video behind and go to Metro to find what I want! Do you think that's an "efficient way of searching? You shoud enable "search" in the Metro as well as in the Desktop. Bah… another comment eaten, and I just realized it now. What is the timeout here? If I don't hit refresh right before posting, it gets eaten. At any rate, I'll try to reconstruct my original post: Are there any improvements to the indexer itself in Windows 8? The search feature in Vista/7 is great, but the indexer is competitively very slow. We had a situation where a 3rd party PDF software package installed its own PDF iFilter, and for some reason, over time it started corrupting the index for many users. We had to disable their iFilter and then manually delete and rebuild the index (rebuilding from the Indexer Control Panel wouldn't do it). We turned off all indexing sources except for Outlook, and it took over 3 days to reindex 80,000 items (~1 GB) on an otherwise idle, Core 2 Duo 2.4 GHz/4 GB RAM/7200 RPM drive desktop machine (over a weekend). This was typical performance for other users that had corrupted indexes. Will any improvements from other search properties (FAST, Bing, etc.) be incorporated? Likewise, while I can appreciate the "hands-off/maintenance-free" approach to the indexer, there is no logging ability whatsoever. Will this be addressed? I think at least an option to turn on some rudimentary logging/monitoring is a minimum. There is currently no way to know what files error out or are not indexed for other reasons. It would also be very appreciated if the limits of the indexer were documented somewhere–e.g., the fact that the indexer stops indexing at some point on larger files. At what point is it currently? I can't find current information online anywhere, but only some indirect discussion about this issue in the previous version along with some indication that the issue still existed in Vista and beyond (as a performance decision). After introducing the instant search feature as part of Windows, many people absolutely rely on the indexer. Please don't stop improving the indexing engine–it needs to be significantly more robust, performant, and well-documented not only to be competitive, but simply to meet its obligation as a critical function of the OS. It's frustrating when an online search of the entire web is a better experience than a simple search only of your own computer. If there are improvements in Windows 8 to the indexer, please let us know! 🙂 Just wonder if we have any improvement for Intl languages? In intl version, some feature/product names are left in English, so it cannot be searched when I use Korean to search it. Just wonder if we have any improvement for Intl languages? In intl version, some feature/product names are left in English, so it cannot be searched when I use Korean to search it. your comment stinks! WTF you are talking about anyway? CTRL+ALT+DEL is for options screen with task manager as an option and CTRL+SHIFT+ESC (which can be pressed by one hand) is for lanching Task manager since windows vista. R u still on XP? Similarly F3 and WindKey+F is for search. F3>Type query>Hit Enter and you get results. Also, in 7 and Vista you can search in start menu. Hit WindKey>type query and you get the results. All that you can do in Windows 8 with extra options. So, what is your point? You dont have any point. You lose… There there now, nobody loses anything. Maybe Microsoft will lose all their real desktop business customers eventually. But hey they will have rectangle happy customers instead, that love pressing random key combinations to compensate for the luck of common sense. Now, I am sure there must be a key comb. somewhere that will make this Metro UI crp go away…where is it, where is it… @Ryan: Something else is going on there, there is no way that Win7/Vista's indexer should take 3 days for a 1 GB Outlook OST. Mine is 2GB and well over 80,000 items – indexing it I would estimate at under an hour, if even that. This is an old 2GB Althon 64 X2 4800 PC with a slow HD. Now that being said, yes I agree – I would like to see some improvements in the low-level functionality of the indexer (or just reducing the Metro avalanche articles a tad:)). A particular annoyance is how search just breaks down outside of indexed areas. OSX's Spotlight doesn't need to distinguish between indexed vs. non-indexed, it just searches everything, and quickly. Now this can be a detriment in some cases, such as plugging in an external HD with lots of files – Spotlight will not allow you to perfor searches until it's finished and starts hitting the HD pretty hard (albeit I don't know this is with Lion). With Windows wildly varying use cases I can see where automatically "index everything" could be a disaster in some scenarios, so indexing file contents only by user command probably makes sense. However, I would like there to be an option to automatically search for all areas on your system by just searching for *file type* in the areas that are not indexed. I realize that the indexer will only index file types if it can't read the files contents, but that still requires you to index the specific folder manually. There are a ton of freeware file-type searchers out there which can comb a HD in seconds, I don't know what seach is doing outside of indexed areas but I've never understood just why it takes so long (Windows search in general before indexing had a deseved reputation of being very, very slow). I'm not sure this is a search indexer limitation, NTFS limitation, or both. I would be fantastic if I could set Explorer to show all hidden files and all OS-files, then just start typing and file that .dll hidden in AppDataLocal Usersetc etc.. Stop posting these copy and paste replies to every thread! If we get answers, we'll move on to other questions and issues. Stop posting these copy and paste rants to every thread then too! WinKey + W makes me SO happy! Awesome work! @pip25 Thank you! Your words are exactly what I needed to hear. How did I not notice your comment before? Glad to know you can tell the difference between me and the other guy. Extra! Extra! Read All About It!…/61455 We're not the only ones complaining about Windows Metro. I see your ZDNet link and raise you one……/6297893 Then I suggest you look at this… Then read this… youarenotsosmart.com/…/the-backfire-effect Please note the URL is no reflection on you… the content is the important factor overall. We can post links all day and try to convince each other that we are right. In the end, Microsoft is going to release what they collectively believe to be the right thing. You have the choice to use it… or not. @@WindowsVista567 I already knew about the "Great Debate" story before I posted my first comment, but I can point to another article with a free, no sign-in poll where 87% of voters think that Microsoft should offer a regular Start Menu. Apparently you haven't looked at the other two links… it doesn't matter how many links we post/find. There is always going to be a source that argues your point… or my point… or the other guys. I highly doubt if I *** loud enough you are going to change your mind. Just because Microsoft hasn't directly taken the time to respond to your exact post, doesn't mean they aren't aware of the concern. They don't owe you (or anyone else) anything. Feel free to keep posting your points over and over again, be the on topic or not. It's their choice if they want to directly aknowledge you (or anyone else). It's your choice to buy the software (or not) that they choose to create and sell. This isn't directed at you, but everyone as a whole…. keep up the same complaints if you feel the energy is worth your time. I'm done even trying to look the the comments sectiosn on these posts. @Microsoft Keep up the good work, and do whatever you think is right in the end. Let’s not forget that the Metro UI applications will only be available from the Windows Market place. So each time I press the Start button I am entering the virtual Windows Shop. That means that Microsoft is force feeding us their app store and they are threatening to cut us off from the desktop apps by treating it as a second class citizen. Sorry my friend but no argument can convince me (and a lot of other people) that when it comes to the desktop Windows 8.0 is just the new Windows 1.0 (as that article says)…only this time it is coming with prettier rectangles and a shop to go along. So I agree with WindowsVista567, he is at least one user that cares about Windows and their future on the desktop, instead of just going with the flow. At the end of the day if they want to “lock down” the tablet space, they are free to do as they like. But when they are ruining the desktop experience to herd us all towards the Metro UI direction (and eventually their shop), it doesn’t sound very nice and only a sheep would just follow. Finally they are making statements like “all the screens will be touch screens in the future”, come on, my next 60” TV that will replace my 52” will be a touch screen? Am I going to use my media center remote control, or I am going to be getting up to change channels by touching the screen. The same goes for my multi-monitor desktop setup. Am I going to be filling all my monitors with finger prints? Of course Microsoft will release what they thing is right for them, but we have every right to tell them it is not right for us. @Steven Sinofsky I have another Metro-related question, and comments are turned off on the other post so this is the best place I can find to ask this: Would you every try to convince us that Windows Media Center is better than Windows Media Player for listening to music on a daily basis? When run in full-screen mode, Media Center essentially is a Metro-style app, a few years ahead of its time. In many ways, Metro feels like an evolution of Media Center, not Windows. If Media Center isn't as good as Media Player for desktop use, how are Metro-style apps better than desktop apps? This is one of the big questions that everyone has been asking, phrased a little bit differently, and I would like to see this addressed in a future post. @AdamDesrosiers Thanks for the positive comments! I think Microsoft can implement both the tradition desktop and new Metro Start screen in a simple, unified, single UI. This would be much easier to use, intuitive, and more powerful for users of both the classic desktop and Metro Start screen. Not to mention, it gets rid of the need to have two separate charm bars in two different locations, which will only add to more confusion. Simplicity, while providing all the tools to power users, is the key to winning the user over. Having two separate desktops definitely does not meet that criteria. There is an implicit design rule evident in these posts that the user interface will not be modified based on touch versus mouse use, probably based on the notion that the two input methods are not an either/or proposition in practice (use). However, my view is that this rule should not be an absolute, as this subsequently denies any opportunities for specialization of the UI for different input methods, regardless of merit. Perhaps MSFT don't see any significant scope for specialization, which would be remarkable in itself (that such a convenient set of cooincidences should exist), or that MSFT are ignoring these opportunities for both the dual-input scenario and for the sake of marketing the line that one UI fits (almost) all device classes. In contrast, my idea here about presenting search results, includes changing the presentation dependent on the presence of a touchscreen (or user preference regarding UI optimization mode), and then optimzing each case in respect of this. For touchscreen: 1. Search results appear in details view down the left side of screen 2.1 For files, each result record includes these fields; 1) a number 2) file extension [max 4 chars*] 3) File name 4) Modified time in relative format 4) File size in MB.# [KB's are too small + i don't like commas in numbers] 2.2 For apps, divide results into groups based on vendor name. Use this name as a sub-header for each group. Each app result is displayed with 1) a number [following a continuous sequence that ignores sub-headers] 2) App name 3) Small icon. 2.3 For settings, follow the pattern for apps, except 'app name'='setting description'. 3. On right side of screen is an extended keypad. This keypad starts at bottom-right and continues up the screen. Above row 7, 8, 9 is 10, 11, 12, then 13, 14, 15 etc. 4. The numbers referred to @2.1|2-1) correspond to the numbers @3 5. As the user scrolls (if necessary) through the search results list, the file details change (obviously), but the file numbers – and the extended keypad – *do not*. The displayed numbers all remain static when scrolling occurs. So page three, row twelve of the search results is a file numbered 12, and the calender looking device on right has a just adequately sized tile/key labelled 12, that when touched, results in "file 12" opening. Assuming 24 records per page – for this example; file#12=record#60 * If extension > 4 chars, display as; abc~ (i'd prefer seeing the ext over icon, but of course could be both) The tiles (keypad keys) contain a small app icon, or a medium icon displayed as watermark, and also contain number ##. Scroll buttons go top and bottom of "keypad". For the mouse user, the keypad pane is simply replaced by a second pane of search results (as required). Important ideas are: 1. Result record shape (strips of left-aligned text) is optimized for scannability, and file/app/setting details follow an MSB -> LSB sequence. Activation points are optimized for touch (squares). Search result items in this post are by contrast doing both jobs, are therefore relatively large, thus requiring multiple columns. I doubt the public will accept this multi-column layout (especially compared to the simplicity of web search results). One column is best, two is stretching the friendship, but acceptable. More than two spells trouble. 2. (Although irrelevant to main concept,) date/time modified is replaced with time-since-modified, in appropriate formats (mins, hours, days, etc). This prevents the user having to perform in-head calculations and be aware of the date. 3. Jensen Harris's //build/ vid explains how users prefer to use the left and right edges, and especially the lower-left/right areas, as touch points. By separating the results from the touch points, and placing the touch points down the right edge (with top search result activated at bottom-right), my layout follows the principle described by Jensen – the method used in the DP does not. channel9.msdn.com/…/BPS-1004 4. Marina's post included this statement: "We know that remembering where something is located is much easier in a 2-dimensional space than in a 1-dimensional list. Our brains are naturally inclined to remember location, in addition to other properties like color and size." My layout draws on that insight more explicitly than the DP does – the search result on row x always corresponds to a tile in a fixed, and therefore learnable location. There is a consistent spatial relationship between row ## and tile ##. By contrast, how is the DP exploiting the insight referred to in MD's quote, for search results? Further points; 1) The search filters can go somewhere in the middle of screen – say, just to the left of the keypad – and hence be an extension of this 2) By adding a Ctrl key, user can select multiple files, and get an instant AQS equivalent query @search bar 3) the general principle could be used in any context that involves generating lists, including calendars. Finally, the new keyboard "shortcuts" are all well and good, but surely a new standard keyboard with several extra keys would be appropriate for the Metro era. I quoted 'shortcuts' because i think this is a misnomer when applied to keyboard sequences. F1 is a true shortcut, whereas stuff like WIN+F and CTRL+SHIFT+ENTER should only be referred to as a sequence. If you [MSFT] want to call these functions shortcuts, then market a keyboard that includes these functions as single keys. Anything less is a compromise. Well, this thing with covering the entire screen is just not working out for me. I have a 30'' screen at 2560×1600. There is a reason for having that big screen, multiple windows next to each other, not one app covering the entire screen leaving a ton of white space / not utilized space. That dog just wont hunt. It also feels ridiculous that I should have to wait for a animation/transition to complete before I can continue to do tasks such as launch a new app, find a setting or the like, with win7 it's just WIN key and search, bam, action. This thing with trying to get a touch interface into a regular keyboard/mouse computer just wont work, and as other has already mentioned, it's even more pain on a big screen with the right click menu appearing bottom right, that gives me a huge distance to travel with the mouse to be able to do a sub-action, this really has to be re-worked for keyboard/mouse usage. On another note, can't wait to play with win8 on a tablet. I watched the video twice but i can't believe what i am seeing! You searched for "calc" and "power options". Both things can easily be done from the win7-start menu today without choosing between different search options (did you really press Tab – Key Down – Return to navigate from the app-search to the settings-search? This is crazy!) . The most annoying thing in the world is to leave the desktop to see this full screen view of metro – oh my god this is really terrible. I use the search field in the start menu of win7 all the time and i allways get my results after a few keystrokes. Don't change things just for the sake of "change". I work with many programs like Visual Studio, SQL Management Studio, Eclipse, Remote Desktop, Photo Shop, Excel, … and none of those applications will ever work with a Metro interface. Metro is good for tablets and for users who surf the web, reading emails, viewing pictures and such things. Don't force working people in offices to work with a Metro interface. The "search" video is just funny, noone will enjoy this feature it is really bad. I always laughed about users who said "i will stay on Windows XP as long as possible" but now i start thinking "i will stay on Windows 7 as long as possible" 🙂 hahaha You're Windows search seems to be very fast and useful, but remember there are users who do not like sudden windows change or other type of animation. I suggest you to show right search panel firstly and after a fade in, the results panel. @Steven Sinofsky In the light of this new Windows UI, I've been reading Jensen Harris's old Office UI blog again, and I found an interesting link that took me to this, on another blog: blogs.msdn.com/…/464152.aspx It turns out that this post was written by none other than Steven Sinofsky! I have a question for you that has been bothering me for some time: In the blog post I linked to, you provided quotes from users who negatively described the GUI experience as compared to using MS-DOS. The quotes you pulled to describe GUI's were from users who thought that DOS was better for general computing than Windows. Today, we know how wrong this is, but is this how the Windows team sees Metro? Does the team think that Metro is to the GUI what the GUI was to DOS? Many users disagree with you on this point. From the perspective of many, Metro is as bad as the Office Assistant. I'm sure you've seen the comparisons that people have drawn between Metro and Microsoft Bob. Here's another question: what happens to Metro UI users who don't have touchscreens? You can't properly use a GUI without a mouse or trackpad, so how do you properly use a touch/Metro UI without a touchscreen? Do you expect that touchscreens on the desktop will become as common as mice? Oddly enough, it's still possible to comment on that post that is over six years old. However, it is directly related to this Windows 8 discussion and I would be interested in hearing your thoughs. My comment on that page is below all the PingBack comments. Any cool thing about the new UI is – it's immersive. But first – great with providing a way for more immersive apps but what the OS being more immersive itself? Take control panel, explorer and so on. They should use the immersive concept as well as the Start Menu. Again it's not just the Apps list. The problem is that the lack of Metro UI in Windows 8 itself – that is the OS without the factory apps on top uses legacy UI and a 3rd kind of web ui for the charm, i.e. control panel and so on. Where do you want to go? To go, you need to go there. That's the problen: The theme across the partial UI's for subsystems in the OS needs to be taken to Metro UI and possibly immersive as well. It will make the experience more complete and let the legacy be the part that "does not fit into the future". Right now, the immersive stuff only exist as far as the UI's are concerned – only from the Start Menu and up through any App in WinRT. Hopefully we will se an immersive Explorer using tiles and stuff … an App List with tiles – like I suggested above. The cool stuff … who said Windows should run on legacy displays? Have it virtual reality. With the immersive UI it could be projected instead and go beyond. Getting that virtual Start Menu, virtual Desk Top, virtual Home Screen or whatever … would allow for i.e. reuse with the location API. When come to the office it's "knows" go give me that screen. When I login in at the sports club on their PC and roams I get may sports Starts Menu for that place. At home it just starts the media center (when the Gallileo system is up and runing determining that PC within a meter or 2) The Start Menu or really the a launch system should be that flexibile always virtualizing. I.e. in the last use case there is just one apps so I don't need to see the Start Menu. BTW With "Metro UI" I'm referring exclusively to those tiles. They are the sun reflecting the perceived quality of Metro UI. The Tiles … More bricks – more immersiveness … more visuals blocks … less text. I.e. control panel, i.e. Apps List should be just stacks of tiles. If anybody don't like an immersive UI throw in an option or slider that can disable immersiveness partially and a warning when you loose the ability to run WinRT apps. Think games and players … Less text, more visuals (tiles or small dislays) … go with the concepts in the Start Menu and implement it. It needs to be everywhere, flexibile and useful. Then a new immersive UI in Windows 8 will stand out as the broad experience. Right now its only an exclusive experience limited to the Start Menu and any WinRT app on top. Control panel feels like an ActiveX upgrade … not Metro Tile stuff. It's up to you … may the app engine should be perceived as under the hood? So no priority for more immersive. But PC's are about files, right? So you are going to use the OS as well. So let's have it immersive as well – with them tile displays everywhere. … do tiles with the legacy taskbar as welll out of the box when immersive is on .. a guess is … you're already doeing it …? But let the application launch system (the "Start Menu") become more dynamic than its current state … a virtual launcher with triggers and all kinds of stuff possible. Same for the "formal Star Menu" the Apps List. If not please let there be an API (haven't looked through that properly) so it can be extended by 3rd parties. So basically design the launch system for variability or different configurations with option for triggers either external (manual) or internal (i.e. location … "Role is everything"). If only one app in a Start Menu no indirection. Make the Apps List just the formal Start Menu of all apps with tiles and use something like stacking to organize them and 2nd to i.e. support workflow on the stacks (batching). I think this would work much better for the apps list … like stacks of video tiles in media player. The tiles are a visual "media" presentation anyway. Have a button at the top of any instance of the Start Menu to go to the Apps List or formal Start Menu – i.e. a preset button next to the title Start Menu or that you can just press the Start Menu title and get the standard Metro context – allowing to configure or change your Start Menu instance. This is a development preview of Windows – so my development comments without knowing how much of this has already been discussed and given priorities. Another thing that could be done with a virtual Start Menu and inference: When there's is only one app in a virtual Start Menu and that instance of a Start Menu is active that could imply kiosk mode given the new immersive UI (full screen). It would make kiosk mode much easier to configure to some point: … just create a new application of Windows (virtual Start Menu) and put only one app there – i.e. Media Center, activate that menu and reboot. At the next login theres an option to do a new user for kiosk – based on the last activated instance of a windows application (Start Menu) was a singularity, one app applied to the infrastructure in this last case. A new must be created to proceed with auto-login. On additional reboots it can then just do the auto login and start the app directly in an exclusive mode (no explorer policy hacks – all automated). To disable later press the Start button lower left – and on reboot you get the Windows security screen to login. I.e. it would be easy to setup the machine to run Media Center immersively as kiosk for consumers. Virtual Start Menu's – are like the Windows Phone's "super" tiles … It's all about bringing real value to the business and experience of launching applications – not just claiming technical effectiveness like shortening mouse movements in a new Start Menu. With Virtual Start Menus we would get a different experince launching apps since the "launching experience" itself would simulate data-driven – like using the People super-tile on the Windows Phone aggregating different coupled services below – at least from a use perspective. Saying that, the Metro UI on the windows phone is not considered to be just another application launcher but data-driven trough the tiles. I think the tiles reflecting functionality or app icons in the new Windows Start Menu contradicts the frontpage idea in the Phones UI – at least initially since every app in the current Windows frontpage will have their own tile and complicate the interface. So again another point for making virtual Start Menu – or the notion of super-tiles – bascially supporting the transition in Windows to the data-driven tile idea in the original Metro UI from the phone. On one possible migration path: in the future Windows could have those basic tiles like a graphics tile (similar to the idea of the Phones People tile) – you hit it … and it virtualizes all kind of services (or apps) building a virtual UI for using WinRT cloud apps all each doing one thing or 2 with graphics. Much like MS Office itself is just a collecting of objects with different UI's and workflows. An aggregated UI like the People tile in the Windows Phone is reflecting a real Cloud app and the basic tile idea. The user value of that idea is not yet represented in the use of new launch systems default page. @WindowsVista567 — Many people disagree with something that I did not say? So is it "process is everything" ? ;o) The current focus on IT to deliver effective workflows focused on output-value for users. So is launch PIM and initiating workflow events? Is the Windows Phone People tile really a "super-file" tile?Then what about PC's and files. Chrome OS will support files – even though they initially said it's all web. Windows 8 says PC's are much about files? Then what about launch of files? Should I pin a folder in the Start Menu? Will I have to launch Word first to open the office workspace? On the Windows Phone I open the People workspace to deal with the People? Will Windows 8 be like that? Opening a global object like People on the Phone? Opening a global object like Documents on Windows? The great thing about the PC is we get to concentrate on the data. No margins. On the Phones it would mean – I go to the gps data and say – I want to do this with that data – and choose a software feature (the app). Only I can usually not do that on a phone because they are provisioned by the Telcos or other interest. So Is it really about the user interface or is it really about the bureacracy (deals)? But that is using the data. You can build an experience around using the data – i.e. a device embedding the data. But it usually means provisioning. Like a TomTom navigator. Or an iPhone. Or a Windows Phone. People want to use data. One thing is the popularity of VLC. Why – because they go and double click that video file and it comes on display. But data first. The point is, when evaluating users it's incredible how fast they learn when interested – and harddisk sales proove the point. Every person below age 40 can do that now including the deployment. But the visibility (popularity) of something like VLC is based on browsing the data first. Windows works that way – and I know it will keep working that way. Data is the road to every use. My point here is … get the concept of data first into the Start Menu – the desktop, explorer … data or files first. I.e. let's have the People tile there. Using the legacy UI – let's have a folder in the namespace like documents, videos, sound named People. And so on … more global objects (and similar capabilities to be declared by supporting WinRT apps) Also do a Movies global object i.e. contained inside the videos global object. Have WinRT capability and when you hit the Movies tile … and supporting provisioning apps will be there to let you order a movie. I.e. you could basically aggregrate any movie offer in World into the UI of the movies tile. The users wants data. Providers may want their own app icon and control the user experience – it's the challenge of not only the original idea of hypermedia but also inherit to the cloud and orchestration of similarity between services in portals. But providers can still do that – provide their own UI or HTMl5 web-page in an app. Like on the Windows Phone – the user can drag that app icon onto the front (Start Menu) as a tile. With the virtual Start Menu suggested, coupling with the concept of a super tile – you could actually construct your own kind of "global object" with those provisoned movie apps running as tiles inside the same view – similar to portlets. However in view only – it would be like portlet mapping only – without both data integration through global objects and without functional integration through suoer-tiles – that a global object reflected by a super-tile for that application would help facilitate. Anyway the user will decide – and with more global objects as tiles the WinRT app can be integrated into the experience anyway the users decides to access the data offered. Also third parties could be allowed to declare a new capability in terms of a new global object or namespace – to support specialized integration within apps through i.e. one tile originating from one creative app – and extended by others. All this perspective also reflects – in any case, what frontends will mean to the socalled webpages in the hyper world eventually. What's the host for UI? We are just at the begining … webpages is a transition. Like wordprocessing was more rich than typewriting. And frontends are virtual too. They don't exist before you use them – they are nowhere, but can be anywhere when observed (accessed). It will be that way eventually. Real quantum. And first class usable when just expressing a conceptual solution like a Peoples tile or Movies tile. In some ways this resembles what UDDI set out to do – but more constructive. Instead of making start menu or app as a search give us simplified app for start menu items and imp please give us simple way to shut down These posts are getting too long, so let’s summarize the main points here and see if I got it right. From all these blogs and relevant postings Microsoft is arguing the following points: 1. All screens will be “touch enabled” in the future (they said so in a build video too) and that implies you will be touching all your screens instead of using the mouse. 2. Metro UI is the “evolution” of Windows and the new way of interacting with the operating system. 3. The current classic Windows is too complicated for the users. 4. Productivity efficiencies are to be found when you have one or two only visible applications at any given time. 5. Full screen on the current action (e.g. search) is what users want and it will make them more efficient. 6. Memorizing lots of key combinations will solve any deficiencies of the new approach. 7. The classic Windows looks ugly where the Metro style is so modern and pretty. 8. The new paradigm is applicable to everything and scales well from phones, to tablets, to laptops and up to desktops. 9. Icons are not good anymore because text in rectangles is so much better to convey information. 10. All these findings are backed by telemetry data and can be quantified so there is no argument about. Arguments against all the above points are scattered around the forum, but the only thing I would say is that the Metro UI and the current Windows UI (desktop) are not the same.. @Steven Sinofsky Is that what I said? That didn't come out quite right. I meant that it is impled in everything the team has done that you see Metro as replacing the desktop, and the desktop in Windows 8 is provided only as a means for backward compatibility. In other words, you think that Metro is the future and that the desktop is the past. Am I right? Going back to the original question… do you see Metro as being to the GUI what the GUI was to DOS, yes or no? @mil_ "These posts are getting too long…" With respect to what? The attention span of the average reader? These are technical posts about difficult and complex subjects. The posts are as long as they need to be, given the content, and in some cases even the longer posts are not enough, so will have to be continued in later posts. Really, if you find the posts too long, then you're on the wrong blog. 1. "All screens will be “touch enabled” in the future (they said so in a build video too) and that implies you will be touching all your screens instead of using the mouse." All screens in the future will be touchscreens, means … all future screens will be touchscreens – it does not mean one, two or three other things, including anything about the fate of the mouse. The Metro-related post authors and Steven Sinofsky have made clear that touch and mouse are not, and should not be regarded as an either/or proposition. There is no rule that says you can't plug a mouse into a touch-enabled system. Jensen Harris @//build/ made clear the mouse was the most precise input method available and ideal for apps like Photoshop. For MSFT to predict the death of the mouse in favor of touch would be tantamount to predicting the demise of Photoshop. Haven't heard MSFT make that prediction, implied or not – have you? 2. "Metro UI is the “evolution” of Windows and the new way of interacting with the operating system." This is correct except that 'evolution' implies gradual change – whereas Metro should be seen as more of a revolution than simply contributing to gradual change – it's a clean break from the past. If 'evolution' were the right word, MSFT would be calling the new sub-system WinET, rather than WinRT. Besides, a mere evolution wouldn't be causing all this fuss 🙂 3. "The current classic Windows is too complicated for the users." More or less correct – for some users. Case in point; my dad knows all about Excel and Outlook, but ask him where he saves his files, or to copy a file to a UFD, and he has no idea. Many users are like this – they can use their apps ok but anything relating to Explorer or CPLs or basic admin tasks is totally alien to them. You have to stay aware of this intermediate/middle-of-the-bell-curve type user that is more sophisticated than the casual web browser but still struggles with some of the more abstract stuff, even things like drive letters and nested folders. Remember also that most so-called power users grew up in the era of/or have had lots of experience with command-line interfaces, which more or less force the user to understand this and other lower-level stuff, so the general problem is only likely to worsen in a relative and absolute sense. Furthermore, it's not just a matter of being "too complicated" – it's simply an issue of maximizing ease-of-use. That's a laudable goal, and is being achieved not just by designing with touch in mind, but with several other major design principles, most of which were covered in the "too long" post by Marina Dukhon. Commenters like WindowsVista567 who say things such as "No amount of extra scrollbars, corner menus, or right-click UI's will change the fact that Metro was designed for touch and converted for mice and keyboards" are wrong. Metro wasn't designed "for touch" – it was designed *for users*. Anyone who says they agree with that last quote without offering evidence in support is talking out of the wrong end of their bodies. 4. "Productivity efficiencies are to be found when you have one or two only visible applications at any given time." Many commenters have ignored the benefits of running apps fullscreen. Specifically they have focused on a perceived or anticipated loss of inter-app productivity or workflow, but have ignored the *intra*-app productivity benefits of fullscreen, chromeless, "immersive" UIs – which offer a distraction-free, maximum pixel work environment. Also, as i pointed out @ blogs.msdn.com/…/reflecting-on-your-comments-on-the-start-screen.aspx – the belief that tiles/groups *within* Start won't eventually be able to display first-class app content is incorrect. Instead, believe the evidence to the contrary, and don't wait for some VIP to tell you what you can read/see with your own eyes. 5. "Full screen on the current action (e.g. search) is what users want and it will make them more efficient." It will make them more efficient, but whether it is what they want remains to be seen, but ultimately irrelevant. As Steve Jobs said – "A lot of times, people don't know what they want until you show it to them." 6. "Memorizing lots of key combinations will solve any deficiencies of the new approach." Presumably you say the same about Ctrl-C, Ctrl-V, Win-F, Win-L and all other existing key combinations? What makes key-combos features for Desktop, but band-aids for Metro? Regardless of the environment, it will always be true that having single keystroke functions is preferable to key-combinations, and MSFT fanboys should be pushing for all new keyboards ("Metroboards"?) to include functions like Cut, Copy, Paste, and Win-W as single key options. 7. "The classic Windows looks ugly where the Metro style is so modern and pretty." MSFT have not called the Desktop environment ugly. Have you got a quote or two to back up that claim? This is subjective stuff, however it would be fair to say that Metro is not yet deserving of any beauty awards, but we are right at the beginning of the Metro era. Be patient like i know you were with early versions of Windows. 8. "The new paradigm is applicable to everything and scales well from phones, to tablets, to laptops and up to desktops." If Win8 runs ok in 1GB RAM, and phones are produced with 1GB RAM or more, then i guess that claim would be correct in a resources sense – but MSFT have a phone-specific OS, so we can jump to the next class/size of devices anyway, unless you want to define the new paradigm as referring to little more than "designed for touch", which would be far from complete. So which classes of device don't you think Win8+ will be suitable for, or are you arguing against the notion of OS scalability? 9. "Icons are not good anymore because text in rectangles is so much better to convey information." That's just a false dichotomy. Text in tiles has not superseeded icons, it complements them – at the very least. Also, how would you indicate things like # of unread emails or the weather using only icons? Even disregarding stuff like live data, icons and text have always been used in combination, rather than as competing substitutes. Putting icons and text into shapes called tiles hasn't changed the situation one bit. 10. "All these findings are backed by telemetry data and can be quantified so there is no argument about." That's a big claim on your behalf, and again, if you can't back it up with quotes or citations i'll accuse you of making things up as you go. What i've found interesting about the commentary on telemetery is this – people only *** about and misrepresent the use of telemetary when the end result or new feature is not to their liking. In the case of the new Task Manager, which was explicitly designed using telemetary data as a guide, not a single commenter on the TM post has so far argued against the use of telemetary in that design, because *they like the outcome*. The same folk will whine incessantly about the use of telemetary when they *don't* like the outcome. Hypocrites, every one of them. ." Who said anything about replacement? Please watch or re-watch Jensen Harris's //build/ presentation. Metro style apps are particularly suitable for tasks that work with chromeless "windows". Other, heavily chromed apps (like Photoshop) still have an important place and will continue to be supported. Is that too difficult to understand? I guess if i had to condense my criticism of all these points and most of the other arguments against Metro i've heard repeated endlessly, into a single phrase, it would be; it's more complicated than that. More generally, i think a lot of you guys (and girls) have made up your minds about WinRT/Metro far too prematurely. There is a long way to go and lots of features and refinements to be added. Be patient, and perhaps take heed of this Bill Gates quote – "Most people overestimate what they can do in one year and underestimate what they can do in ten years." i hope microsoft will just declare this is tablet OS and not design for desktop. So i can use it the most happily with my tablet. let it be optional for desktop (if they want to install it, it is still supported). So with this desktop user can keep quite and stop complaining. there is nothing wrong with windows 7, desktop user can still wait for microsoft to release their next gen os for desktop ( wonder what it will looks though, since peoples seem reluctant for any changes in UI). there is no point to release windows 8 for desktop with removal of all metro style features, since its not much different to windows 7 anyway. @Drewfus: Yes, these posts are too long for the intended audience. We are talking about full screen Metro UI users, no time (or means) to scroll or resize. Either say what you want within a tweet or don’t say it at all 😉 Now before you go writing another long reply, I was just kidding, don’t get this previous sentence seriously, it was a joke. Of course we need long posts to explain all these arguments for/against such complex features. Man, your long posts are infectious…here is one from me and although I don’t disagree with your posting that much, I would like to explain some of my points better. But first let us me make a few things clear. I am only referring to the Metro UI and not the WinRT. So far I like WinRT and I think it is a step to the right direction. When I am referring to “scaling”, I mean the Metro UI and not the kernel of the OS. That is a subject on its own and so far Microsoft is doing a fantastic job with the kernel. No complains whatsoever. “Jensen Harris @//build/ made clear the mouse was the most precise input method available and ideal for apps like Photoshop.” Yes I know that I can still use Photoshop, Visual Studio etc on the desktop, then why do I have to be jumping to the full Metro UI every time I want the start menu? He did mentioned on the given video that all the screens in the future will be touch enabled, like it was something that was missing from my workflow, i.e. replace the mouse with touch. Touch is not relevant to my day to day work at all. “whereas Metro should be seen as more of a revolution than simply contributing to gradual change – it's a clean break from the past.” Metro UI (not WinRT) cannot be either evolution or revolution because it is not directly comparable with desktop Windows. Two different paradigms of working with applications. Break from the past like what? So..we are not going to be using computers for work in the future? “Metro wasn't designed "for touch" – it was designed *for users*.” Hmm, yes you are right in the way you defined the broad spectrum of “users”. So I cannot disagree with this argument, the only thing I can add is that it was not designed for the existing desktop users that use computers to produce and not always consume content. “Many commenters have ignored the benefits of running apps fullscreen. Specifically they have focused on a perceived or anticipated loss of inter-app productivity or workflow, but have ignored the *intra*-app productivity benefits of fullscreen, chromeless, "immersive" UIs” I won’t disagree completely on that point because it depends on the user and the given workflow. It definitely does not match my requirements (or anybody at my workplace) but let’s see what people make of it in the future. “It will make them more efficient, but whether it is what they want remains to be seen, but ultimately irrelevant.” makes key-combos features for Desktop, but band-aids for Metro?” The problem is that I found myself learning more about key combinations reading about Metro UI than all my life using the Windows desktop. What makes it a band aid is the fact that this new UI is supposed to be “perfect” for tablets, yet we are resorting to key combs. “This is subjective stuff, however it would be fair to say that Metro is not yet deserving of any beauty awards, but we are right at the beginning of the Metro era. Be patient like i know you were with early versions of Windows.” Yes, look at the new task manager, it is pretty (I can say that). The problem of course is that this is WinRT and not Metro UI but they are confusing the two (intentionally?). “So which classes of device don't you think Win8+ will be suitable for, or are you arguing against the notion of OS scalability?” As I said I am referring to the Metro UI and I find it unusable in desktop environments (for people who create content, just so we get the right user definition here). Working on a Metro UI environment is counterproductive as far as my workflows are concerned. I installed Windows 8 and used it on my desktop before I come to that conclusion. Remaining comments: The main point about all these issues is yes telemetry data sucks when trying to design a UI because successful UI design is not something you can easily quantify. UI design is a form of art and art has a lot of interpretations. Yep, the new task manager looks cool and does provide extra functionality. Does it solves all the problems indicated by the telemetry data, I don’t care, I like it as a developer it does make my life easier. Do I like the Metro UI, again I don’t care what the telemetry data says it does make my work life difficult so I don’t like it on my desktop. If as you say we have made our mind prematurely (and again let’s keep the conversation on the Metro UI and not WinRT) then we will be complaining only about features that are missing and not about the fact that they are polluting the desktop UI with tablet features. A full screen search window is not an unrefined feature, no amount of refinement will make it “not full screen” because it is “full screen” to start with. Microsoft took upon them the quest of unifying the desktop and the tablet space (and everything in between), one UI (Metro) to rule them all. In the process, they are giving me (a developer with decades of experience) the same UI as they are giving to my mother, a 65 year old lady that she does use Word, PowerPoint and the browser to perform 99% of her tasks. Sorry my friend, but something is seriously wrong here, or just Microsoft has another magic brush to paint the future with. Based on past history, I will stay clear of that as well because my guess is that it is going to be another “I told you so” moment. So to precise the notion of tiles in the Metro UI and the namespaces in legacy Windows – the global data objects or namespace containers and their functional reflection in "super" tiles (like the People "super" tile) would reflect support for a domain (application domains). So support for different domains woould be facilitated by support for variability in the launch system. The launch system is the basic delegate in Windows holding the responsibility for what the application infrastructure – namely Windows itself – is actually going to be used for, what will be run right now. One might argue there is just a need for one concrete (single instance) of the launch object (the current one and only Start Menu). However, that argument would be contradicted by use of roaming in the Cloud – the going to be default Windows 8 consumer experience – really the use of the Cloud itself: mobile use/mobility/anywhere. The use of the application infrastructure Windows will follow the user – the mobility, rather than the device (the idea of having a device experince like a GPS navigator – and i.e. just one single menu purposing the device. However with roaming in Windows 8 and virtual Start Menu you could do that as well). So the devices responsibility being a singular user expirence are weakening fast. The devices are become more imaginery or limitless. I.e. the IPod almost instantly became the IPhone (the IPod was really about ITumes and Music bureaucracy to generate sales of IPods). The iPhone became an IPad. The IPad becomes a PC (IPad + Desktop stand + keyboard ). The Android or popular Linux application infrastructure device has Home Screens for the different possbile uses. So its hard to follow the *BS* in the media that the PC is dead. PC's are visibly (popular) referencing Microsoft Windows. However, the fact is PC's are everything "Intel". And Intel are growing. Initially x86 BSD and Linux came around. Apple went "PC" with Intel and BSD. Android went PC with Linux. It's really Open Source PC platforms crossing the chasm growing into the PC market (Novell tried to do that with SUSE – but Google is better at that – selling a "PC", not just Linux) – i.e. even their form factor is growing into real PC's – adding what's missing. Those devices are not getting smaller. They are getting bigger awhile more virtual, i.e. with touch you can take the flat display with you. The devices are virtualized more and more – and the user context (for instance the location) will determine what is valuable (effective) to have in the actual Start Menu at that moment. Next is the realization of virtual reality like you could project or video map the UI onto a surface and natural interfaces like machine vision interaction (like kinnect). Then you would not need a display – but a highly efficient LED lamp inside the "PC" (the "Phone") and projecting from behind the user the camera could do that spatial user interaction thing like Minority Report … the future of a "Pocket PC". So great with a new launch UI – but release it from the device context. In my view device virtualization and everything is a PC (Windows, Linux (Android), MacOS (BSD)) is just yet another reason the launch object can not be singular and attached to the device context. The launch object (Start Menu) is really virtual and follows the users movement across dimensions such as location, time and so on. That completely macthes and couples with the new support and default consumer experience in Windows 8 for moving in those dimensions ("roaming") – completetly device independent. @Computermensch: Interesting argument about roaming, user profile and non- single use devices. As far as common, “content consuming users” are concerned I will have to agree with your points and Windows 8 Metro UI does answer some of these requirements. Indeed it does present the user with a common environment that does not seem foreign moving form device to device. On the other hand, are we not doing (in UI terms) what Java has claimed all these years, i.e. write once, run everywhere? This by the way was a misleading statement, you will never write an application the same way if you are targeting a server or a desktop or a phone environment unless of course you are not a very talented developer or you simply don’t care. I still cannot buy the argument that we do have to treat every user as a simpleton that cannot deal with a change of UI when moving from some limited capabilities device (e.g. GPS, Phone etc) to a full blown desktop with 3 monitors, 16GB of memory and 2 graphics cards. The UI should transform to take advantage of the extended capabilities of device I am using, not having to simulate the lowest common denominator just so the user is not “offended” by the added functionality. When I am moving from one device to another I do so because that device has something different to offer me. I cannot be convinced that a 60” TV screen should have the same UI as the Windows Phone 7, or that having three monitors connected to my desktop does not present some very interesting opportunities for a better interface than a tablet/phone one. I don’t want device independence; I want Microsoft to offer me the best UI they can come up with for each of the devices based on form factor and other features. @Mil Yes, I agree with you too.. That's why I want the virtual launch system. Then you can do exactly what you want – i.e. also write an app with an immersive UI that just fits your context – i.e some device, some server. I also agree with you the users are more advanced – they are not simpletons, i.e. my former VLC argument. I.e. like your Java argument about the need for different UI's depending on i.e. device context – desktop, server. I also agree with that. That's why I want virtualization in the launch system. Then at least the user can just switch the UI based on i.e. device dependence. With the virtual start menu and possible use of machine ID or geo location – for a media center frontend app the user could for instance set a launch object on workstation to hold only that app, activate the launch object (this Start Menu) as default – and the PC would default to start immersively as a Media Center. On the Server the user could set another app or the same (depending on support inside the app for variable UI) to be part of the some data management or whatever.for the media files. He could start the app itself – like the current Windows 8 developer preview Start Menu … or with more support for what I call "super" tiles the app could decide to integrate itself (just like the shell namespace context menu in legacy Windows). I think of the People tile (allthough from the Windows Phone) as an example of users calling Explorer / ROOT {namespace], browser a file there and do something using the shell context menu (with apps integrated) I think the applications deployed to the device – or the actual application of Windows itself – will determine to best UI. The actual UI is whatever you start. Don't know if that can be automated from the app store (if Microsoft should offer to configure the application UI of Windows based on the major application type deployed on an instance of Windows OS). But with virtualization of the launch system the user could configure that himself or capable apps could also support that on deployment or device dependence (i.e. a remote control device is connected) I.e. You could may be even using the virtual launch system for just launching the legacy UI with no immersive. My whole point in virtualization in the launch system is postponing that decision to whatever the user decides and allow for easy configuration. Just press a few things – and connect some dimension (machine ID and/or Geo Location and/or Time) So if you take your laptop to your office or may be even your desk at home (depending on geo sensitivity – i.e. see the upcoming Gallileo sytem in Europe to replace GPS) you can set your use of Windows to just present you with the legacy UI. Take the same laptop or just login to some screen at your dining table – and you see something like a view of tiles with News and stuff. I.e. it already got todays wheater displayed in that tile. As a user you decide what is actually the best UI – the best use case right there, right now. You are launching the UI or app on Windows. So I think we agree on that since I think a virtual launch system would do exactly what you want and follows your perspective on things (I'm just still calling it Start Menu not to confuse – but Start Menu is really when Windows does not know what the user want's to do next – really use the Windows engine for in that instance. So different configrations could be created by the user and attach to device context i.e. MAC adresse or machine name (device dependence), location or time). I.e. integrated with the calendar you can just go around your workplace and Windows would have launched some of your stuff when you go to that meeting – only if you want to do so (like the current use of the start folder in legacy Start Menu). But this is more faceted (combinations of variable machine ID or device depedence, Geo Location, Date/Clock). At your desk at work a preferred menu wih Visual Studio, source code workspace and other programming tools could be preconfigured. All differential programmering or configuration of the Start Menu just by using drag and drop of apps with a few presets for that instance of the virtual Start Menu. From my point of view I'm just after more automation in Windows to get the simple UI – namely what I want Windows to support right now, right here in the actual display offering to reduce everything else away put in the background. Then in many cases I wont need more profiles. For instance as a system administrator at one company I can just create a virtual start menu for their place if my Live ID is connected to their LAN and i.e. the AD in Windows Server 8. Need to do something else? I just take forward my personal start menu. One app I would like to have across all menu's could be a messaging tile. If the Start Menu could be resized or just fast-keyed to like 1/4 of the display – I could just look at those tiles, i.e. seeing the new messages running on the dislay of the tile with Visual Studio to the right. Moving the mouse over the Start Menu's background could i.e. extend it to full screen display the rest of the tiles for programming tools. In that case I would keep my static tiles or icons or shortcuts pinned to the left of the start menu. Newly deployed apps should also be to the left then I think i.e. visibility. So as you stated – the need to have not one UI that fits everything – like run everywhere, but the need to have different UI's depending on context. THE BEST UI – is eaxctly the same I want. And LAUNCH or actual use of Windows OS is the key to that. I think it's a shame – if a new launch system is designed for Windows in 2011 – and it's does not promise to do it's responsibility better in accordance with todays statements from MIcrosoft ("role is everything", "workflow is everything" and so on. Namely launching or triggering apps. If not a new Start Menu will really have a achieved nothing new, except people needs to manage a new UI and the practical complications of that.. @Steven Sinofsky "Many people disagree with that I did not say?" Yes! This might be the best Windows news that I've heard in a long time. I didn't think of this at first, but this implies (for the first time ever) that you don't see Metro as replacing the desktop. In other words, it sounds like you realize that a large percentage of users will not make the move to Metro unless Microsoft practially forces them to. Feel free to correct me if I'm wrong, though, because I might just be reading more details into your words like I did before. Or maybe I didn't properly state what it is that many users disagree with? Actually, in this case, many users do disagree with what you did not say, because in the //build/ videos, it sounds like you actually see Metro and touchscreens the way you describe the GUI in this blog post (blogs.msdn.com/…/464152.aspx). Now you just need to implement that option to change Windows back to normal that we have been asking for. @WindowsVista567 Please, your approach is not appropriate. BTW For the example of a GPS navigation device running Windows 8 i.e. on ARM a user would just have a virtual start menu attached to that machine. I.e. you can actually deploy i.e. a TomTom app from appstore and probably that app would just setup that instance of the Start Menu. What does that precisely mean? Well, on your TomTom navigator formfactor you set the TomTom app running. May be in the future it would use Windows 8 or variant. But on the laptop you can still use that instance of the Start Menu (i.e. named My TomTom Nagavtor 4584) – only on that device – the laptop – is does not start i kiosk like on the small gps device, but works as TomTom Home. I.e. may be would get a fewer icons. Any supporting 3rd party support tools would be on that same Start Menu for that device. Of course you can still pin stuff where you want them. But it also opens the possibility of accessing more stuff on that GPS display in your car – if Windows 8 is under the hood. I.e. just switch the Start Menu … or really the actual UI. Virtual Launch System under the hood (let's keep it as Start Menu in the Windows front end) Finally, whether to use Metro UI or not will entirely depend on what you are going launch or how you configured your actual Start Menu. In many use cases the virtual launch system will allow stuff to just start immersive and fullscreen. I.e. that sports coaching app just comes on when I'm outside at the sports facility. In any less determined situation I get something much closer to legacy. I.e. I'm just going to login in to my PC – and do different stuff. Whatever I feel like. For that I also get an instance of the Start Menu (the one marked default and unbounded – without i.e. machine id, geo location and time). If I want to reset the theme i.e. reseting it to Aero rather than Metro – since launch is about display or UI – I can just select the Windows Theme for that launch object – this Start Menu instance: All in all I do a preset of this default Start Menu to use the legacy UI – and it brings me straight to the desktop and possibly automatically setting policies to prefer legacy in this case … when possible (i.e. opening the control panel gives me the legacy control panel). If so though – now virtual Start Menu is the key to automating user rendering configurations for the display – this also counts for my previous examples I guess – the HKEY_User will be variable for especially the shell keys, especially rendering constrains. But the shell is already the object of change in Windows 8. So should be no problem. Auto-launching would include a security concern in the use case in a Start Menu or really launch object instance (i.e. auto-login in kiosk mode with device dependence – auto-login in HKEY_machine but ok to reflect from the launch object since this is one unique machine id getting dedicated to the kiosk role in this case … device dependence … and requires the user is local administration to reset the device role). Then no worries about whether or not to run Metro UI. Users decide – they decide now, but the decision making would be implemented into the virtual Start Menu without the need to do group policy or local security policy and stuff or one registry hack. You just launch the best/optimal UI for your current use case of Windows. And with Windows 8 it has the potential to integrate into any device or form factor – any kind of PC. @Steven Sinofsky: Please tell us what "approach" is "appropriate". You said that when you begain this blog, it was to facilitate a *discussion*. It's been anything but a discussion. Anytime anyone brings up a legitimate criticism, it just gets ignored. Is this any way to treat your customers? @Steven Sinofsky Whoops. Sorry. Feel free to delete those comments. Trying to figure out what you mean from one simple comment probably isn't a good idea. I won't make that mistake again. Launch is the basic application of the application infrastructure – that basic initial event. So support for that special event is critical in the operating system. It the alpha event where an application starts its life. Let's have virtuali Start Menu. Make sure those instance configurations are serialized and reflected in XML. Then application domains can be shared. I.e. at a new work place I just import the application domain – that virtual start menu. I can setup a web server to push such configurations – i.e. virtual application suites or the appstore can be extended to throw commisions at resellers who virtually packages apps into a suite for i.e. Windows Software Development – in practice becomes a virtual start menu with deployment. Insteading of educating folks about what to install (lots and lots of reviews) you tell them what to use and wrap it up in a virtual start menu. When I install the virtualized Start Menu instance I can go to the appstore and see my basket with the price tag. Launch it is. Let others do product management wrapping them apps as if they were partials of custom cars with users preference for best solution available right here, right now done by a reseller. Turn the key and there you go. @Steven Sinofsky This comment system is a terrible substitute for a real dialogue. The exchange that just occurred is proof. This may be the last thing I ever post here. @WindowsVista567: I didn't see anything inappropriate in your posts. Microsoft can delete them if they want, but anyone could have saved screenshots. @WindowsVista567 and @I-DotNet It is inappropriate to say I said something I clearly did not, then to use my statement that I did not say it as further proof I said something. As we have said, no comments are deleted for expressing any view unless they are offensive. @I-DotNET and the rest of the commentators My approach was inappropriate because I pushed too hard for answers, with a bad method, reading details into Sinofsky's comment that didn't exist in a desparate attempt to find out if Windows 8 will include the Metro UI in the Developer Preview format. Sadly, this just isn't working. It's been over a month and nothing has really changed, and this comment field is more of a message board than a dialogue, so it is pointless for me to say anything else. Believe me, Steven Sinofsky's comment is painful to read… and mainly because of how true it is. I never thought I would be the one to post a comment with such a negative reaction. I don't see how any more comments from me can possibly benefit anyone. I would actually prefer it if Microsoft deleted that last post; it's one of the worst I've written. Don't go blaming Microsoft or accusing them of trying to prevent feedback from being posted, because that's not the issue. For now, I'll just wait and see what Windows 8 turns into. No more comments. none now. No more comments from WindowsVista567! done now. No more comments from WindowsVista567! @Steven Sinofsky: You said that this was going to be a *discussion*. Which blog are you discussing our concerns? It's certainly not this one. Every time any legitimate negative criticism gets brought up, they get summarily dismissed (and usually without explanation beyond 'early adopters' are afraid of 'change'.). If you want your existing customer base to go away, then be honest and just say so. But please do pretend that this is a discussion with your existing customers when it's clearly not. @Steven Sinofsky When I said that "posting that comment that you said as 'not appropriate' was a dumb idea," I mean that I, WindowsVista567, made a dumb decision in posting that comment. You haven't done anything that I think was "dumb." @I-DotNET Let it go. I was wrong. Period. Done. Your posts have nothing to do with my comment mistakes. Hopefully, I won't find anything else that I want to say differently. Let's hope that this will be my last, last, comment. @Computermensch: Yep, I can see this approach working in the long term. I have recently purchased an LG washing machine that has a little TFT screen. It makes choosing the various washing options an easy task (at last) because it does explain all the settings you choose as you turn the dial in one place (temperature, spin cycle rpm etc). Then when it is doing the actual washing it does display all the necessary information. It even can play diagnostics to a phone set you can hold next to it if you call the support center. Now, I am not saying let’s put >40MB of memory into this thing and run Windows 8 kernel, but we could run WinCE or something, keeping the Windows Virtual UI paradigm. When I am in the kitchen I look at the washing progress in its small screen, full screen with only the activity of interest showing, i.e. the washing (yep I don’t want to browse the Internet on my washing machine unlike some companies would make you believe). Now if I go to my PC upstairs I will be able to see the washing machine as a tile, or even better as something that I don’t hate lately 😉 In this tile I can see the progress and any other info I require, expand it and get a full real time report. Of course if we follow exactly what the Metro UI implies, all my 30” monitor would display in this example would be progress of the washing cycle in full screen. But let’s ignore that at the moment. To keep Microsoft happy on their latest fad we could also make use of the “cloud” so my Omnia7 (Windows Phone 7) can also display a special tile about the washing machine linked to other information and stats, i.e. electricity/water spent etc. But using your GPS locator and the fact that I am within WiFi range the phone could skip the notification if it knew that I am currently watching TV. Instead my Windows Media Center would be able to give me a notification when the washing is done, with “results” summary and if I have given it full permissions it can even pause the movie for me and when the washing is done. So I can have my movie playing loud and not worry about hearing the end of the washing tune (this machine plays a very nice tone at the end but not loud enough for hearing it across all rooms in the house). All this device interaction though will have to span across profiles because my wife’s account should be notified as well since she can also be interested in the washing action taking place in the kitchen. Now we have a number of devices that are all connected and they know what is going on around them, i.e. all the actions we are taking and they can keep us informed about their progress. Man and machine working together. Now if only my Iconia tablet could do the ironing I would be so happy. But I guess I will have to wait for the ironing tile to be available at the Microsoft app store first. @ Steven Sinofsky Please stop arguing and start listening. You want feedbacks and we give you feedbacks, but you only seem to defend yourself. Stop arguing plz…. @Mil Yeah, that's the picture. And it would be great if the tites could notify across virtual start menus too – i.e. your wifes profile. That could be done if Microsoft would let you push or share a virtual start menu i.e. even partially – so she can also just get i.e a few tiles or simply in some cases just 1 tile. I.e. when a user accepts a shared virtual start menu they could say yes to accept while no to its layout – then getting a list of virtual start menus and just drag the tiles where they want them. It's all about the producer-transformer-consumer (P > T > C) – or as you put it – system interactions – and while manual or introducing a human to a tile at the end of the interactive chain – or even inside the chain. So ideally those tiles or apps could be developed to notify each other and even better also chained interactively delivering output to each other. Promise of the cloud, devices and sensors. Just to correct myself: I called the People tile a "super" tile to promote its ability to reflect a global object or namespace containing everything connected to the concept of People. The right name for that sort of tile in the Windows Metro UI is a hub. I had forgot that word. BTW Initially the PTC pattern was left out of GOF book about Design Patterns. Interactions was considered so basic they did not go into the litterature initially. That was corrected a few years later. As other put it: Compuer Science is basicly the science about system interactions. So in that sense the tiles are pretty basic and important if they can become these interactive bricks as we go. So theres a whole lot more to it than just rendering the UI too. Just a MIL put it about interactions. Metro UI: Along the road the Metro should go for the perspective of interactions … and the UI – go for virtualization (the actual UI on Windows instantly)? Metro is already there in manys … but the virtual UI is not, unless virtuallization in the Start Menu is implemeted now when Microsoft is changing the concept of the Start Menu. Will there be any voice activated methods such as voice or natural language search in Windows 8? It is already becoming common in search engines and Siri of iOS, and will be a good feature to have in the Windows OS bringing it up to par with the rest of the competition. In some ways a virtual Start Menu could be the path to take the Metro Ui further … to become in one instance of a launch object simply a UI to i.e. Word Processing as one application domain. I.e. one tile or app delivers grammatic control. One is the editor (i.e. may be a HUGE TILE) and so on … may be somebody would do an app to do some writing for you following patterns to write a good story? Use of tiles like this follows the idea somebody else wrote somewhere in this forum to be able to drag the resize the Start Menu. It's just all immersive and we should be able to see some of the tiles like gadgets as we go – i.e. the entire display should not be exclusive to one app in Metro always. It would take declarative programming beyond XML where users can just construct their own applications using single or multifeatured featured apps in the apps store – constructing them into interfaces of tiles reusing the virtual Start Menu interface. So may be the formal name should just be Start? And then you can rename your actual launch object to whatever you want it to be. Virtualization in launch can mean many things … because its virtual. Any actual rutime scenario can be implemented. But lets see where Microsoft goes. Right now we still probably have to use Windows legacy for i.e. Visual Studio – because it's not going to run fullscreen while we have to go away from it to run some tool. May be one day Visual Studio will also have some of its major features put into tiles in a virtual launch object – probably named after the project? So I would not have to even open the project in Visual Studio? Those tiles could include build and continiouns integration reports from a Team Server, a play/debug tile and a test tile reflecting dynamic unit testing as we program – and of course priorities from the scrum project lead … and some 3rd party app features from the appstore. In nature, I hit my portable device and its projects the source and runs the prototype on some wall or display. At that point the legacy interface will probably have been replace somewhere in the future. Like the final countdown for almost 30 years of the text BIOS, But the virtual Start Menu would be a start – then such decisions can be taken later for Windows developing the Metro experience. And we get to experiment and extend the launch system from which all applications lifecycle depend – and integrate how we get the best UI right here, right now (office location, machine id, tine). … Really the projected display of the best available solution to me right here, right now. Of course it would all be experimental use – but the support in Windows would be there. If Microsoft wants – they can just keep their current display of a Start Menu there – but variability would be available to others non-tablet users. … and virtual start menus will be Windows not just on par (state-of-the-art) with Linux (Android) – especially Android 4 (ICE Cream) allthough it just has Home Screens. It would be beyond with potential for automated displays without the need to go and start your app. You just use the power putton and virtualize the use of the device. In the kitchen the tablet will simply display the recipe app or a recipe webpage untill changed. So take it further … to the basics of what the OS is used for. Running an application type or domain on top and provide some automation so it follows the network stuff. Not Home Displays (for icons), but real Mobile Displays for Macine ID, Location, Time … stuff in space … so you in many cases just go rendering the actual UI directly. The users don't have that possibility yet … and it supports the basic idea beyond Home Screens for functional complexity by icons … namely the Data-Driven Metro UI and the deicision to run WinRT apps immersively and fullscreen. … and starting an application directly is also about less navigation. Why do I want to start something that can start itself when appropriate? There's just one Start button – the button on the machine? Remember the Dieter Rams Braun Coffe machine – 1 button. Because everything inside was integrated and automated. Automation is key to reducing complexity in the presentation – not graphical design removing stuff manually. That's the secondary approach and its work and potential dependis on the degree of automation. That's why that coffee machine could portray itself as so simple with 1 start button: Power On. The virtualization of spatial launch objects will do the same in Windows. I have installed windows 8 and am using it as my primary OS. I also want to share some screen shots of my windows…/windows-8-features-applications-programs-screen-shots-display-wall-papers-style The only problem with search in Win7 from the start menu is speed. This is troublesome especially as I can't do anything else during the search as if i switch windows the start menu disappears and the search is lost. So I have to type and keep the menu open while the search is performed. This is annoying- @WindowsVista567 "Let's hope that this will be my last, last, comment." Why do you have to "hope"? YOU control when and where you post, what a ridiculous comment. "We look forward to your continued feedback as you try out the Windows 8 Start search experience!" All my slighty negative comments are not even published here, way to hear users when you can only see positive comments… It's very annoying that the search has settings and files under separate tabs. Since we are working with a full screen monitor, can't we see every thing at once? It worked in win7 with a much smaller space so it should definitely work in win8. According to your telemetry data, one third of searches aren't for apps so for those one third of all searches, we shouldn't needlessly be imposed with the extra task of clicking the tab for those of us who don't remember keyboard shortcuts. The problem with the old search (as in XP, Win 7) is the FILESYSTEM not the interface. Microsoft clearly doesn't do any indexing UNTIL you search. Well, duh, that's going to be slow. But how does this idiotic Metro crap solve that problem? It doesn't. "All my slighty negative comments are not even published here, way to hear users when you can only see positive comments…" They don't care what we think. They figure we'll buy whatever they peddle as long as its in the store. But if Microsoft PCs are going to be crippled into being tablets, why not just buy a tablet? Windows 8 is all the more reason to buy an Android device. And if Windows usability and multitasking is going to crippled, why not buy a Macbook Air? If Windows becomes as crippled as Mac, I'll just go to Mac. If Windows is going to be given an ugly tablet interface and made into a tablet masquerading as a laptop, I'll just go to Android whose interface is way better than Metro (Android interface is more Windows-like actually, since it mimics your standard Desktop type interface that both Windows XP / 7 and Mac have). @mil_: Picking up on a few of your comments. "When I am referring to “scaling”, I mean the Metro UI and not the kernel of the OS." Ok, fine. However, i don't agree with the general consensus on this blog and in the forum that the Metro UI is great for hand-held devices but doesn't scale well to laptop/desktop PCs. When you go from icons to tiles as the target points, and then start adding app data and app content to the tiles, the bigger the screen you have, the better off you are. Then if you consider combining tiles into groups and regarding the group as a "window", plus the need to zoom out to see all you groups and scroll to see all your tiles, then you are definately at an advantage with a larger screen, even in a relative sense. So i think the idea of Metro being a tablet UI "shoehorned" into a desktop UI is false – and the converse is true. Metro is absolutely designed with big monitors, and multiple monitors, in mind, and not only will it scale well, but these environments are where it will shine. Take this as a (currently) extreme example. Consider a house like the M & B Gates residence with walls covered in screens that display various types of content based on the preferences of the occupants and visitors. Now what interface would be preferable for controlling systems like that – the Metro UI with touch, or Desktop with a mouse? Of course, it's a "no-brainer". So there's one nice example were the critics of Metro on larger systems are just wrong. The question for me, is not – does Metro scale up? – rather it's – will Metro work ok on sub-netbooks and small tablets? exactly is the problem in temporarily "losing the desktop"? Is it the transition itself, or the loss of attention, or something else? I agree that the abrubt change in contrast/brightness is currently a problem. (Part of that problem is due to apps using stark white, battery-sapping backgrounds. IMO plain white is too bright and should never be used – a light beige or cream hue is far easier on the eyes, especially in dim lighting environments.) Regarding the altered brightness and "jarring" nature of the transition, there are several things that could be done, and i think Microsoft have to some extent deliberately avoided smoothing-out the Metro -> Desktop -> Metro transitions in the DP to see how much people can tolerate. I guess they have the answer now. However, i can imagine things like combining/locking the Metro and Desktop background color and wallpaper would help, as would replacing the slide-back, slide-in affect with a rapid fade-out, fade-in of the tile/window layer (possibly overlapped). That might mean users having to replace their more graphically rich desktop wallpapers with something more bland that doesn't spoil the look of Start, but so be it (or just have a prominent slideshow tile, as compensation). While i'm on the subject, the other tweaks i would make are: 1. The start menu button should look less like the Win7 button than it does in the DP. It should get the Metro color scheme (white flag on green base), and the running app look, so users perceive the start button as representing an app, and not a pull-up menu. Currently the start button is too much of a "lie" (it breaks user expectations, causing a slight loss of trust in the OS). The context-menu gets an 'Open Start Menu Programs' Explorer link so users can quickly rebuild their taskbars. 2. The Desktop tile should be removed, and be replaced by a Desktop group, containing by default, IE and Explorer tiles, plus tiles for whatever icons the user pins to the taskbar (@desktop). Perhaps the Desktop group should get smaller, rectangular tiles, to make this group look a little more like the start menu. 3. System tray functionality should be completely removed from the taskbar (with the possible exception of date/time) and moved to Start. Desktop is just another destination (from Start), so it should no longer host OS related functions & notifications. 4. An unrelated point i'm going to add regardless, is that tile visibility should not be restricted to unlocked sessions. The user should be able to flag tiles as 'Public' (non-confidential), so that when they lock their logon sessions, these tiles stay visible so users can observe live data. The point i made about telemetary had nothing to do with liking or disliking the new Task Manager personally. Instead, the fact is that everything new in Win8 that has a UI is being designed with telemetary as a guide, or, as a design tool, is probably a better way of putting it. I don't understand why people can't except this, or why people think the telemetary data totally drives the outcomes, with no respect to any other factors, including "the art". There are multiple factors at play here, and MSFT are not using telemetary "fullscreen", like you seem to think they are. Frankly, i think many people (not yourself) are attacking the use of telemetary in Win8 because they can't or can't be bothered articulating what problems or issues they have with the new stuff, or simply want to pretend that MSFT is some big, dumb organization with no "artists", and if only they would listen to me (who has the great design sense and skills), then all would be well. Well to those folks i say – keep dreaming. Great post, like your previous ones. I Like the way you explain things through demos, stats and graphs. Very persuasively done. Love the Search feature in 8, definitely easier than 7. The only thing that irks me is IE10, its less responsive on my 1.25 RAM, 6 yr. old HP desktop so much so that I have to frequently go to the desktop view. Also wish it had a Home button just as in its desktop view. @Steven Sinofsky There's one thing that telemetry can't address: psychological matters. I believe you're disregarding the psychological attachment of desktop users to the Desktop (Open windows, taskbar, icons) as a "home" to their computing needs. Adding a separate screen for most of the critical tasks is understandably a need for tablet usage – and the screen you're building is stylish and functionally superior to every other tablet interface out there. That's were MSFT always shined, after all. But for a desktop scenario, you should allow it to blend somehow with the desktop itself: as an overlay, as a half-screen that slides out of one the screen sides, etc. – without actually "hiding" the desktop, without leaving it and making it disappear from the user's view. This has a very bad psychological impact, that's in my opinion what's generating most of the negative answers to the start screen. Also, Aero should be somewhat metro-fied for the always underrated question of visual consistency – but that's another matter. @Drewfus: Please read again the example you mentioned “Now what interface would be preferable for controlling systems like that – the Metro UI with touch, or Desktop with a mouse?”. “What exactly is the problem in temporarily "losing the desktop"? Is it the transition itself, or the loss of attention, or something else?” I do not want to transition to a full screen application just for a few seconds. It is tiring, stupid and unnecessary.. When I am driving, I am not going full screen with the in car radio interface because I am changing stations. My problem with the telemetry data is that they compare oranges and potatoes by saying “look, you now have more space to search for things”. Yes, I don’t even need telemetry data to show me that I can display more results on a full screen window than an 8th smaller Window the old start menu represented. So what? Do I really need to scientifically explain why the telemetry data is used wrongly in an effort to support a UI that is made for tablets and desktop challenged simpletons? I don’t think I have to prove anything when there is a history of Windows that spans almost two decades. As I said before there was nothing stopping us from “inventing” this “new” way of using Windows a decade ago. The technology required was there one way or another (maybe the smooth transitions would be a bit hard to achieve though). All these years Microsoft was trying to convince us that the desktop UI could fit into the Mobile Phone…Windows Mobile 6.0, 6.5 etc. Then the market “explained” to them in billions of lost market share that they were following the wrong path. Now they are trying to fit the Phone UI into the desktops…maybe this time they are not completely wrong because they will get all the novice users to like it.? Does it also tell them that I am interested in animating tiles that distract me from my work constantly without having the option to restrict the size of the Window that displays them? These are the wrong conclusions, it is not what I want as a desktop user and the only reason they try to defend that position is because they are trying to herd us towards that direction. I am not going to debate the rest of your points because they represent suggestions on how to unify the two paradigms, and probably they are correct if the main objective was correct. But I disagree completely with unifying the two because they are as I said two different ways of using a computer and they will never merge without breaking one of them completely. The main points are, I am not going to be touching my 3 desktop monitors now or in the future. A full screen application is something I want to have full control of. Searching for applications/files is not what I am paid to do when I am sitting in front of my computer. I know where my applications are and I don’t have tens of thousands of them now and I am not going to have tens of thousands of applications in my desktop in the future. I want a different UI tailored for the device it is used with and make full use of its capabilities. “Full screen” is not the same as “full use”, it is just a lazy way of using the desktop that appeals to novices but is against professional users of the desktop.. We can also add that the Start Menu because of exactly that role is the most important object in the operating system controlling the end user experience. Technology from Microsoft is extremely great but its under the hood Microsoft needs to make the Start Menu and thus the end user experience as just a good techonology (characterized by almost no weaknesses) as the NTFS (like the introduction of transaction control in Vista and Windows 7). Complete hidden but great. Now in Windows 8 a new file system is expected by some. So NTFS is not good enough in Microsoft opion. Yes, a new technology is may be needed. But thats under the hood and nobody "consumer" like ever sees it or directly experience it. But the same ambitiousness from Microsofts part should be there regarding the most important thing for the end user experience. Where's all the software and automatics – the smart stuff – beyond looks and graphics? Again virtual start menu. Come on! Don't do a Start Menu with an Apps list – don't do it likke 1995. Think end user expience has to be in value, in the possibilities – in USE! Not just pictures or imagination. Do the same great stuff there as elsewhere. Bottom up is great … but top down too if you have to prioritize. Building Windows 8 is an imaginary process … theres no way to start with the bottom first and do a technically strong and very useful UI in a later release. You can't do such a UI first and have no a weak engine under the hood. Do both. Great with the strong engine. That was also the case with Windows Vista – it was the core for Windows 7 – like Windows 2000 was for Windows XP. Now WIndows 8 – new core, WinRT, possibly protogon and much, much more. Very busy doing core technology. Which is great. Only to avoid the Vista thing – remember the UI too! And its not about some nice pictures – but useful. Vista had an animatied desktop. Never mind. The technology at the time for Vista was very good and it was the foundation of Windows 7 – Vista rebranded with A NEW DEKSTOP! So please get it. Personally, I wrote a feedback note then critizing the lack of renewal in taskbar during Vista. It came with Windows 7! In Windows 7 I worried about the lack of renewal or innovation in the taskbar and start menu. It came with Metro. But now I worry about the usefullness. It has to be strong technology like what to do for every other component in Windows. Everything is so good. Then why is there no smart real good techonology in the UI? I'm not thinking about the looks. The looks are rather great. But that Start Menu can not really do anything software cool. Nothing. Same with the apps list. They are just appaling in behaviour – but looks ok (the tile stuff). Following that idea, those tiles could be smart of stuff. Or at least I would want that virtual start menu. You go under the hood and stuff is really cool in Windows Why is that? What happens at the desktop level? Nobody cares about writing cool software and smart algos for that. I took a look in process monitor following the work of the Start Menu and Apps List. The apps list just scans folders across the system and presents them icons in the apps list. That's it. Hey, we don't wanna do it the cool way. I want to write a new application pool instead or something like that? No tiles, no stacks, no virtualization. No computer science? Only psychologi and medical science? Please, please – what I really worry is, that there will be no way to build changes into the beaviour of the Start and also the Apps LIst, because you want to control that complete because of reality, consumer trust and the appstore. Meaning locked up unflexible Start Menu and Apps List – like a new locked up Media Center presentation with no ways of changing that … and a real forever locked up tech Start Menu (not looks, but FUNCTIONALITY and no virtualization) … untill next Windows release. Meanwhile new start menu and launcher comes up – only they will not be able too collaborate with the appstore, because variability and managed API's that can EXTEND THE BEHAVIOUR in the Start Menu was ignored. I.e. is it wrong to say that from Microsofts perspective the success of the app store depends of the Start Menu. I.e. can anbody install something from the appstore if the are not using that Start Menu? So do great stuff for the Start Menu under the hood and virtualize it. Also with a managed API variants can be required to implement certain behaviour and not overide others. Shoud not be that hard to do. A lot less harder that a lot of new stuff in Windows 8. Please, more effort here. The artists are doeing great, but more computer stuff … software stuff. An Start Menu for 2012 that would impress people in Computer Science. Touch is not new or special. It's old. The market interest is new. So let's get more than that. Allow us to do more with launching programs. The most important part of the user objects. You already know what I want to do. Spatial Launch Objets. Just provide the API's so we don't have to break collaboration with the app store. On the phone we can access the live camera feed … As I put in earlier I don't mind you doeing you own Start Menu that way – just that in can be replaced. If you don't want it replaced put more software into it – other than the artists, psychologist and other interpretive specialists. Provide more engineers that will write virtual code as well. But I do mind that you're doeing it the Vista way again. More software into the user expiernence. Think about what you did for the taskbar, right? It became smarter. It could do stuff. Now think about how much of that you're doeing with the Start Menu. Search is just appaling. That's delegating the responsibility to the user … go discover and find it yourself. I am not saying it easy – I'm just saying the allow the object to be switched. Then we can redo the start menu. Everybody can have launch the way the want. Evyerbody can optimize the user experience. Everybody is different. Let's use differtial programming for the Start Menu. Virtual! And finally. With the virtual start menu – and possibly virtual shelll – Windows is getting ready for its future. It has 95% market share. It's so huge – nobody really invests so much money in developing the infrastructure except Microsoft. And may be Goolge coming up – except they still does not really care about innovation in the OS because they are using Linux – and have to give stuff away. MacOS is notorious for having most of BSD code in its kernel. Android is Linux. Both dependend on open source license so every investment possibly lost to the public. So nobody really invests. With the virtualization starting to come into the desktop level we can finally get on with the game and say, hey – the roads have been build. Let's focus on some new stuff instead. And i.e. the MacOS at some point in the future can be Windows core in part rebranded at the deskttop level. Just as it already is – but BSD. Same for Android – but Linux. They all prepared for it choosing stuff that runs on Intel technology. Let's get on with it. There are new ventures to be done. Hi Windows team ! i have some questions and plz..answer me ! maybe someone above has asked this but as there this complain about differentiating the apps..files.settings into categories .. and how that doubles the clicks (taps on tablets) to find a file o settings when you're not intending for an searching an app ? so you tell me.. you need more room to show the results and avoid the confusion..but you're actually doubling the taps / clicks aren't you ? if you insist on doing it your way..ok .. but why don't you apply this workaround ? if a user hits win+F for example..it still gives you the files category BUT it's not files..it's files FIRST if he hits win+W then it gives you settings FIRST search result ??! And i have another question that i be glad to be answered earlier this week mr ballmer said in press cf that " I don't want to be a scientist to be able to use a (android ) phone..so since you both work in the same company.. .. I ask this.. haw could I know I had to hit win+W to get the settings results and not be a scientist ?? seriously..i used developer preview for 3 weeks at least (and i'm a soft eng by the way ) and I didn't notice it until I saw that on your blog..maybe I'm dumb !? @mil_ ." No, it doesn't. All it "proves" is that a household full of wall monitors might be best controlled via a tablet. For a house with one or two wallscreens, direct touch would be useful, just as it would be for a display built into a refrigerator, or other household appliance. "I do not want to transition to a full screen application just for a few seconds. It is tiring, stupid and unnecessary." I timed the transition from Desktop -> Start (and the reverse), and it seems to be around 0.75 seconds. This is below the approximate 1.0 second threshold that usability expert Jacob Nielson identifies as "…the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay."…/responsetime.html In contrast, the start menu goes close enough to being within the 0.1 second barrier, which "…is about the limit for having the user feel that the system is reacting instantaneously…" However, in the case of Start-Desktop transitions the user will have to readjust to a totally changed screen display, as well as processing movement during the transition interval. This would mean getting perilously close to a genuine disruption of the users attention. Not good. Microsoft will most likely need to reduce the transition time right down, and minimize the cognitive overhead as best they can, before Win8 goes RTM. ." I'll just make a point i've already made in a slightly different way – don't let Microsoft's new terms for old things mislead you. If you want an example of what i mean, go to – and there is a very simple Metro style UI – a solid background and one big "tile" in the middle displaying content, plus a field for user input. That tile could just as easily be your video conferencing app, or your newest inbox entries. A Metro tile is just the analog to an HTML <div> – "reimagined" as the building-block for web-based app interfaces. A combination of tiles is called a group, but you could call it a webpage, or a window, or a … banana. The point is we now have a web-standards based application interface model, albeit incomplete. The other thing about tiles is that they can (or will) be created in any size required. So not just 1x or 2x, but also 0.1x, 10x, fullscreen, eighth-screen, quad-screen, fit-to-content. Whatever suits. Don't assume any limits, unless Microsoft tell you otherwise, and maybe not even then. "Do I really need to scientifically explain why the telemetry data is used wrongly in an effort to support a UI that is made for tablets and desktop challenged simpletons?" If Microsoft justify their design decisions using objective data/evidence + usability testing + trial & error + existing research + well known design principles + maths, you are going to have to do a lot more to counter their arguments than just assuming your own conclusion. Telemetry is useful for optimization, but to optimize implies that the fundamentals of the thing being designed or refined must already be in place, so these must have had a different source of inspiration. Do F1 teams design their cars using telemetry alone, or do they use telemetry for fine-tuning? ?" I partially agree with you here, in that Microsoft seems to be trying to persaude us that the start menu is so bad and yet so crucial to users that we should regard it as the Achilles Heel of Windows that absolutely needs a major overhaul – to put it mildly. Of course, the counter-argument is always going to be that since, as the telemetry tells us, 88% of app launches occur from places other than the start menu, then to that extent the argument that the start menu is some grossly flawed thing must also be 88% irrelevant. The problem for the "pro-start menu" group is that the argument is a two-way street – if you're not using the start menu much for app launch or for search, then why so much angst over the occasional mildy interrupting Desktop -> Start -> Desktop cycle, if you're getting stuff like fullscreen search results and data services into the bargain? Aren't we sailing perilously close to a storm in a teacup here? "I am not going to be touching my 3 desktop monitors now or in the future." Fine, but touch is touch and Metro is Metro. Besides, i reckon you will touch your monitors, occasionally 🙂 "Searching for applications/files is not what I am paid to do when I am sitting in front of my computer." Almost none of us are, but here is the fascinating thing (that i predict we'll see covered in a future post) – most users spend an inordinate amount of time searching for files, apps and webpages. Web search time is something we are well aware of, but apparently users spend some amazingly high proportion of each computer-facing hour searching for stuff, particularly files. There are several reasons, including the poor file naming habits of users, and the fixed heirarchies that existing filesystems force us to use.…/filedeath.html So i don't agree with you when you say – "“Full screen” is not the same as “full use”, it is just a lazy way of using the desktop that appeals to novices but is against professional users of the desktop" – in the case of search. On the contrary, if anything should be fullscreen in Windows, it's search. ." Again, your last point is true, if you assume your own conclusion (that Metro UI is for tablets and not for desktops) – but why?
https://blogs.msdn.microsoft.com/b8/2011/10/18/designing-search-for-the-start-screen/
CC-MAIN-2018-05
refinedweb
52,570
70.23
What are lifecycle methods? How do the new React16+ lifecycle methods fit in? How can you intuitively understand what they are and why they are useful? If you’ve had questions on how the React lifecycle methods work — look no further. What’s the deal with lifecycle methods anyway? React components all have their own phases. Let me explain further. If I said to you, “build a Hello World component”, I’m sure you’ll go ahead and write something like this: class HelloWorld extends React.Component { render() { return <h1> Hello World </h1> } } When this component is rendered and viewed on a client, you may end up with a view like this: The component had gone through a couple of phases before getting here. These phases are generally referred to as the component lifecycle. For humans, we get, child, adult, elderly. For React components, we have, mounting, updating and unmounting. Coincidentally, mounting a component is like bringing a newborn baby to the world. This is the component’s first glimpse of life. It is at this phase the component is created (your code, and react’s internals) then inserted into the DOM. This is the very first phase the component goes through. The mounting phase. Do not forget this. It doesn’t end here. A React component “grows”. Better put, the component goes through the updating phase. For react components, without updates, the component will remain as they were when they were created in the DOM world. A good number of components you write get updated — whether that’s via a change in state or props. Consequently, they go through this phase as well. the updating phase. The final phase the component goes through is called the unmounting phase. At this stage, the component “dies”. In React lingo, it is being removed from its world — the DOM. That’s pretty much all you need to know about the component lifecycle in itself. Oh, there’s one more phase a React component goes through. Sometimes code doesn’t run or there’s a bug somewhere. Well, don’t fret. The component is going through the error handling phase. Similar to a human visiting the doctor. And now, you understand the four essential phases or lifecycle attributed to a React component. - Mounting — It is at this phase the component is created (your code, and react’s internals) then inserted into the DOM - Updating — A React component “grows” - Unmounting — Final phase - Error Handling — Sometimes code doesn’t run or there’s a bug somewhere NB: A React component may NOT go through all of the phases. The component could get mounted and unmounted the next minute — without any updates or error handling. The illustration (and our example thus far) has assumed that the component goes through all phases — for the sake of explanation. Understanding the phases and their associated lifecycle methods Knowing the phases the component goes through is one part of the equation. The other part is understanding the methods react makes available at each phase. These methods made available to the component at each phase is what’s popularly known as the component lifecycle methods. Let’s have a look at the methods available on all 4 phases — mounting, updating, unmounting and error handling. Let’s begin by having a look at the methods unique to the Mounting phase. The mounting lifecycle methods The mounting phase refers to the phase from when a component is created and inserted to the DOM. The following methods are called (in order) 1. constructor() This is the very first method called as the component is “brought to life”. The constructor method is called before the component is mounted to the DOM. Usually, you’d initialise state and bind event handlers methods within the constructor method. Here’s a quick example: const MyComponent extends React.Component { constructor(props) { super(props) this.state = { points: 0 } this.handlePoints = this.handlePoints.bind(this) } } I suppose you are conversant with the constructor method so I won’t elucidate further. What’s important to note is that this is the first method invoked — before the component is mounted to the DOM. Also, the constructor is NOT where to introduce any side-effects or subscriptions such as event handlers. 2. static getDerivedStateFromProps() Before explaining how this lifecycle method works, let me show you how the method is used. The basic structure looks like this: const MyComponent extends React.Component { ... static getDerivedStateFromProps() { //do stuff here } } The method takes in props and state: ... static getDerivedStateFromProps(props, state) { //do stuff here } ... And you can either return an object to update the state of the component: ... static getDerivedStateFromProps(props, state) { return { points: 200 // update state with this } } ... Or return null to make no updates: ... static getDerivedStateFromProps(props, state) { return null } ... I know what you’re thinking. Why exactly is this lifecycle method important? Well, it is one of the rarely used lifecycle methods, but it comes in handy in certain scenarios. Remember, this method is called (or invoked) before the component is rendered to the DOM on initial mount. Below’s a quick example: Consider a simple component that renders the number of points scored by a football team. As you may have expected, the number of points is stored in the component state object: class App extends Component { state = { points: 10 } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} <p> You've scored {this.state.points} points. </p> </header> </div> ); } } The result of this is the following: Note that the text reads, you have scored 10 points — where 10 is the number of points in the state object. Just an as an example, if you put in the static getDerivedStateFromProps method as shown below, what number of points will be rendered? class App extends Component { state = { points: 10 } // ******* // NB: Not the recommended way to use this method. Just an example. Unconditionally overriding state here is generally considered a bad idea // ******** static getDerivedStateFromProps(props, state) { return { points: 1000 } } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} <p> You've scored {this.state.points} points. </p> </header> </div> ); } } Right now, we have the static getDerivedStateFromProps component lifecycle method in there. If you remember from the previous explanation, this method is called before the component is mounted to the DOM. By returning an object, we update the state of the component before it is even rendered. And here’s what we get: With the 1000 coming from updating state within the static getDerivedStateFromProps method. Well, this example is contrived, and not really the way you’d use the static getDerivedStateFromProps method. I just wanted to make sure you understood the basics first. With this lifecycle method, just because you can update state doesn’t mean you should go ahead and do this. There are specific use cases for the static getDerivedStateFromProps method, or you’ll be solving a. You could read that again if you need it to sink in. Also, component state in this manner is referred to as Derived State. As a rule of thumb, derived state should be used sparingly as you can introduce subtle bugs into your application if you aren’t sure of what you’re doing. 3. Render After the static getDerivedStateFromProps method is called, the next lifecycle method in line is the render method: class MyComponent extends React.Component { // render is the only required method for a class component render() { return <h1> Hurray! </h1> } } If you want to render elements to the DOM, the render method is where you write this (as shown above) i.e returning some JSX You could also return plain strings and numbers as shown below: class MyComponent extends React.Component { render() { return "Hurray" } } Or return arrays and fragments as shown below: class MyComponent extends React.Component { render() { return [ <div key="1">Hello</div>, <div key="2" >World</div> ]; } } class MyComponent extends React.Component { render() { return <React.Fragment> <div>Hello</div> <div>World</div> </React.Fragment> } } In the event that you don’t want to render anything, you could return a Boolean or null within the render method: class MyComponent extends React.Component { render() { return null } } class MyComponent extends React.Component { // guess what's returned here? render() { return (2 + 2 === 5) && <div>Hello World</div>; } } Lastly, you could also return a portal from the render method: class MyComponent extends React.Component { render() { return createPortal(this.props.children, document.querySelector("body")); } } An important thing to note about the render method is that the render function should be pure i.e do not attempt to use setStateor interact with the external APIs. 4. componentDidMount() After render is called, the component is mounted to the DOM, and the componentDidMount method is invoked. This function is invoked immediately after the component is mounted to the DOM. Sometimes you need to grab a DOM node from the component tree immediately after it’s mounted. This is the right component lifecycle method to do this. For example, you could have a modal and want to render the content of the modal within a specific DOM element. The following could work: class ModalContent extends React.Component { el = document.createElement("section"); componentDidMount() { document.querySelector("body).appendChild(this.el); } // using a portal, the content of the modal will be rendered in the DOM element attached to the DOM in the componentDidMount method. } If you also want to make network requests as soon as the component is mounted to the DOM, this is a perfect place to do so as well: componentDidMount() { this.fetchListOfTweets() // where fetchListOfTweets initiates a netowrk request to fetch a certain list of tweets. } You could also set up subscriptions such as timers. Here’s an example: // e.g requestAnimationFrame componentDidMount() { window.requestAnimationFrame(this._updateCountdown); } // e.g event listeners componentDidMount() { el.addEventListener() } Just make sure to cancel the subscription when the component unmounts. I’ll show you how to do this when we discuss the componentWillUnmount lifecycle method. With this, we come to the end of the Mounting phase. Let’s have a look at the next phase the component goes through — the updating phase. The updating lifecycle methods Whenever a change is made to the state or props of a react component, the component is re-rendered. In simple terms, the component is updated. This is the updating phase of the component lifecycle. So what lifecycle methods are invoked when the component is to be updated? 1. static getDerivedStateFromProps() Firstly, the static getDerivedStateFromProps method is also invoked. That’s the first method to be invoked. I already explained this method in the mounting phase, so I’ll skip it. What’s important to note is that this method is invoked in both the mounting and updating phases. The same method. 2. shouldComponentUpdate() As soon as the static getDerivedStateFromProps method is called, the shouldComponentUpdate method is called next. By default, or in most cases, you’ll want a component to re-render when state or props changes. However, you do have control over this behavior. Within this lifecycle method, you can return a boolean — true or false and control whether the component gets re-rendered or not i.e upon a change in state or props. This lifecycle method is mostly used for performance optimisation measures. However, this is a very common use case, so you could use the built-in PureComponent when you don’t want a component to re-render if the stateand props don’t change. 3. render() After the shouldComponentUpdate method is called, render is called immediately afterwards – depending on the returned value from shouldComponentUpdate which defaults to true . 3. getSnapshotBeforeUpdate() Right after the render method is called, the getSnapshotBeforeUpdatelifcycle method is called next. This one is a little tricky, but I’ll take my time to explain how it works. Chances are you may not always reach out for this lifecycle method, but it may come in handy in certain special cases. Specifically when you need to grab some information from the DOM (and potentially change it) just after an update is made. Here’s the important thing. The value queried from the DOM in getSnapshotBeforeUpdate will refer to the value just before the DOM is updated. Even though the render method was previously called. An analogy that may help has to do with how you use version control systems such as git. A basic example is that you write code, and stage your changes before pushing to the repo. In this case, assume the render function was called to stage your changes before actually pushing to the DOM. So, before the actual DOM update, information retrieved from getSnapshotBeforeUpdate refers to those before the actual visual DOM update. Actual updates to the DOM may be asynchronous, but the getSnapshotBeforeUpdate lifecycle method will always be called immediately before the DOM is updated. Don’t worry if you don’t get it yet. I have an example for you. A classic example of where this lifecycle method may come in handy is in a chat application. I have gone ahead and added a chat pane to the previous example app. The implementation of the chat pane is as simple as you may have imagined. Within the App component is an unordered list with a Chats component: <ul className="chat-thread"> <Chats chatList={this.state.chatList} /> </ul> The Chats component renders the list of chats, and for this, it needs a chatList prop. This is basically an Array. In this case, an array of 3 string values, ["Hey", "Hello", "Hi"]. The Chats component has a simple implementation as follows: class Chats extends Component { render() { return ( <React.Fragment> {this.props.chatList.map((chat, i) => ( <li key={i} {chat} </li> ))} </React.Fragment> ); } } It just maps through the chatList prop and renders a list item which is in turn styled to look like a chat bubble :). There’s one more thing though. Within the chat pane header is an “Add Chat” button. Clicking this button will add a new chat text, “Hello”, to the list of rendered messages. Here’s that in action: The problem here, as with most chat applications is that whenever the number of chat messages exceeds the available height of the chat window, the expected behaviour is to auto scroll down the chat pane so that the latest chat message is visible. That’s not the case now. Let’s see how we may solve this using the getSnapshotBeforeUpdate lifecycle method. The way the getSnapshotBeforeUpdate lifecycle method works is that when it is invoked, it gets passed the previous props and state as arguments. So we can use the prevProps and prevState parameters as shown below: getSnapshotBeforeUpdate(prevProps, prevState) { } Within this method, you’re expected to either return a value or null: getSnapshotBeforeUpdate(prevProps, prevState) { return value || null // where 'value' is a valid JavaScript value } Whatever value is returned here is then passed on to another lifecycle method. You’ll get to see what I mean soon. The getSnapshotBeforeUpdate lifecycle method doesn’t work on its own. It is meant to be used in conjunction with the componentDidUpdate lifecycle method. While you keep the problem we’re trying to solve at heart, let’s have a look at the componentDidUpdate lifecycle method. 4. componentDidUpdate() This lifecycle method is invoked after the getSnapshotBeforeUpdate is invoked. As with the getSnapshotBeforeUpdate method it receives the previous props and state as arguments: componentDidUpdate(prevProps, prevState) { } However, that’s not all. Whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as the third argument to the componentDidUpdate method. Let’s call the returned value from getSnapshotBeforeUpdate, snapshot, and here’s what we get thereafter: componentDidUpdate(prevProps, prevState, snapshot) { } With this knowledge, let’s solve the chat auto scroll position problem. To solve this, I’ll need to remind (or teach) you some DOM geometry. So bear with me. In the meantime, here’s all the code required to maintain the scroll position within the chat pane: getSnapshotBeforeUpdate(prevProps, prevState) { if (this.state.chatList > prevState.chatList) { const chatThreadRef = this.chatThreadRef.current; return chatThreadRef.scrollHeight - chatThreadRef.scrollTop; } return null; } componentDidUpdate(prevProps, prevState, snapshot) { if (snapshot !== null) { const chatThreadRef = this.chatThreadRef.current; chatThreadRef.scrollTop = chatThreadRef.scrollHeight - snapshot; } } Here’s the chat window: However, the graphic below highlights the actual region that holds the chat messages (the unordered list, ul which houses the messages). It is this ul we hold a reference to using a React Ref. <ul className="chat-thread" ref={this.chatThreadRef}> ... </ul> First off, because getSnapshotBeforeUpdate may be triggered for updates via any number of props or even a state update, we wrap to code in a conditional that checks if there’s indeed a new chat message: getSnapshotBeforeUpdate(prevProps, prevState) { if (this.state.chatList > prevState.chatList) { // write logic here } } The getSnapshotBeforeUpdate has to return a value. If no chat message was added, we will just return null: getSnapshotBeforeUpdate(prevProps, prevState) { if (this.state.chatList > prevState.chatList) { // write logic here } return null } Now consider the full code for the getSnapshotBeforeUpdate method: getSnapshotBeforeUpdate(prevProps, prevState) { if (this.state.chatList > prevState.chatList) { const chatThreadRef = this.chatThreadRef.current; return chatThreadRef.scrollHeight - chatThreadRef.scrollTop; } return null; } First, consider a situation where the entire height of all chat messages doesn’t exceed the height of the chat pane. Here, the expression chatThreadRef.scrollHeight - chatThreadRef.scrollTopwill be equivalent to chatThreadRef.scrollHeight - 0. When this is evaluated, it’ll be equal to the scrollHeight of the chat pane — just before the new message is inserted to the DOM. If you remember from the previous explanation, the value returned from the getSnapshotBeforeUpdate method is passed as the third argument to the componentDidUpdate method. We call this snapshot: componentDidUpdate(prevProps, prevState, snapshot) { } The value passed in here — at this time, is the previous scrollHeight before the update to the DOM. In the componentDidUpdate we have the following code, but what does it do? to scrollTop value to the sum of the heights of extra messages – exactly what we want. Yeah, that’s it. If you got stuck, I’m sure going through the explanation (one more time) or checking the source code will help clarify your questions. You can also use the comments section to ask me:). The unmounting lifecycle method The following method is invoked during the component unmounting phase.() as shown below: // e.g add event listener componentDidMount() { el.addEventListener() } // e.g remove event listener componentWillUnmount() { el.removeEventListener() } The error handling lifecycle methods Sometimes things go bad, errors are thrown. The following methods are invoked when an error is thrown by a descendant component i.e a component below them. Let’s implement a simple component to catch errors in the demo app. For this, we’ll create a new component called ErrorBoundary. Here’s the most basic implementation: import React, { Component } from 'react'; class ErrorBoundary extends Component { state = {}; render() { return null; } } export default ErrorBoundary; static getDerivedStateFromError() Whenever an error is thrown in a descendant component, this method is called first, and the error thrown passed as an argument. Whatever value is returned from this method is used to update the state of the component. Let’s update the ErrorBoundary component to use this lifecycle method. import React, { Component } from "react"; class ErrorBoundary extends Component { state = {}; static getDerivedStateFromError(error) { console.log(`Error log from getDerivedStateFromError: ${error}`); return { hasError: true }; } render() { return null; } } export default ErrorBoundary; Right now, whenever an error is thrown in a descendant component, the error will be logged to the console, console.error(error), and an object is returned from the getDerivedStateFromError method. This will be used to update the state of the ErrorBoundary component i.e with hasError: true. componentDidCatch() The componentDidCatch method is also called after an error in a descendant component is thrown. Apart from the error thrown, it is passed one more argument which represents more information about the error: componentDidCatch(error, info) { } In this method, you can send the error or info received to an external logging service. Unlike getDerivedStateFromError, the componentDidCatchallows for side-effects: componentDidCatch(error, info) { logToExternalService(error, info) // this is allowed. //Where logToExternalService may make an API call. } }; } componentDidCatch(error, info) { console.log(`Error log from componentDidCatch: ${error}`); console.log(info); } render() { return null } } export default ErrorBoundary; Also, since the ErrorBoundary can only catch errors from descendant components, we’ll have the component render whatever is passed as Children or render a default error UI if something went wrong: ... render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } I have simulated a javascript error whenever you add a 5th chat message. Have a look at the error boundary at work: Conclusion It’s been a long discourse on the subject of lifecycle methods in React — including the more recent additions. I hope you understand how these methods work a little more intuitively now. Catch you later! “The (new) React lifecycle methods in plain, approachable language” superb Explanation So how does one use the functionality of `getSnapshotBeforeUpdate` in a functional component instead of a class component?
https://blog.logrocket.com/the-new-react-lifecycle-methods-in-plain-approachable-language-61a2105859f3/
CC-MAIN-2019-39
refinedweb
3,488
57.37
Subject: Re: [boost] [process] The Formal review preiod is nearing the end From: Nat Goodspeed (nat_at_[hidden]) Date: 2016-11-07 16:14:53 On Mon, Nov 7, 2016 at 12:52 PM, Klemens Morgenstern <klemens.morgenstern_at_[hidden]> wrote: > Am 07.11.2016 um 21:09 schrieb Nat Goodspeed: >> * any_initializer could still be used with any templated initializer >> type. Isn't that still true? > You're right, those were templated too. BUT the executor was actually not a > template, so you could've written on_success(windows::executor& e). That is > now different. I don't know how a type erasure could be done here, but I > could write a variant. > The reason is, that some properties/initializers require access the the > sequence, mainly to obtain the reference of the io_service. Please try that? I want a custom initializer to be able to access such things too. >> * Klemens states that the machinery needed to write custom >> initializers is currently in the detail namespace. I want it to be >> promoted out of the detail namespace: I want support for custom >> initializers to be a documented, supported feature of the library. If >> the library is not yet "done" in that respect, then let's consider it >> again when it's more fully baked. > Ok, so you have three things you can do: use custom handler for events, as > in > > child c("foo", on_error([](auto & exec, const std::error_code & > ec){std::cerr << ec.message() << std::endl;}); > > which is already public & documented (or at least mentioned in the > documentation). I saw that, but was misled by the fact that the documentation showed a nullary lambda. In any case I'm more interested in a custom initializer that can self-consistently intercept more than one such event. > Secondly there is the basic inheritance of "handler" > (currently private, but needlessly so) > > struct foo : boost::process::detail::handler > { > template<typename Exec> > void on_error(Exec & exec, const std::error_code & ec) > { > std::cerr << ec.message() << std::endl;} > }; > }; > > foo f; > child c("foo", foo); > > This has additional features like async_handler, where you can write an > on_exit handler etc. and there's a function which get's the passed > io-service; so it's a bit more rich than in 0.5. Good! I think you're saying that this feature is stable? Let's just move it out of "detail." > Now the third option (and most complicated) would be that you declare a tag > for a type, provide a builder and a initializer. I won't explain that here > in detail, but let's say "foo" can be internally constructed from a sequence > of "bar". > > The reason this is not public, is because I'm not sure what should be public > and what not and I'm not sure if it works as a public interface the way it > does internally. I think that needs some experience from someone other than > me, actually implementing an extension, to know that. I didn't think that it > would've been the best idea to put this in the version of the library to be > reviewed, especially since I need the experience of someone else. I really > think it makes much more sense to get the library accepted in its structure > before we - and by we I mean me and a user, e.g. you, - work out the details > of the public extension interface. Then may I suggest a namespace like "experimental" (borrowing a convention used in recent C++ documents)? My expectation from other Boost libraries is that I am explicitly supposed to avoid namespace "detail." The connotation is: hands off! "experimental" suggests "API is still unstable" while leaving the feature open for user testing. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2016/11/231494.php
CC-MAIN-2021-49
refinedweb
633
64.61
Simon Large wrote: ..snip.. Note that I do not disagree with Simon, but this reminds of something :-) > You do not receive a proper reply from us, because: > (X) It looks like you haven't read the docs yet > ( ) You bug report is incomplete or not a bug at all > ( ) Your feature request is not specified in enough detail > (X) You are violating our list etiquette > ( ) We are just in a bad mood There are lots of useful acronyms on this page, some of which may start to apply here ;-) NB What I would have done had I been the original poster (having read the docs of course) was to try it and see, it wouldn't take long to test an import checkout etc. I believe it's called testing.... Bill -- ___ oo // \\ "De Chelonian Mobile" (_,\/ \_/ \ TortoiseSVN \ \_/_\_/> The coolest Interface to (Sub)Version Control /_/ \_\.
http://svn.haxx.se/tsvn/archive-2005-01/1286.shtml
CC-MAIN-2013-20
refinedweb
151
60.01
I am taking part in a small programming competition online. Basically what I do is solve a task, write an algorithm and send my code to be automatically evaluated by the competition holder's server. The server accepts a wide variety of programming languages. All the tasks basically require the program to take input from the terminal and output a correct to the terminal as well. So on the competition holder's website I noticed that one of the languages they support is C++ and they use g++ to compile it. Well, since I'm not that fluent in C++ as opposed to C I thought I would return my answers in C. This worked great for the first task. However in the second task I constantly hit the limit set for the execution time of the program (2 seconds) This is my C code: #include <inttypes.h> #include <stdio.h> #include <stdint.h> #include <math.h> #include <stdlib.h> uint8_t get_bit(uint64_t k) { ... } int main(int argc, char *argv[]) { uint64_t n; uint64_t k; scanf("%u", &n); uint64_t i; for (i = 0; i < n; i++) { scanf("%u", &k); printf("%d\n", get_bit(k)); } return 0; } get_bit int main(int argc, char *argv[]) { uint64_t n; uint64_t k; cin >> n; uint64_t i; for (i = 0; i < n; i++) { cin >> k; cout.operator<<(get_bit(k)) << endl; } return 0; } get_bit It is probably because your code is may be (see comments) incorrect. You cant use %u with scanf and 64-bit integer. Check the third table here . You should use sth like %llu.
https://codedump.io/share/W7MgLpjQifsr/1/c-printing-extremely-faster-than-c
CC-MAIN-2018-09
refinedweb
259
74.9
table of contents other versions - jessie 3.74-1 - jessie-backports 4.10-2~bpo8+1 - stretch 4.10-2 - testing 4.16-1 - stretch-backports 4.16-1~bpo9+1 - unstable 4.16-1 NAME¶getutent, getutid, getutline, pututline, setutent, endutent, utmpname - access utmp file entries SYNOPSIS¶#include <utmp.h> struct utmp *getutent(void); DESCRIPTION¶New applications should use the POSIX.1-specified "utmpx" versions of these functions; see CONFORMING TO... FILES¶/var/run/utmp database of currently logged-in users CONFORMING TO¶XPG2, SVr4., following SUSv1, does not have any of these functions, but instead uses #include <utmpx.h> struct utmpx *getutxent(void); NOTES¶ Glibc notes¶The above functions are not thread-safe. Glibc adds reentrant versions #define _GNU_SOURCE /* or _SVID_SOURCE or _BSD_SOURCE; see feature_test_macros(7) */ #include <utmp.) EXAMPLE¶The following example adds and removes a utmp record, assuming it is run from within a pseudo terminal. For usage in a real application, you should check the return values of getpwuid(3) and ttyname(3). #include <string.h> #include <stdlib.h> #include <pwd.h> #include <unistd.h> #include <utmp); }
https://manpages.debian.org/jessie/manpages-dev/getutent.3.en.html
CC-MAIN-2022-27
refinedweb
181
55.61
Items In openHAB Items represent all properties and capabilities of the user’s home automation. While a device or service might be quite specific, Items are unified substitutions inside the openHAB world. Items can be Strings, Numbers, Switches or one of a few other basic Item types. A programmer can compare Item types with base variable data types of a programming language. A unique feature of openHAB Items is the ability to connect them to the outside world via Bindings. An Item does not simply store information that is set by software (e.g., OFF, 3.141 or “No Error”); the information stored by an Item may also be set by actions that take place in your home. But let’s not get ahead of ourselves. The rest of this page contains details regarding Items and is structured as follows: - Introduction - Item Definition and Syntax Introduction Items are basic data types and have a state which can be read from, or written to. Items can be linked to a Binding channel for interaction with the outside world. For example, an Item bound to a sensor receives updated sensor readings and an Item linked to a light’s dimmer channel can set the brightness of the light bulb. There are two methods for defining Items: Through Paper UI. Generally all 2.x version Bindings can be configured through Paper UI. (Note that 1.x and legacy Bindings do not offer this option) Through text .itemsfiles located in the $OPENHAB_CONF/itemsfolder. Files here must have the extension .items; you may create as many .itemsfiles as needed. However, each Item must be unique across all .itemsfiles. Refer to the installation docs to determine your specific installation’s folder structure. Generally 1.x version Bindings can only be bound to Items through .items files. 2.x Bindings may be configured using either method described above. Assumptions for Paper UI: The examples below assume that the user is using a text editor to create a .items file. While the way of defining an Item using the graphical, interactive Paper UI is different, the elements and the nature of an Item definition are identical using either method. Editor Recommendation: It’s recommended to edit .items files using one of the openHAB supporting editors. Doing so will provide you with full IDE support including features such as syntax checking, and context assistance. Item Definition and Syntax Items are defined using the following syntax: itemtype itemname "labeltext [stateformat]" <iconname> (group1, group2, ...) ["tag1", "tag2", ...] {bindingconfig} - Fields must be entered in the order shown itemtypeand itemnameare manadatory - All other fields are optional - Fields may be separated by one or more spaces, or tabs - An Item definition may span multiple lines Examples: Switch Kitchen_Light "Kitchen Light" {mqtt="<[...], >[...]" } String Bedroom_Sonos_CurrentTitle "Title [%s]" (gBedRoom) {channel="sonos:..."} Number Bathroom_WaschingMachine_Power "Power [%.0f W]" <energy> (gPower) {channel="homematic:..."} Number Livingroom_Temperature "Temperature [%.1f °C]" <temperature> (gTemperature, gLivingroom) ["TargetTemperature"] {knx="1/0/15+0/0/15"} The last example above defines an Item with the following fields: - Item type Number - Item name Livingroom_Temperature - Item label “Temperature” - Item state formatted to display temperature in Celsius to one-tenth of a degree - for example, “21.5 °C” - Item icon with the name temperature - Item belongs to groups gTemperatureand gLivingroom(definition not shown in the example) - Item is tagged as a thermostat with the ability to set a target temperature (“TargetTemperature”) - Item is bound to the openHAB Binding knxwith binding specific settings (“1/0/15+0/0/15”) The remainder of this article provides additional information regarding Item definition fields. Type The Item type defines what kind of state can be stored in that Item and which commands the Item will accept. Item types are comparable to basic variable data types in programming languages. Each Item type has been optimized for a particular kind of component in your smart home. This optimization is reflected in the data and command types. Available Item types are: More details about all of the available Item types and their commands are available under Concepts, see: Item Types Overview To learn about the technical internals of the individual Item types, please refer to: Javadoc on Generic Item and its subclasses Name The Item name is used to uniquely identify an Item. The name must be unique across all .items files in your openHAB configuration. The only characters permitted in an Item name are letters, numbers and the underscore character. Spaces and special characters are not permitted. A good Item name is self-explanatory and hints at its Item type and interaction options. A good hierarchical arrangement allows you to create common-sense groupings of Items. Names may be organized by function, and/or location. Users are advised to establish and follow a consistent naming scheme for Items. You may wish to think of a logical naming hierarchy that makes sense to you and apply that consistently in your openHAB installation. Having a well thought out naming scheme can be especially important as your installation grows. An Item naming scheme with a physical or logical top-down will ensure you can easily identify the function or purpose of the Item, especially over time. The following naming style guide is recommended: Words build a physical or logical hierarchy Every word of the Item name starts with an uppercase letter Words should be separated by an underscore character, except for words that logically belong together Names that reoccur frequently, such as the names of rooms or appliances, may be abbreviated to reduce overall name length. (Example: Bathroom = BR) Examples: Group is a special Item type that may be used to nest or combine Items. Users are encouraged to apply the style guide above to group names as well as Item names. Two naming schemes are established in the community for Group names: - Use a plural word form (e.g. Batteries) where possible. Otherwise the word “Group” may be appended for clarity. - Prepend a lowercase “g” to the name (e.g. gBattery) Label Label text is used to describe an Item in a human-readable way. Graphical UIs will display the label text when the Item is included, e.g. in Basic UI in a Sitemap definition. Some I/O services (e.g. the Amazon Alexa skill) also use the label to match an external voice command to an Item. In textual configurations the label, in quotation marks, appears next to the optional state presentation field in square brackets (see below). The label for the Item in the following example is “Temperature”: Number Livingroom_Temperature "Temperature [%.1f °C]" State The state of an Item depends on the Item type, the Channel bound to the Item, and internal or external events. A analogy can be drawn between the state of an Item and the value of a variable in a computer program. Item State This section provides information about what a user can expect regarding the behavior of the state of an Item. Items are created with a state of NULL Operations in openHAB such as a user interacting with the Item using the Basic UI, or a Binding updating the state of an Item will change the state of the Item An Item’s state may also be set through a Binding which may be reacting to changes in the real world A Binding may set the state of an Item to UNDEFif it looses communications with a Thing (for example, a Z-wave doorbell with a dead battery). The Binding may also set the state to UNDEFif an error exists in the binding configuration, or under other conditions N.B. Many openHAB users find that it can be very useful to use Persistence and System started rules so that their systems behaves in a predictable way after an openHAB restart. Command vs. Status Users should bear in mind the difference between an Item used to send a command to a Thing, and an Item that reflects the status of a real-world Thing in the UI. This distinction may seem obvious, but it can be a little confusing when an Item appears not to reflect the correct status of a Thing. For example, let’s say you have a Switch Item that is used to turn on a light. You insert this Item into a sitemap. You call up the sitemap and switch on the light using the UI. The switch icon changes from red to green, but you notice that the light does not turn on. What happened? Perhaps the Switch physical device is faulty or perhaps the device lost communications with your network. In any case, the UI performed correctly - it reflected the fact that you sent a command to the Switch Item. What the UI did not do is convey the status of the device being switched. Of course, this is the correct. As of this point, you do not have any Item in your sitemap that would do this. If it is critical that you know that the light came on, you could install a sensor that monitors light level. You could then, through the appropriate Binding, reflect light level changes through a Thing to an Item. Then you add the light-level Item to your UI. Now when you send the Switch Item command, and you see a corresponding increase in light level in the room, you know for sure that your command has been received and acted upon, because you have a return status Item in your UI. State Presentation The Item definition determines the Item’s textual state presentation, e.g., regarding formatting, decimal places, unit display and more. The state presentation is part of the Item label definition and contained inside square brackets. The state presentation for the Item in the following example is “ %.1f °C”: Number Livingroom_Temperature "Temperature [%.1f °C]" If no state presentation and no square brackets are given, the Item will not provide a textual presentation of it’s internal state (i.e. in UIs no state is shown). This is often meaningful when an Item is presented by a non-textual UI elements like a switch or a diagram. Formatting of the presentation is done applying Java formatter class syntax. If square brackets are given, the leading % and the trailing formatter conversion are mandatory. Free text, like a unit, can be added before or after the formatter string. A few examples are given below: Number Livingroom_Temperature "Temperature [%.1f °C]" // e.g. "23.5 °C" String Livingroom_TV_Channel "Now Playing [%s]" // e.g. "Lorem ipsum" DateTime Livingroom_TV_LastUpdate "Last Update [%1$ta %1$tR]" // e.g. "Sun 15:26" Number Livingroom_Clock_Battery "Battery Charge [%d %%]" // e.g. "50 %" State Transformation Transformations can be used in the state part of an Item, to translate the raw state of an Item into another language, or to convert technical values into human readable information. In the example below, the entry MAP(window_esp.map) causes the output of the Contact Item to be translated from “CLOSED”, to the Spanish “cerrado”: Contact Livingroom_Window "Ventana del salón [MAP(window_esp.map):%s]" Please refer to the article on Transformations for more usage details and a list of available transformation services. Icons The icon name is used by openHAB to select the image to display next to an Item name when using one of openHAB’s UIs, e.g. Basic UI. The icon name appears between angle brackets “<>”. In the example below, the “switch” icon has been selected: Switch Livingroom_Light "Livingroom Ceiling Light" <switch> openHAB provides a set of classic icons by default. Users may add their own icons in either png or svg format in the openHAB icons configuration folder, $OPENHAB_CONF/icons/classic/. The following guidelines apply to user-added icon files: - Only pngor svgfile formats may be used - Icon filenames may include lowercase letters, numbers and underscores ( _) - Uppercase letters and special characters are prohibited - Hyphens ( -) are reserved for Dynamic Icons (see below) - Example filenames: - Good: myswitch.svg, power_meter.png, error23.svg - Bad: PC_Display.svg, power-meter.png, tür⇔.svg Bitmaps or Vector Graphics: openHAB can work with either Bitmap ( png) or Vector ( svg) icon files. The format should match the display capabilities of the user interfaces in use (e.g. Basic UI). It is thereby important to decide on one format beforehand; vector graphics are recommended. The setting can be changed via Paper UI for most user interfaces. Please check the user interface documentation if in doubt. Note that image files with the wrong file ending will be ignored. Users may substitute their own icon for an icon from the default icon set by placing a file in the $OPENHAB_CONF/icons/classic/ folder with the same filename as the name of the icon being substituted. Dynamic Icons Some icons are dynamically selected by openHAB depending on the Item’s state. For example, a “switch” icon may appear to be green when the Item is “ON” and red when the item is “OFF. Behind the scenes, openHAB is actually selecting two different icon files depending upon the Item state - switch-on or switch-off. A third default icon file, switch, is required as well. This icon file matches when none of the other icon files match the Item state (e.g. when the Item is in an undefined state). Dynamic icon filenames follow the pattern below: <name>-<state>.<extension> <name>- the name of the icon set -<state>- the Item state the icon maps to (e.g. “ON” or “OFF”, “OPEN” or “CLOSED”) <extension>- bitmap ( png) or vector graphic ( svg) icon file extension (see above) Dynamic icon sets may consist of as many state-specific icon files as needed. Each set must meet the following criteria: A default icon is mandatory. The default icon filename is the name of the icon without a hyphen or state (e.g. switch.svg) Icon filenames must follow the naming restrictions given for icons above The state name must reflect the Item’s raw state. Transformations applied in the state presentation definition of the Item have no influence on icon selection. The state portion of the icon name must be in lowercase letters Example: The user defines the “Livingroom_Light” and “Livingroom_Light_Connection” Items: Switch Livingroom_Light "Livingroom Ceiling Light" <myswitch> String Livingroom_Light_Connection "Livingroom Ceiling Light [MAP(error.map):%s]" <myerror> On the filesystem, the following icon files are provided by the user: Take note, that the Transformation used in the Livingroom_Light_Connection Item doesn’t effect the needed state specific icons - the icon selection considers “myerror”, not the contents of the error.map file. Number State Matching Rule: For Number Items the equal or next lowest state icon that can be found will be used. For a dimmable light (0-100%), you might provide icons as in the example: Just as with regular icons, user-defined dynamic icon sets may be configured via the custom icons folder $OPENHAB_CONF/icons/classic/. Groups The Group is a special Item type that can be used to define a category or collection into which you can combine other Items or Groups. An Item may be put into one or more groups, and groups may be nested inside other groups. The general syntax for Group Items is as follows: Group groupname ["labeltext"] [<iconname>] [(group1, group2, ...)] The Group item is commonly used to define hierarchies of Items from different perspectives. For example: - Location-oriented or physical perspective: - Floors in your house → Rooms on that floor → An appliance in that room… - Functional or logical perspective: - Maintenance Group → All battery states → Individual battery states in percentage - Further examples: all lights, all room temperatures, combined power consumption These relationships can be exploited in Sitemaps or in automation rules to navigate through the hierarchically organized Items or to perform computations and updates on subsets of similar Items. Example: // Overarching group Group House // Location perspective Group GroundFloor (House) Group Livingroom (GroundFloor) // Functional perspective Group Sensors (House) Group Temperatures (Sensors) // Example Item Number Livingroom_Temperature "Temperature [%.1f °C]" (Livingroom, Temperatures) The example shows an Item which stores the temperature of the living room called Livingroom_Temperature. From a location perspective, you may have a group called Livingroom. When you add Livingroom_Temperature to the Livingroom group, Livingroom_Temperature is automatically part of the GroundFloor and House groups. This is because Livingroom is a member of the GroundFloor group, and GroundFloor is a member of the House group. From a functional perspective, the Living room temperature can also be seen as one of many temperatures in the automation setup. Therefore the addition of Livingroom_Temperature to a functional group called Temperatures, which itself belongs to the Sensors group, seems reasonable. Using nested group hierarchies such as these allows a rule to iterate through all sensors on the ground floor for maintenance actions, for example. Because of the hierarchical structure of your group items, the rule will be clean and short. Additionally, the rule will not need to be modified when a new Item is added to the Temperatures group. Group Type and State As you are now aware, an Item can have a state (e.g. “ON”, “OFF”). A Group Item can also have a state. The Group’s state is determined by the state of all its Items, and the aggregation function specified in the group definition. The general syntax for groups with a specific item type and aggregation function is: Group[:itemtype[:function]] groupname ["labeltext"] [<iconname>] [(group1, group2, ...)] - If the aggregation function is omitted, the function EQUALwill be used - If the aggregation function and itemtypeare omitted, no group state will be aggregated from member Items Group state aggregation functions can be any of the following: Boolean group state functions additionally return a number representing the count of member Items of value ‘value1’ (see example below). Because the group state is an aggregation of multiple Item states, not every Item state change results in a change of the group state. Note that aggregation functions can only be used on compatible Item types. Incompatible Item types within a Group may result in the invalid aggregation result UNDEF. Examples: Group:Number Lights "Active Lights [%d]" // e.g. "2" Group:Switch:OR(ON, OFF) Lights "Active Lights [%d]" // e.g. ON and "2" Group:Number:AVG Temperatures "All Room Temperatures [%.1f °C]" //e.g. "21.3 °C" The first two examples above compute the number of active lights and store them as group state. However, the second group is of type switch and has an aggregation function of OR. This means that the state of the group will be ON as soon as any of the member lights are turned on. Groups do not only aggregate information from individual member Items, they can also accept commands. Sending a command to a Group causes the command to be sent to all Group members. An example of this is shown by the second group above; sending a single ON or OFF command to that group turns all lights in the group on or off. The third example computes the average temperature of all room temperature Items in the group. Tags added to an Item definition allow a user to characterize the specific nature of the Item beyond it’s basic Item type. Tags can then be used by add-ons to interact with Items in context-sensitive ways. Example: A Light in a typical home setup can be represented by a Switch, a Dimmer or a Color Item. To be able to interact with the light device via a natural voice command, for example, the fact that the Item is a light can be established by adding the “Lighting” tag as shown below. Switch Livingroom_Light "Livingroom Ceiling Light" ["Lighting"] Tagging is a new feature and only a few I/O add-ons have implemented it. The easiest way to determine if tags have been implemented in a specific add-on is to see if the add-on documentation explicitly discusses their usage. Tags will be ignored if no Items in the openHAB installation support it. See the Hue Emulation or HomeKit Add-on documentation for more details. Binding Configuration One of the greatest strengths of an openHAB automation system is the sheer number of devices you can interact with. See “currently available Bindings” for a list of available Bindings. This capability of interacting with real-world things is enabled through the association of Bindings with Items. Once an Item is associated with a Binding, the state of one aspect of a device is reflected in openHAB (e.g., you can see if a light is on or off in one of the user interfaces). Additionally, you have the opportunity to interact with a device through its Items, if interaction is supported for that aspect of the device (e.g., you can command the light to turn ON or turn OFF). The Binding of an Item is given in the last part of the Item definition between curly brackets e.g. {channel="..."} in the example below: Number Livingroom_Temperature "Temperature [%.1f °C]" {channel="..."} Users should note that there are significant differences between how Items are associated with devices between 1.x Binding configuration and 2.x Channel linking. These are described below. 1.x Binding Configuration To bind an Item to a Binding, you add a Binding definition in curly brackets at the end of the Item definition: Switch Phone_Mobile {ns="192.168.1.123:80"} Where “ns” is the namespace for a certain Binding like “network”, “netatmo”, “zwave” etc. Every Binding defines what values must be given in the Binding configuration string. That can be the id of a sensor, an ip or mac address or anything else. The information required for each binding is specified in the configuration information provided for each of the available Bindings. Examples: Switch Phone_Mobile "My Mobile Phone" {ns="192.168.1.123:80"} Number Netatmo_Indoor_CO2 "CO2 [%d]" {netatmo="00:00:00:00:00:00#Co2"} Number Azimuth "Azimuth [%d]" {astro="planet=sun, type=position, property=azimuth"} Contact Garage_Door "Garage door is [MAP(en.map):%s]" {zwave="21:command=sensor_binary,respond_to_basic=true"} In some cases, you will need to use legacy openHAB 1.x bindings with your openHAB 2.0 installation. In this case, you will need to enable this feature through the Paper UI menu by turning on “Include Legacy 1.x Bindings” found at /configuration/services/configure extension management/. You can then download the legacy .jar file and placed it in the $OPENHAB_CFG/addons/ folder. If further configuration is required then you will need to create an openhab.cfg file in $OPENHAB_CONF/services/ and paste the appropriate Binding configuration into this file. For all other native openHAB2 Bindings, configuration is done through a bindingname.cfg file in the OPENHAB_CFG/services/ directory (substitute the name of your binding for bindingname above). Some bindings will automatically create a .cfg file in $OPENHAB_CONF/services/. Inside these files are predefined variables which are required for the Binding to operate. In many cases you will need to view and edit these to suit your system. These variables can hold IP addresses, API keys, user names, passwords etc. These are all in plain text, so be careful who you share these with if some data is sensitive. 2.x Binding Configuration openHAB2 introduces the concept of Things and Channels. Unlike 1.x version Bindings which each define their own format for the Binding config that is defined on the Item itself, 2.x Bindings define those parameters in a Thing. Each Thing has one or more Channels, and Items are linked to one or more Channels. Some Bindings support automatic discovery of Things, in which case discovered Things will appear in the Inbox in the Paper UI. Once accepted, the new Thing will appear under Configuration > Things. Other Bindings support defining Things in a .things file located in the OPENHAB_CFG/things/ folder. See the Bindings configuration section for more information on how to discover or manually define Things for a given Binding. Paper UI Linking As described above, you can link an Item with a Channel using the Paper UI. - First create the Item in Paper UI under Configuration Items. - Next navigate to the Thing that has the Channel to link to the Item. - Click on the expand icon to the right of the Channel to link to the Item and press the +next to “Linked Items.” - Select the Item from the list and press “Link”. Text File Linking You may also link an Item with a Channel using the .items file located in the OPENHAB_CFBG/items/ folder. Information about available Channels and options can be found in the Binding readme or discovered via Paper UI. In Paper UI select a Thing to learn about Channels it supports. Linking an Item to a Channel is of the form {channel="channel id"}. Examples: Switch Phone_Mobile "My Mobile Phone" {channel="network:device:devicename:online"} Number Netatmo_Indoor_CO2 "CO2" {channel="netatmo:NAMain:home:inside:Co2"} Number Azimuth "Azimuth" {channel="astro:sun:home:position#azimuth"} Contact Garage "Garage is [MAP(en.map):%s]" {channel="zwave:21:command=sensor_binary,respond_to_basic=true"} Multi Binding/Channel Linkage An Item may be linked to multiple Bindings and/or Channels. Commands and Updates from and to these Items will be combined, and can be used in interesting ways. Example: Switch Office_PC {nh="192.168.3.203", wol="192.168.0.2"} Number Temperature {mysensors="24;1;V_TEMP", expire="5m,-999"} The first example shows a symbiosis of the network health Binding and the Wake-on-LAN Binding to interact with a PC. The second example shows a common use case for the expire Binding where the mysensors Binding will update temperature readings regularly but the expire Binding will also listen and eventually modify the Item state. Exception autoupdate autoupdate="false" is a special instruction which keeps the current state of the item, even if a command has been received. This way, the Item is unchanged unless you explicitly post an update to the item. Example: Switch Garage_Gate {binding="xxx", autoupdate="false"}
http://docs.openhab.org/v2.2/configuration/items.html
CC-MAIN-2018-51
refinedweb
4,303
54.52
## k8s on local Sometimes I want to run k8s on my local machine to check something. So far I've used Minikube and one bound to Docker Desktop, but I wondered there might be newer ways to do it. Then I found this thread: The following tools are introduced there: - Minikube - Microk8s - K3s - Kind - Desktop Docker - K3d - Kubeadm So I tried k3d, just because I felt I like it. ## k3d It seems k3d runs k3s on Docker, which is also introduced in the thread above. I was confused a little bit when I thought Docker container which is for running Docker containers... but anyway I tried it. My laptop is Ubuntu, but it should work (I hope) on Windows & Mac because it's Docker. Firstly, I installed it reading the README (it supports brew as well): $ curl -s | bash Then, I created cluster and set configuration for kubectl: $ k3d create $ export KUBECONFIG=$(k3d get-kubeconfig) It really worked! $ kubectl get pods -A NAMESPACE NAME READY STATUS RESTARTS AGE kube-system local-path-provisioner-58fb86bdfd-kvmdh 1/1 Running 0 3m40s kube-system coredns-57d8bbb86-grbbr 1/1 Running 0 3m40s kube-system helm-install-traefik-4qr7t 0/1 Completed 0 3m40s kube-system svclb-traefik-j8c49 3/3 Running 0 3m5s kube-system traefik-65bccdc4bd-vtk9r 1/1 Running 0 3m5s $ kubectl get svc -A NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE default kubernetes ClusterIP 10.43.0.1 <none> 443/TCP 5m57s kube-system kube-dns ClusterIP 10.43.0.10 <none> 53/UDP,53/TCP,9153/TCP 5m56s kube-system traefik LoadBalancer 10.43.80.235 192.168.48.2 80:30107/TCP,443:31822/TCP,8080:31373/TCP 5m5s It seems to use traefik for a LoadBalancer service. ## Istio? I hit upon an idea whether Istio could run on it. Then I found this issue: It seems he successfully ran Istio on it after he turned off traefik to avoid port conflict. Let's try it. ### Create k3d cluster without traefik # Delete the previous cluster $ k3d delete # Create a cluster without traefik $ k3d create --server-arg --no-deploy --server-arg traefik # Generate config $ export KUBECONFIG=$(k3d get-kubeconfig) # Check $ kubectl get pod,svc -A NAMESPACE NAME READY STATUS RESTARTS AGE kube-system pod/local-path-provisioner-58fb86bdfd-h6npn 1/1 Running 0 13m kube-system pod/coredns-57d8bbb86-zkjkq 1/1 Running 0 13m NAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE default service/kubernetes ClusterIP 10.43.0.1 <none> 443/TCP 13m kube-system service/kube-dns ClusterIP 10.43.0.10 <none> 53/UDP,53/TCP,9153/TCP 13m Now I'm ready for installing Istio on it. ### Install Istio I found the latest version was already 1.4, but I felt I would like to try 1.3 because 1.4 was released just in this month. I downloaded Istio from here: and I installed Istio following the steps in this page: I've already installed Helm on my laptop, and I chose the option of using helm template. # Create a namespace for Istio $ kubectl create namespace istio-system # Install CRDs $ helm template install/kubernetes/helm/istio-init --name istio-init --namespace istio-system | kubectl apply -f - # Wait for the generation of the CRDs $ kubectl -n istio-system wait --for=condition=complete job --all Oh, I found the command has been changed. Previously, it was wc to check there're 23 CRDs created, but now it uses kubectl wait --for. Nice! $ helm template install/kubernetes/helm/istio --name istio --namespace istio-system | kubectl apply -f - I couldn't believe there's no error... This might be the first time for me to be able to install Istio without any troubles lol kubectl get svc,pod -n istio-system NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/istio-galley ClusterIP 10.43.10.191 <none> 443/TCP,15014/TCP,9901/TCP 2m21s service/istio-policy ClusterIP 10.43.86.131 <none> 9091/TCP,15004/TCP,15014/TCP 2m21s service/istio-telemetry ClusterIP 10.43.11.107 <none> 9091/TCP,15004/TCP,15014/TCP,42422/TCP 2m21s service/istio-pilot ClusterIP 10.43.126.19 <none> 15010/TCP,15011/TCP,8080/TCP,15014/TCP 2m21s service/prometheus ClusterIP 10.43.41.148 <none> 9090/TCP 2m21s service/istio-citadel ClusterIP 10.43.91.217 <none> 8060/TCP,15014/TCP 2m21s service/istio-sidecar-injector ClusterIP 10.43.117.133 <none> 443/TCP,15014/TCP 2m21s service/istio-ingressgateway LoadBalancer 10.43.69.0 192.168.96.2 15020:30845/TCP,80:31380/TCP,443:31390/TCP,31400:31400/TCP,15029:31842/TCP,15030:32247/TCP,15031:32685/TCP,15032:31093/TCP,15443:30499/TCP 2m21s NAME READY STATUS RESTARTS AGE pod/istio-init-crd-10-1.3.5-28hj7 0/1 Completed 0 5m40s pod/istio-init-crd-11-1.3.5-vmwmw 0/1 Completed 0 5m40s pod/istio-init-crd-12-1.3.5-84q77 0/1 Completed 0 5m40s pod/istio-security-post-install-1.3.5-jb66j 0/1 Completed 0 2m21s pod/svclb-istio-ingressgateway-ww22d 9/9 Running 0 2m21s pod/istio-citadel-5c67db5cb-hmhvb 1/1 Running 0 2m20s pod/prometheus-6f74d6f76d-tpjpc 1/1 Running 0 2m20s pod/istio-policy-66d87c756b-hf4wx 2/2 Running 3 2m21s pod/istio-galley-56b9fb859d-7jmsq 1/1 Running 0 2m21s pod/istio-sidecar-injector-5d65cfcd79-lhh6k 1/1 Running 0 2m20s pod/istio-pilot-64478c6886-9xm7b 2/2 Running 0 2m20s pod/istio-telemetry-5d4c4bfbbf-g4ccz 2/2 Running 4 2m20s pod/istio-ingressgateway-7b766b6685-5vwg5 1/1 Running 0 2m21s Next, I tried to run a sample application on the Istio. ### Deploy bookinfo sample application To check it actually works, I deployed bookinfo sample application included in Istio: # Enable automatic sidecar injection $ kubectl label namespace default istio-injection=enabled # Deploy apps $ kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml # Wait for the deployment finished for example using watch $ kubectl get pods -w NAME READY STATUS RESTARTS AGE details-v1-78d78fbddf-5db8b 0/2 PodInitializing 0 37s reviews-v1-7bb8ffd9b6-rdgjc 0/2 PodInitializing 0 37s ratings-v1-6c9dbf6b45-p7567 0/2 PodInitializing 0 36s productpage-v1-596598f447-nj6wx 0/2 PodInitializing 0 36s reviews-v3-68964bc4c8-qrhc4 0/2 PodInitializing 0 37s reviews-v2-d7d75fff8-65f4q 0/2 PodInitializing 0 37s # Create ingress gateway for bookinfo $ kubectl apply -f samples/bookinfo/networking/bookinfo-gateway.yaml After that, I confirmed External IP of LoadBalaner service: $ kubectl get svc -n istio-system istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}' 192.168.96.2 and opened the following URL with the IP: http://{The IP Address}/productpage I was surprised again that it worked! The memory usage of the container with bookinfo was around 2GiB: $ docker stats --no-stream CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 598bd6d07c85 k3d-k3s-default-server 52.24% 1.909GiB / 15.4GiB 12.40% 819MB / 21.7MB 1.41MB / 818MB 899 Thought it wouldn't be easier to solve problems if something happens somewhere, it seems very convenient to run k8s on local with k3d. Posted on by: Mitz I like Java, SpringBoot, Thymeleaf, Docker, Scrum, DDD and love my daughters. Discussion Thanks for your great post, however I wasn't able to access the http pages using the gateway service external ip! I just had to expose the 80 port with the following extra parameters when creating the k3s cluster: k3d create --publish 8080:80 --server-arg --no-deploy --server-arg traefik Then I was able to browse successfully: localhost:8080/productpage finally, you should note that you can easily access the Kiali dashboard with: istioctl dashboard kiali
https://dev.to/bufferings/tried-k8s-istio-in-my-local-machine-with-k3d-52gg
CC-MAIN-2020-40
refinedweb
1,290
52.49
- I need help for this copy byte code ... - Trying to get Java to ask the user for a number - I need some help... Please ! - [SOLVED] I'm not sure what I need to do next. - flight reservation code problem... - Need help with user imput - Switch problem. How do I return to my menu? - Why wont my program calculate sales tax? - Need Help on Looping Program!! Beginner!! - Array - Problem with the loop ..... ;( - Help!! Need to add a few things and I be lost!! - My program wont print the sum of the rows in a two-dimensional array - Need help with my hangman program! - Random suit and card with arrays - A deck of cards - Syntax error on token ";", { expected after this token please HELP - [SOLVED] Help reading a file to decode or encode - Unisex batroom - [SOLVED] Beginner, stuck on implementing while loop, compiles fine but still won't run - Putting codes in order...... - simple translator GUI ?? - Wheel of Fortune - Simple Game - non-static method getDimensions() cannot be referenced ... - I'm confused - HELP WITH MY BEGINER JAVA CODE.. - StdDraw Cannot be Resolved?? - [SOLVED] Printing an ArrayList of user-defined Objects - About loop - Need help with making a menu that sits on left side of JFrame - Need help - JOptionPane display on seperate lines - Help with conversion - Temperature Converting Application - Memory Card Game JButtons Array - Screen is flippering / flickering. - code not returning sum - Java Maze Problem (Please Help Guys) - Help on developing code for autoform fill in website - [SOLVED] homework troubles, any help would be appreciated - Trouble with writing/reading array to/from file - Unwanted appendices - A GUI issue. - Complete Noob -- A little help would be appreciated... - Password writing file - Java Homework Help - Check OS - Begginer Java - Bug in my code? - HTML Parsing - Help using String and character analyzers such as isDigit() and isLetter() - Run Time Error - NEED SOME HELP - I am having major issues with layouts - [SOLVED] where I'm wrong? - Java GUI not working - Initializing a downloaded class in another class - Java Multithreading Example - Issues - Midi message from an input device. Help needed with the messages I'm receiving. - extract selected text out of a pdf file using java - Exception in thread "main" java.lang.NullPointerException - Need help with what to do next - Help writing the IF statement for Y/N - [SOLVED] Linked List (adding alphabetically) - [SOLVED] how to format double value? - Creating a javadoc help please. - LinkedList : Adding elements in constructor - Couple compile errors for dice game - [SOLVED] java calendar - Java If Statement - Code help - Need help on access encrypted folder - substring StringIndexOutOfBoundsException - Code help with reset button error - i need help - [SOLVED] Not finding main class - Trying to make 3 images become random in an Applet. Need help - Eclipse not recognizing my method for class. - What am I missing? - Elements in double array (java) - [SOLVED] Printing A Histogram... - Initializing and Receiving Variables, Creating Methods - Help with inserting into a b-tree - I'm stuck on my Camelot game - [SOLVED] Please help with my while loop that turned into infinite loop! - Check if 'int' is empty - Scheduling algorithm - Creating object everytime object is called - BlueJ trouble or program trouble (Combining Arraylists) - [SOLVED] Traversing two different linked list - Reading ints into a multidimensional array - Auto Update JLabel on JButton Press? - Please Help!!! - Strange boxes appearing - Arraylist input help, quick question. - Can't Figure out Why I am Getting Null Pointer Exception - Please help me to do the search edit and delete. PLEASE :( - Literation Code - Help With errors. Please. - String Arrays [] - Need help with a Java Assignment regarding enums and arrays - Help! | Slecht/niet runnen van .java - Help with assignment about a board game (enum and array question) - Popout Jframe, Everything is STACKING!!! Help! - help creating a virtual Object - help with circular linked list - Need help with Huffman coding, please? - Seperating String with comma - Why isn't this code working? - File Input Trouble - How to get rid of this? - GUI Help - Threads in BankAccount program - More GUI help - Google Chart from database Servlet not working - applet is not initialized. Help will be appreciated - repaint in a JButton while loop. - Network connectivity issues with my project - Need direction on how to get the output desired from Parking Ticket Simulator - Seeking help with a program. - Total Sales Error - [SOLVED] URLConnection inconsistency + SSCCE - How do I add Junit package - Happy Pi Day ; a Pi Game! - fcntl.ioctl equalient code in java ? - Exception at main... - Matrix multiplying using separate input classes and a GUI - [SOLVED] Array Population via .txt File - [SOLVED] Using variable across methods - [Newbie] Method will not execute. - My code return null, Why? - Super-beginner needs help! URGENT - n00b asking jspinner question - Overloading Method - Type mismatch: cannot convert from void to ClassX.MethodX - JAVA LOOP HELP!!! - replaceAll() help - Need Help! Out of bounds error on ARRAYS!! - [SOLVED] Help with my Java program: Making change from an entered double. - Not Reading From Text File - Help needed to figure out why I keep getting error messages in Eclipse - [SOLVED] Simple Library Program / Need feedback. - How to use GNU Crypto LIbrary in Matlab via Java Interface - Switch Case Problem help - Java Programming - Dice Game Help! - Decimal Bianry Converter - Certain Expectation for assignment - Why isn't this code working? - [SOLVED] Can't reassign boolean value! - Begginer : help would be much appreciated for this exercice! - need help on my project.. - Error In WavFile..... - [SOLVED] Array Index out of bounds Exception - How can you get the compiler to run more than one public class? - JSF - input field is not updated - Need helpt with sorting arrays? - Trouble Creating a DFS Maze - My polymorphism code won't work - problem with enum (int to months) - What did I do wrong here? - [SOLVED] Help with my Java program: Applet that draws 5 random circles. - Leap Year/Calendar Program. toString() method error. - [SOLVED] Error in calling JFrame's super. - Count number of 'coin'p coins in a "machine" - Inheritance not working! - Sorting a Linked List - Search Term Program Problem - Trying to print a method for a table - Dijkstra's code help - Help with understanding simple GUI Code - [SOLVED] Need help with Pick A Card Program Please - Passing variables with void methods - [SOLVED] System exit command is not working properly - need help with phone number program for homework - "Variable not initialized" - Can my board and rent fees be set up like this for a monopoly(Multi array for rents?) - i am having a problem with the distance formula,help needed! - Need help with calculating stock code. - Accessing Private Int in a Subclass - Need help with calculating stock with joptionpane - null pointer exception on extending a server class - Jquery issue? dont know if I can ask on thsi forum. - [SOLVED] Try Catch Problems - hi its mery , and iam new i have this code - problem with Random() - urgent help! - problem with printing to text area - Warning when I do a build - Problem with my poker program - Java Code Help on Draw method - Modulus with BigIntegers - Problem: Grabbing Ints from JTextField - [SOLVED] Combing println with for loop - How to use Get and Set methods - char problems - string identifier symbol not found - cannot find symbol error with defining a string - Am I doing this right? (demonstrate TWO sorting algorithms) - creating a simple console menu - [SOLVED] Exception in thread "main" java.lang.NoClassDefFoundError - Exception in thread "main" java.lang.NullPointerException - Error with taking float numbers from an input dialog box. - Starting a Path - Adding add/remove button to add/remove tab - how to add a JFrame listener for a JPanel - Formatting white space to 3 characters in parentheses - Help with using mergesort to sort a list of names alphabetically? - Problem of Making Jar - NullPointerException trouble - new to java, and need help with assigment - [SOLVED] Translate sentence to morse cod? - Regular expression handling - System.out.println("Message"); - this is easy for those who know java!! - Hello Hello - Game for Small Children Program - Image Doesn't Display with Qualified Image Path???? - No suitable driver found for jdbc:mysql://localhost/books - won't load png - png problem continued - how to plot the line graph using jfreechart reading from text file - java.lang.String cannot be cast to java.util.Hashtable - Help with Group Layout - Matrix Generator - Java Script or HTML - Read input, read file, find match, and output... URGENT HELP! - What is worng in my java code - Please help me solve this problem, this is really urgent! - HTML Unit Help - how to plot a line graph by reading the values from database? - [SOLVED] Char Array Increment + 1 - JOptionPane menu and multiple methods - [SOLVED] A little help please~~How should i fix it?? - I need a little help - Help with Bounded Buffer problem - [SOLVED] (LWJGL)openGL arraylist rendering problem - NEEDING HELP UNDERSTANDING A CODE FROM THREE CLASSES!!! - problem in plotting graph for same x-axis values - JDialog from JFrame button (GUI) - Switch position of nodes on list - AS Assignment project - Creating a game in Greenfoot - Needing some help with array getter and setter methods!! - Need help finishing my program - Problem w/ Hashmap. Null Pointer? - Chaos Problems. - Inheritance; Problem with Test class - Using a HTML5, CSS3 and jQuery website template, can't get the Java pop-ups to work.. - Problem with sorting by alphabetical order - [SOLVED] Write a program that merges two files containing alphabetized lists of student record - [SOLVED] Keyboard Listeners and ImagePanel - TFTP Server not allowing data transfer - How to load specific .midi (music) files from the cache?
http://www.javaprogrammingforums.com/sitemap/f-62-p-16.html?s=9f35327b73a0658ade09f5044aab0251
CC-MAIN-2016-18
refinedweb
1,552
64.41
Back to: Java Tutorials For Beginners and Professionals List Collections in Java with Examples In this article, I am going to discuss List Collections in Java with Examples. Please read our previous article where we discussed the Java Collections Framework. As part of this article, we are going to discuss the following pointers in detail. - List Interface in Java - Classes of List Interface - ArrayList Collection in Java - LinkedList Collection in Java - Difference Between ArrayList and LinkedList in Java - Vector Collections in Java - Stack Collection in Java - Comparison Between ArrayList, LinkedList, Vector, and Stack in Java List Interface in Java: In Java, the List interface is an ordered collection that allows us to store and access elements sequentially. It extends the Collection interface. In Java, we must import java.util.List package in order to use List. As a List is an interface, we cannot create objects from it. Classes of List Interface In order to use functionalities of the List interface, we can use these classes: - ArrayList - LinkedList - Vector - Stack These classes are defined in the Collections framework and implement the List interface. ArrayList Collection in Java: ArrayList is the implementation class of List Interface which is used to store a group of individual objects where duplicate values are allowed. ArrayList internally follows array structure, which means in ArrayList all the elements are stored in contiguous memory locations same as an array, but ArrayList size is not fixed. ArrayList is not a synchronized class. If any object is synchronized we can access only one thread at a time but if an object is not. synchronized then we can access multiple threads. Creating an ArrayList in Java Syntax : ArrayList<Type> al = new ArrayList<Type>(); Here, Type indicates the type of ArrayList. ArrayList Constructors in Java ArrayList<E> al = new ArrayList<E>(); This constructor is used to create the new ArrayList with a default capacity of 10 and the size of ArrayList is 0. ArrayList<E> al = new ArrayList<E>(int capacity); This constructor is used to create the new ArrayList with a default capacity of 10 and the size of ArrayList is 0. ArrayList<E> al = new ArrayList<E>(Collection obj); This constructor is used to create the new ArrayList by copying the elements of any existing Collection (List, Set). Points to Remember: - size means the number of elements that are stored in Collection. - capacity means the memory allocated for elements. - <E> is called Generic Parameter type. - E is the element type that must be a reference type but not any primitive type. Methods of ArrayList: We can use all Collections Method to work with the ArrayList. Sample Program to demonstrate ArrayList Collection in Java import java.util.ArrayList; import java.util.List; public class ArrayListDemo { public static void main (String[]args) { // Creation of ArrayList ArrayList <Integer> al = new ArrayList <Integer>(); //adding the elements into the list al.add (10); //autoboxing al.add (new Integer (20)); //manual boxing al.add (30); al.add (40); al.add (50); //Display elements of the List and its Size System.out.println (al); System.out.println (al.size ()); //inserting an element into the List at specified location al.add (1, 77); System.out.println (al); System.out.println (al.size ()); //modifying the existing element of the List by specifying its value al.remove (new Integer (30)); System.out.println (al); System.out.println (al.size ()); //removing the element of the List by specifying its index position al.remove (0); System.out.println (al); System.out.println (al.size ()); //Displaying elements of List 1 by 1 using for loop (accessing) for (int i = 0; i < al.size (); i++) { System.out.println (al.get (i)); } //Displaying elements of List 1 by 1 using forEach Loop (auto-unboxing) for (int v:al) { System.out.println (v); } //Searching an element System.out.println (al.contains (50)); //Copying the array list into another list ArrayList < Integer > al1 = new ArrayList < Integer > (al); System.out.println (al1); } } Output: Note: In add(), remove(), get(), set() methods if we write any wrong index which is not available then it will throw a run time exception called IndexOutOfBoundException. ArrayList supports storing multiple null values. ArrayList Example with Complex Data type in Java: import java.util.*; class Customer { String name; int balance; int id; //Costructor Customer (String s, int i, int j) { name = s; balance = i; id = j; } //toString() method is overridden to give a meaningful String representaion of each object. public String toString () { return "Name : " + name + "|Balance : " + balance + "|ID : " + id; } public static void main (String args[]) { // ArrayList will contain a collection of Customer's objects. ArrayList < Customer > arr = new ArrayList < Customer > (); //Creating Customer objects. Customer customer1 = new Customer ("Jay", 1000, 2); Customer customer2 = new Customer ("Shane", 7000, 3); Customer customer3 = new Customer ("Ricky", 5000, 1); Customer customer4 = new Customer ("Tom", 3000, 6); Customer customer5 = new Customer ("Mick", 6000, 4); //Storing objects in an ArrayList collection class. arr.add (customer1); arr.add (customer2); arr.add (customer3); arr.add (customer4); arr.add (customer5); for (Customer c:arr) System.out.println (c); } } Output: LinkedList Collection in Java with Examples: LinkedList is the implementation class of List Interface which is also used to store a group of individual objects where duplicate values are allowed. LinkedList internally follows a doubly linked list structure where all the elements are stored in the form of nodes that linked each other. The LinkedList in Java is not a synchronized class. LinkedList also supports multiple null values. This provides the functionality of LinkedList Data Structure. Each element in a linked list is known as a node. It consists of 3 fields: - Prev – stores an address of the previous element in the list. It is null for the first element. - Next – Stores an address of the next element in the list. It is null for the last element. - Data – Stores the actual data Note: Elements in linked lists are not stored in sequence. Instead, they are scattered and connected through links (Prev and Next). Creation of LinkedList Syntax : LinkedList<Type> ll = new LinkedList<Type>(); Here, Type indicates the type of LinkedList. LinkedList Constructors LinkedList<E> ll = new LinkedList<E>(); It is used to construct an Empty List. LinkedList<E> ll = new LinkedList<E>(Collection obj); It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection’s iterator. Note: There is no capacity concept for LinkedList. Methods of LinkedList: We can use all Collections Method to work with the LinkedList. Sample Program to demonstrate LinkedList Collection in Java import java.util.*; class LinkedListDemo { public static void main (String[]args) { LinkedList < String > animals = new LinkedList <> (); // Add elements to LinkedList animals.add ("Dog"); animals.add ("Cat"); animals.add ("Horse"); System.out.println ("LinkedList: " + animals); // Get the element from the linked list String str = animals.get (1); System.out.print ("Element at index 1: " + str); System.out.println (" "); //Iterator method Iterator < String > itr = animals.iterator (); while (itr.hasNext ()) { System.out.println (itr.next ()); } } } Output: LinkedList Example with Complex Data type in Java: import java.util.ArrayList; import java.util.LinkedList; class Student { String name; int age; Student(String na, int ag) { name = na; age = ag; } public String toString () { return "Name : " + name + " Age : " + age; } } public class LinkedListDemo { public static void main (String[]args) { LinkedList < Student > list1 = new LinkedList < Student > (); list1.add (new Student ("Haj", 20)); list1.add (new Student ("Raj", 19)); list1.add (new Student ("Sar", 18)); list1.add (new Student ("Kan", 17)); for (Student x:list1) { System.out.println (x); } } } Output: Difference Between ArrayList and LinkedList in Java: ArrayList is slower in insertion and deletion of elements because it internally requires shifting operations, but faster in accessing the elements because ArrayList uses index position for every element. LinkedList is faster in insertion and deletion of elements because it just requires modifying the links of nodes instead of shifting operations, but slower in accessing the elements because LinkedList does not use any index position. Vector Collections in Java Vector is an implemented class of List Interface. Vector class methods are by default synchronized. It is used to store a group of individual objects where duplicate values are allowed. Vector is exactly similar to ArrayList but ArrayList is not a synchronized class where Vector is a synchronized class. Vector is also called legacy class because it is available from Java 1.0 Version. It is similar to the ArrayList, but with two differences- - The vector is synchronized. - Java Vector contains many legacy methods that are not part of a collections framework. Note: It is recommended to use ArrayList in place of Vector because vectors are not thread-safe and are less efficient. Creation of Vector Syntax : Vector<Type> vector = new Vector<Type>(); Here, Type indicates the type of Vector. Vector Constructors Vector<E> v = new Vector<E>(); This constructor creates a single dimension array with a default capacity of 10. Vector<E> v = new Vector<E>(int capacity); This constructor sets a given capacity as a current capacity to a single dimension array. Vector<E> v = new Vector<E>(Collection obj); This constructor is used for migrating one collection with another collection for transferring data. Methods of Vector We can use all Collections Method to work with the LinkedList. We can also use legacy methods like addElement(), removeElement(), setElement(),…. Sample Program to demonstrate Vector Collection in Java import java.util.*; class VectorDemo { public static void main(String[] args) { Vector<String> mammals= new Vector<>(); // Using the add() method mammals.add("Dog"); mammals.add("Horse"); // Using index number mammals.add(2, "Cat"); System.out.println("Vector: " + mammals); // Using addAll() Vector<String> animals = new Vector<>(); animals.add("Crocodile"); animals.addAll(mammals); System.out.println("New Vector: " + animals); // Using get() String element = animals.get(2); System.out.println("Element at index 2: " + element); // Using iterator() Iterator<String> iterate = animals.iterator(); System.out.print("Vector: "); while(iterate.hasNext()) { System.out.print(iterate.next()); System.out.print(", "); } } } Output: Vector Example with Complex Data type in Java import java.util.*; class Fruits { String name; Fruits (String na) { name = na; } String getData () { return "Name : " + name; } } public class VectorDemo { public static void main (String args[]) { // create a vector with initial capacity = 2 Vector < Fruits > fruits_vec = new Vector < Fruits > (2); //add elements to the vector fruits_vec.add (new Fruits ("Grapes")); fruits_vec.add (new Fruits ("Melon")); fruits_vec.add (new Fruits ("Kiwi")); fruits_vec.add (new Fruits ("Apple")); //print current size and capacity of the vector System.out.println ("Vector Size: " + fruits_vec.size ()); System.out.println ("Default Vector capacity increment: " + fruits_vec.capacity ()); //add more elements to the vector fruits_vec.add (new Fruits ("Orange")); fruits_vec.add (new Fruits ("Mango")); fruits_vec.add (new Fruits ("Fig")); //print current size and capacity again System.out.println ("Vector Size after addition: " + fruits_vec.size ()); System.out.println ("Vector Capacity after increment: " + fruits_vec.capacity ()); } } Output: Stack Collection in Java: In Java, Stack is a class that falls under the Collection framework that extends the Vector class. The stack is a child class of Vector and implements List Interface. The stack stores a group of objects by using a mechanism called LIFO. LIFE stands for Last In First Out, which means the last inserted element deleted first. The stack data structure has the two most important operations that are push and pop. The push operation inserts an element into the stack and the pop operation removes an element from the top of the stack. Creation of Stack Syntax : Stack<Type> stacks = new Stack<Type>(); Here, Type indicates the Stack’s type. Stack Constructor public Stack() The Stack class contains only the default constructor that creates an empty stack. Methods of Stack We can use all Collection Methods. We can also use legacy methods of Vector Class like addElement(), removeElement(), setelementAt(), etc. But if we want to follow the LIFO mechanism we should use Stack methods like follows: - E push(E obj): This method will add new elements to the stack. - E pop(): This method deletes the top element available on Stack. - E peek(): This method just returns the top element available on Stack. Sample Program to demonstrate Stack Collection in Java import java.util.*; public class StackDemo { public static void main(String[] args) { Stack<Double> s = new Stack<Double>(); s.push(10.2); s.push(50.2); s.push(30.2); s.push(40.2); s.push(70.2); System.out.println(s); System.out.println(s.pop()); System.out.println(s); System.out.println(s.peek()); System.out.println(s); } } Output: Stack Example with Complex Data type in Java import java.util.*; class Sports { String name; Sports (String na) { name = na; } String getData () { return "Name : " + name; } } class StackDemo { public static void main (String[]args) { Stack < Sports > stack = new Stack < Sports > (); Sports s1 = new Sports ("Cricket"); Sports s2 = new Sports ("Football"); Sports s3 = new Sports ("Basketball"); Sports s4 = new Sports ("Table Tennis"); Sports s5 = new Sports ("Badminton"); stack.push (s1); stack.push (s2); stack.push (s3); stack.push (s4); stack.push (s5); stack.pop (); stack.pop (); // Returns the number of elements present in the stack System.out.println ("Stack size is " + stack.size ()); // check if stack is empty if (stack.empty ()) System.out.println ("Stack is Empty"); else System.out.println ("Stack is not Empty"); } } Output: Comparison Between ArrayList, LinkedList, Vector, and Stack in Java In the next article, I am going to discuss Cursors Collection Framework in Java with examples. Here, in this article, I try to explain List collections in Java with Examples and I hope you enjoy this List collection in Java with Examples article.
https://dotnettutorials.net/lesson/list-collections-in-java/
CC-MAIN-2022-27
refinedweb
2,239
50.02
1. comes with a large standard library that covers areas such as string processing like regular expressions, Unicode, calculating differences between files, Internet protocols like HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming, software engineering like unit testing, logging, profiling, parsing Python code, and operating system interfaces like system calls, file systems, TCP/IP sockets. 3. Explain what Flask is and its benefits? Answer: Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its. The user can modify the session if only it has the secret key Flask.secret_key. 4. What is the purpose of the PYTHONSTARTUP environment variable? Answer: PYTHONSTARTUP – It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH. 5. How will you convert an integer to a hexadecimal string in python? Answer: Converts an integer to a hexadecimal string. 6. What Is The Statement That Can Be Used In Python If The Program Requires No Action But Requires It Syntactically? Answer: The pass statement is a null operation. Nothing happens when it executes. You should use “pass” keyword in lowercase. If you write “Pass,” you’ll face an error like “NameError: name Pass is not defined.” Python statements are case sensitive. (Online training institute) 7. What Are Python Iterators? Answer:. 8. How is memory managed in Python? Answer:. 9. What is map function in Python? Answer: map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many tables are given. #Follow the link to know more similar functions. 10. What is multithreading? Give an example? Answer: It means running several different programs at the same time concurrently by invoking multiple threads. Multiple threads within a process refer the data space with the main thread and they can communicate with each other to share information more easily. Threads are light-weight processes and have less memory overhead. Threads can be used just for a quick task like calculating results and also running other processes in the background while the main program is running. 11. What’s the Difference Between a List and a Dictionary? Answer: A list and a dictionary in Python are essentially different types of data structures. Lists are the most common data types that boast significant flexibility. Lists can be used to store a sequence of objects that are mutable (so they can be modified after they are created). In Python, you can’t use a list as a “key” for the dictionary (technically you can hash the list first via your own custom hash functions and use that as a key). A Python dictionary is fundamentally an unordered collection of key-value pairs. It’s a perfect tool to work with an enormous amount of data since dictionaries are optimized for retrieving data (but you have to know the key to retrieve its value). It can also be described as the implementation of a hashtable and as a key-value store. In this scenario, you can quickly look up anything by its key, but since it’s unordered, it will demand that keys are hashes. When you work with Python, dictionaries are defined within curly braces {} where each item will be a pair in the form key: value. 12. Why Is It Important? Answer: Although this has nothing to do specifically with Python programming interview questions, there’s a good chance that you will have to answer these types of questions. In any position, technical or not, the behavioral aspects of each individual also play a critical in the selection process. This is because even if you’re the best Python programmer in the marketplace, it won’t mean much if you can’t perform efficiently and effectively on the job. 13. What Is the Accomplishment You Are Most Proud Of? Answer: This interview question is designed to test your storytelling skills in the context of a professional example. So it’s important to start by setting the stage for your example. You can do this by talking about where you were working at the time, the project you were working on, the people you worked with, how you worked (tools, processes, the time is taken), and the specific results. You will have to think on your feet as there may well be follow-up questions, so be prepared to dive in and get into the nitty-gritty details. It’s essential to use a recent example here, so keep it fresh and give the recruiter a chance to imagine your future success based on your past work experience. 14. When Would You Use a List vs. a Tuple vs. a Set in Python? Answer: A list is a common data type that is highly flexible. It can store a sequence of objects that are mutable, so it’s ideal for projects that demand the storage of objects that can be changed later. A tuple is similar to a list in Python, but the key difference between them is that tuples are immutable. They also use less space than lists and can only be used as a key in a dictionary. Tuples are a perfect choice when you want a list of constants. Sets are a collection of unique elements that are used in Python. Sets are a good option when you want to avoid duplicate elements in your list. This means that whenever you have two lists with common elements between them, you can leverage sets to eliminate them. 15. How many data types are there in Python? Answer: One of the more common interview questions on Python – you might get asked to either say the number or actually name them. Python has five different data types: string, list, number, dictionary, and tuple. 16. How will you differentiate between deep copy and shallow copy? Answer: We use a, a deep copy makes the execution of a program slower. This is due to the fact that it makes some copies for each object that is called. 17. How can you organize your code to make it easier to change the base class? Answer: You have to define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. You can also use this method if you want to decide dynamically (e.g., depending on the availability of resources) which base class to use. 18. What is a negative index in Python? Answer: traverse from right to left and iterate one by one till the start of the list. A negative index is used to traverse the elements into reverse order. 19. What is slicing in Python? Answer: Slicing is a mechanism used to select a range of items from sequence type like list, tuple, and string. It is beneficial and easy to get elements from a range by using slice way. It requires a : (colon) which separates the start and end index of the field. All the data collection types List or tuple allows us to use slicing to fetch elements. Although we can get elements by specifying an index, we get only single element whereas using slicing we can get a group of elements. 20. What is a dictionary in Python? Answer: The Python dictionary is a built-in data type. It defines a one-to-one relationship between keys and values. Dictionaries contain a pair of keys and their corresponding values. It stores elements in key and value pairs. The keys are unique whereas values can be duplicate. The key accesses the dictionary elements. 21. What are the different file processing modes supported by Python? Answer: Python provides three modes to open files. The read-only, write-only, read-write and append mode. ‘r’ is used to open a file in read-only mode, ‘w’ is used to open a file in write-only mode, ‘rw’ is used to open in reading and write mode, ‘a’ is used to open a file in append mode. If the mode is not specified, by default file opens in read-only mode. 22. How to overload constructors or methods in Python? Answer: Python’s constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object. We can’t overload constructors or methods in Python. It shows an error if we try to overload. 23.. 24.. 25.. 26. Can Python be used for web client and web server side programming? And which one is best suited to Python? Answer: Python is best suited for web server-side application development due to its vast set of features for creating business logic, database interactions, web server hosting, etc. However, Python can be used as a web client-side application which needs some conversions for a browser to interpret the client-side logic. Also, note that Python can be used to create desktop applications which can run as a standalone application such as utilities for test automation. 27.. 28. Explain the interpretation in Python? Answer: Programs in python run directly from the source code. 29.. 30. What is the Dictionary? Answer: - Dictionary objects can be created by using curly braces {} or by calling dictionary function - Dictionary objects are mutable objects - Dictionary represents a key-value base - Each key-value pair of Dictionary is known as an item - Dictionary keys must be immutable - Dictionary values can be mutable or immutable - Duplicate keys are not allowed but values can be duplicate - Insertion order is not preserved - Heterogeneous keys and heterogeneous values are allowed. 30. What Are The Implementation In Python Program? Answer: Python program can be implemented in two ways 1. Interactive Mode (Submit statement by statement explicitly) 2. Batch Mode (Writing all statements and submit all statements) In Interactive mode, the python command shell is required. It is available in the installation of python cell. In Interactive mode is not suitable for developing the projects & Applications Interactive mode is used for predefined function and programs. 31. How do I test a Python program or component? Answer: Python comes with two testing frameworks: The documentation test module finds examples in the documentation strings for a module and runs them, comparing the output with the expected output given in the documentation string. The unit test modules a fancier testing framework modeled. 31. How is Python executed? Answer: Python files are compiled to bytecode. which is then executed by the host. 32. How do you open an already existing file and add content to it? Answer: In Python, open(,) is used to open a file in different modes. The open function returns a handle to the file, using which one can perform read, write and modify operations. 33. When do you choose a list over a tuple? Answer:. 34. What are the generator functions in Python? Answer: Any function that contains at least one yield statement is called a generator function instead of a return statement. The difference between return and yield is, return statement terminates the function, and yield statement saving all its states pauses and later continues from there on successive calls. 35. How do you invoke the Python interpreter for interactive use? Answer: python or python.y where x.y is the version of the Python interpreter desired? 36. Why do you need to make your code more readable? Answer: We need to make our code more readable so that other programmer can understand our code. Basically, for a large project, many programmers work together. So, if the readability of the code is poor, it will be difficult for others to improve the code later. 37. How Python supports encapsulation with respect to functions? Answer: Python supports inner functions. A function defined inside a function is called an inner function, whose behavior is not hidden. This is how Python supports encapsulation with respect to functions. 38. What is the difference between range() and xrange() functions in Python? Answer: range() is a function that returns a list of numbers, which will be an overhead if the number is too large. Whereas, xrange() is a generator function that returns an iterator which returns a single generated value whenever it is called. 39. How do you perform pattern matching in Python? Explain? Answer:. 40. What is the difference between range & xrange? Explain? Answer: as the real memory sensitive system such as a cell phone that you are working with, as the range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast. 41. What is the difference between deep and shallow copy? Answer:. The the execution of the program slower due to making certain copies for each object that is been called. 42. What is the difference between NumPy and SciPy? Answer:. 43. What is the process of compilation and linking in python? Answer: The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter. The steps that’. 44. What is the namespace in Python? Answer: In Python, every name has a place where it lives. It is known as a namespace. It is like a box where a variable name maps to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object. 45. What are the rules for a local and global variable in Python? Answer: we need to declare it as ‘global’ explicitly. To make a variable globally, we need to declare it by using the global keyword. Local variables are accessible within the local body only. Global variables are accessible anywhere in the program, and any function can access and modify its value. 46. How Python does Compile-time and Run-time code checking? Answer: In Python, some amount of coding is done at compile-time, but most of the checking such as type, name, etc. are postponed until code execution. Consequently, if the Python code references a user-defined function that does not exist, the code will compile successfully. The Python code will fail only with an exception when the code execution path does not exist. 47. What are the Runtime Errors? Answer: The errors which occur after starting the execution of the programs are known as runtime errors. Runtime errors can occur because of Invalid Input Invalid Logic Memory issues Hardware failures and so on With respect to every reason which causes to runtime error corresponding runtime error representation class is available Runtime error representation classes technically we call as an exception class. While executing the program if any runtime error occurs corresponding runtime error representation class object is created Creating a runtime error representation class object is technically known as a rising exception While executing the program if an exception is raised, then internally python interpreter verify any code is implemented to handle the raised exception or not If a code is not implemented to handle raised exception then the program will be terminated abnormally 48. What is PIP software in the Python world? Answer: PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command line tool which can search for packages over the internet and install them without any user interaction. 49.. The beauty of the final block is to execute the code after trying for error. This block gets executed irrespective of whether an error occurred or not. Finally block is used to do the required cleanup activities of objects/variables. 50. What is an operator in Python? Answer: An operator is a particular symbol which is used on some values and produces an output as a result. An operator works on operands. Operands are numeric literals or variables which hold some values. Operators can be unary, binary or ternary. An operator which require a single operand known as a unary operator, which require two operands known as a binary operator and which require three operands is called ternary operator. 51. What Is the Biggest Challenge Facing Your Current Job Right Now? What Is Your Biggest Failure? Answer: This question comes up often regardless of the field because it helps the interviewer get an idea of your approach to problem-solving in your new potential role. The way you approach the answer will make you look awesome, or it will be a red flag. So it will be critical to think about this beforehand and answer the question without delay. As a rule, don’t complain about the management at your current job or blame the people you’re working with. It’s also not a good idea to pretend like your career has been a walk in the park. Instead, tailor your answer to a project you worked on, but don’t get specific about why the challenge turned out to be difficult in the first place. Instead, concentrate on the problem-solving process to highlight your skills. When it comes to your biggest failure, it’s critical that you don’t use this time to talk yourself down. If you can’t think of a specific scenario, think of a time when you were disappointed about something that didn’t work out. The primary objective is to show the interviewer how you managed to turn something negative into something positive. Note: SVR Technologies provide Latest Python Interview Questions and Python Tutorials for beginners and also for experienced candidates. If you are interested for Python Online Training or Python Learning videos courses then Feel free to Enquire now, Our Support team will ready to helps you for Improve skills. We offers 100+ latest and trending courses on every technology. All Python Interview Questions Python VideosDuration: 20 Hours | Version: 2.7, 3.7 - Experienced Faculty - Real-time Scenarios - Free Bundle Access - Course Future Updates - Sample CV/Resume - Interview Q&A - Complimentary Materials
https://svrtechnologies.com/python-programming-language-interview-questions/
CC-MAIN-2020-29
refinedweb
3,092
64.61
I’ve used Tailwind CSS for a few projects over the last several months, and it’s been steadily growing on me – to the point of it becoming my go-to tool for styling new projects. At the same time, I’m seeing a lot of people ask what all the hype is about, often in an effort to determine if it’s right for them too. I’ve responded to those questions a couple of times now, and thought it’d be handy to have a quick reference as to why I’ve come to like it myself, as well as the challenges I’ve experienced along the way. All of this is based on my own experience from recent memory, so it’s likely to change to some degree as time goes on. Still, hopefully it helps someone else grasp if it’s something they should try out themselves. Things I Really Like 1. I can prototype much more quickly. Other styling approaches I’ve used require me to jump between multiple different files just to stand up a page with some basic asthetics. At minimum, that’d mean an HTML file and a stylesheet. And whenever I was in a highly-componentized BEM project (like I most often was), that could mean a lot of files open at once – the file containing the HTML and then one SCSS file for each UI component I was writing. With Tailwind, however, all I really need to pay attention to is the HTML. Fewer VS Code tabs for my brain to manage means I can prototype more easily and quickly. 2. Built-in PurgeCSS means I only ship the styles I actually use. When working with other utility-based CSS frameworks, it’s a pain to ensure you don’t ship any of the CSS you don’t actually use. Depending on the framework, your options are to manually import the things you actually use, give up altogether, or try your hand at configuring a tool like PurgeCSS to remove unused classes on compilation. As of v1.4, Tailwind has PurgeCSS built in, with a lot of the hassle abstracted away, so I can focus on styling without worrying so much about CSS bloat. 3. I can throw away HTML without orphaning accompanying CSS. Especially when I’m prototyping something, it’s common for me to spontaneously throw out HTML I thought I’d need but don’t. When my styles and makeup are maintained separately, a second step is required to remove that unnecessary CSS. I often forget to do that, forever leaving it orphaned. The markup-driven styling provided by Tailwind means all I have to throw away is the HTML itself. Nothing else (unless I have some custom components I’ve composed somewhere, but that’s rare). 4. I don’t need to name so many things. It takes time, it’s hard, and I suck at it. When using Tailwind, the only time I need to dream up a class name is when I’m composing my own components, which isn’t often at all. For the most part, I can spend my time bringing my UI to life, rather than wasting it second-guessing what I chose to name something. 5. Consistent design token values (font sizes, colors, spacing, etc.) are set up for me. When starting with more of a bare-bones, roll-my-own styling approach, it’s a chore to determine what my base font sizes, colors, spacing values, and everything else should be. Tailwind offers consistent sets of these values out-of-the-box, while also enabling me to customize them as needed. 6. It’s easy to incrementally adopt in a project. If you want to leverage just some of the utilities provided by Tailwind, or want to migrate to it more slowly, it’s relatively easy to do so without overcommitting yourself or putting the entire project through a refactor. After setting it up (the most common way to do so is probably as a PostCSS plugin), you can either manually configure Tailwind to include only what you need, or rely on the aforementioned PurgeCSS integration to remove the styles you don’t use. I appreciate that flexibility. 7. The documentation is incredible. In particular, the search functionality in the Tailwind documentation is nearly psychic (and the “press ‘/’ to focus” feature is a huge nice-to-have). If I’m looking for some utility, my first search attempt nearly always returns what I need without requiring me to try again with different terms. It’s just good. Moreover, it’s fast, thorough, and filled with helpful examples. Some Challenges I’ve Seen My admiration for this tool is strong, but it’d be unfair to leave out the challenges I’ve had working with it. 1. The learning curve can be steep. At first, it sort of felt like I was relearning CSS itself, and that was frustrating. There’s a utility for virtually everything (it seems like), and trying to get my brain to map real CSS attributes to those utilities just took some time (I’m still working on it). This is where that documentation really shines, because if it weren’t for that, I’d have given up early on. 2. HTML can quickly become ugly & convoluted. Much of this is probably just preferential, or perhaps due to the fact that it goes against what I’ve become accustomed to while working with BEM for so long. But at the same time, when working with something like JSX in React or any other templating language infused with a moderate amount of logic, it can get rough to parse everything going on in a component with utility classes sprinkled everywhere. I experienced some of this pain when building TypeIt’s site with Tailwind + Gatsby. In order to fine-tune the styling I wanted, I had to do stuff like this: <div className={` lg:flex justify-center fixed lg:relative top-0 left-0 h-full w-full bg-white translate-left lg:translate-none overflow-scroll lg:overflow-visible pt-8 md:p-0 ${menuIsOpen ? "translate-none" : ""} `} > <ul className="self-start mx-auto lg:-mx-3 lg:mt-0 block lg:flex mb-8 lg:mb-0"> {links.map((link) => { return ( <li key={link.path} ref={navItemRef} className={`siteNavListItem flex px-5 flex-col lg:flex-row items-center font-light justify-center mb-5 lg:mb-0 relative`} > {/* link content... */} </li> ); })} </ul> </div> With so many utility classes in play, it was just hard to figure out the best way to format everything while keeping the entire file relatively legible. Admittedly, there are some tricks to help mitigate this, mainly relying on strategies Tailwind recommends to componentize parts of your UI, such as: - using Tailwind’s @applydirective to create single classes composed of utilities. - writing templates or JS components that accept the data you’d like to display. But these all feel like more work I just don’t want to do. All that said, “messy” HTML, at some level, may just be a necessary trade-off of using a styling approach like Tailwind does, much like any other approach has trade-offs of its own. Why Do You Like It? Despite the couple of challenges I’ve seen, Tailwind has allowed me to style UI components in a more productive fashion, and I’ll likely keep it around as my go-to tool for doing such things. Even so, that might not be the case for everyone. So, I’m curious to hear what you like about Tailwind, as well as the challenges you’ve encountered. Are there things you like or hate that I don’t mention here, or are even offshoots of any of them? Bring ’em up! Juho Vepsäläinen I found out using typed-html can give a nice component model that complements Tailwind nicely. For state I'm using Sidewind (my own solution although likely you want to go with Alpine as it's hugely popular and has 1000x GitHub stars :) ). I put these technologies together in a little starter kit, tailwind-webpack-starter, and it's shaping up nicely. I modeled the component APIs after Theme UI and all this combines into something that's typed TypeScript) and extremely light. It's an experimental approach but I like it so far as it gives a nice degree of control while having benefits of many paradigms that are out there at the moment. I've found Tailwind itself is a great starting point for styling work but it's a good idea to bring some structure around it and you can achieve this in the main frameworks (Angular, React, Vue) quite easily as far as I understand. There's even a Theme UI plugin so you can generate Tailwind classes out of it.
https://macarthur.me/posts/why-i-like-tailwind-css
CC-MAIN-2022-40
refinedweb
1,482
69.01
In defense of Test Driven Development hong ・2 min read In defense of Test Driven Development I'm still learning to write great code like everyone else. Recently there's been some articles bashing TDD. I would like to share what worked for me with TDD. OOP and TDD a good pair Good OOP should follow SOLID and clean code principles. Classes should be small and methods even smaller. This makes writing unit tests much easier as there is much less to test per test case. Clean code by Uncle Bob and POODR by Sandi Metz both dedicate large chapters to testing. This is not by accident. Test driven development is a huge part of writing maintainable code. If you are having problems with test driven development, perhaps your classes and methods are too long. Consider whether or not your code follows SOLID and clean code principles. Test cases first Before TDD, what I did was create a class and define the attributes and methods that I think I would need. I found this habit hard to break, until I forced myself to create test cases before I even wrote one line of code. How I did this was to create easier unit tests. Python example: def test_myobject: #check if the attribute exists self.assertTrue(hasattr(myobject, 'myattribute')) #check the type self.assertIsInstance(myobject.mylist, list) #check if function self.assertTrue(callable(myobject.mymethod) #check if attribute defaults to False self.assertFalse(myobject.my_false_attribute) This is very similar to creating the basic structure of a class without writing the actual class. Some would argue that these unit tests do not test anything and are not worth it. After all why would you test basic language concepts like variable assignment? I would say an object's public API is a contract and should be tested. Any change of these attributes will break code. This would be an easy fix, but also these unit tests are easy to write. This make it almost free. Tips Have your class and unit tests side by side when writing and updating code. If you update one, update the other. If your constructors contain any conditional assignment logic, then you should definitely write unit tests for this. I only write unit tests for methods that are public. If your private methods contain some tricky logic that needs to be tested, perhaps consider creating a mixin class for that method and exposing it publicly. If your test cases import a bunch of other classes, that can show you are testing a too much. Practice DRY (Don't repeat yourself) in testing code as well. Use mocks and stubs in replace of other objects that your unit tests depend on instead of importing other objects. Benefits Good test cases have made my flow much better. Now I can rapidly design and add new features and they mostly work on first run. If I do have errors, the issue is with integration and not the single object itself. Refactoring is also easier as I know when I break stuff. This is what worked for me. Good luck on your journey and help others along the way! Why might a project/company use a monorepo? What are the pros and cons of the "monorepo" approach? ...
https://practicaldev-herokuapp-com.global.ssl.fastly.net/cocoroutine/in-defense-of-test-driven-development-4h0e
CC-MAIN-2019-39
refinedweb
545
75.3
“We should do (as wise programmers aware of our limitations) our utmost best to … make the correspondence between the program (spread out in text space) and the process (spread out in time) as trivial as possible.” —Edsger W. Dijkstra, “Go To Considered Harmful” It’s a shame that his essay is most remembered for popularizing the “____ Consider Harmful” meme among programmers and their ill-considered online diatribes. Because (as usual) Dijkstra was making an excellent point: the structure of code should reflect its behavior. Swift 2.0 introduced two new control statements that aimed to simplify and streamline the programs we write: guard and defer. While the former by its nature makes our code more linear, the latter does the opposite by delaying execution of its contents. How should we approach these new control statements? How can guard and defer help us clarify the correspondence between the program and the process? Let’s defer defer and first take on guard. guardguard guard is a conditional statement requires an expression to evaluate to true for execution to continue. If the expression is false, the mandatory else clause is executed instead. func say Hello(numberHello(number OfOf Times: Int) { guard numberTimes: Int) { guard number OfOf Times > 0 else { return } for _ in 1...numberTimes > 0 else { return } for _ in 1...number OfOf Times { print("Hello!") } }Times { print("Hello!") } } The else clause in a guard statement must exit the current scope by using return to leave a function, continue or break to get out of a loop, or a function that returns Never like fatal. guard statements are most useful when combined with optional bindings. Any new optional bindings created in a guard statement’s condition are available for the rest of the function or block. Compare how optional binding works with a guard-let statement to an if-let statement: var name: String? if let name = name { // name is nonoptional inside (name is String) } // name is optional outside (name is String?) guard let name = name else { return } // name is nonoptional from now on (name is String) If the multiple optional bindings syntax introduced in Swift 1.2 heralded a renovation of the pyramid of doom, guard statements tear it down altogether. for image Name in imageName in image NamesNames List { guard let image = UIImage(named: imageList { guard let image = UIImage(named: image Name) else { continue } // do something with image }Name) else { continue } // do something with image } Guarding Against Excessive Indentation and ErrorsGuarding Against Excessive Indentation and Errors Let’s take a before-and-after look at how guard can improve our code and help prevent errors. As an example, we’ll implement a read function: enum Story Error: Error { case missing case illegible case tooError: Error { case missing case illegible case too Scary } func readScary } func read BedtimeBedtime Story() throws { if let url = Bundle.main.url(forStory() throws { if let url = Bundle.main.url(for Resource: "book", withResource: "book", with Extension: "txt") { if let data = try? Data(contentsExtension: "txt") { if let data = try? Data(contents Of: url), let story = String(data: data, encoding: .utf8) { if story.contains("👹") { throw StoryOf: url), let story = String(data: data, encoding: .utf8) { if story.contains("👹") { throw Story Error.tooError.too Scary } else { print("Once upon a time... \(story)") } } else { throw StoryScary } else { print("Once upon a time... \(story)") } } else { throw Story Error.illegible } } else { throw StoryError.illegible } } else { throw Story Error.missing } }Error.missing } } To read a bedtime story, we need to be able to find the book, the storybook must be decipherable, and the story can’t be too scary (no monsters at the end of this book, please and thank you!). But note how far apart the throw statements are from the checks themselves. To find out what happens when you can’t find book.txt, you need to read all the way to the bottom of the method. Like a good book, code should tell a story: with an easy-to-follow plot, and clear a beginning, middle, and end. (Just try not to write too much code in the “post-modern” genre). Strategic use of guard statements allow us to organize our code to read more linearly. func read BedtimeBedtime Story() throws { guard let url = Bundle.main.url(forStory() throws { guard let url = Bundle.main.url(for Resource: "book", withResource: "book", with Extension: "txt") else { throw StoryExtension: "txt") else { throw Story Error.missing } guard let data = try? Data(contentsError.missing } guard let data = try? Data(contents Of: url), let story = String(data: data, encoding: .utf8) else { throw StoryOf: url), let story = String(data: data, encoding: .utf8) else { throw Story Error.illegible } if story.contains("👹") { throw StoryError.illegible } if story.contains("👹") { throw Story Error.tooError.too Scary } print("Once upon a time... \(story)") }Scary } print("Once upon a time... \(story)") } Much better! Each error case is handled as soon as it’s checked, so we can follow the flow of execution straight down the left-hand side. Don’t Not Guard Against Double NegativesDon’t Not Guard Against Double Negatives One habit to guard against as you embrace this new control flow mechanism is overuse — particularly when the evaluated condition is already negated. For example, if you want to return early if a string is empty, don’t write: // Huh? guard !string.is Empty else { return }Empty else { return } Keep it simple. Go with the (control) flow. Avoid the double negative. // Aha! if string.is Empty { return }Empty { return } deferdefer Between guard and the new throw statement for error handling, Swift encourages a style of early return (an NSHipster favorite) rather than nested if statements. Returning early poses a distinct challenge, however, when resources that have been initialized (and may still be in use) must be cleaned up before returning. The defer keyword provides a safe and easy way to handle this challenge by declaring a block that will be executed only when execution leaves the current scope. Consider the following function that wraps a system call to gethostname(2) to return the current hostname of the system: import Darwin func current HostHost Name() -> String { let capacity = Int(NI_MAXHOST) let buffer = UnsafeName() -> String { let capacity = Int(NI_MAXHOST) let buffer = Unsafe MutableMutable Pointer<Int8>.allocate(capacity: capacity) guard gethostname(buffer, capacity) == 0 else { buffer.deallocate() return "localhost" } let hostname = String(cPointer<Int8>.allocate(capacity: capacity) guard gethostname(buffer, capacity) == 0 else { buffer.deallocate() return "localhost" } let hostname = String(c String: buffer) buffer.deallocate() return hostname }String: buffer) buffer.deallocate() return hostname } Here, we allocate an Unsafe early on but we need to remember to deallocate it both in the failure condition and once we’re finished with the buffer. Error prone? Yes. Frustratingly repetitive? Check. By using a defer statement, we can remove the potential for programmer error and simplify our code: func current HostHost Name() -> String { let capacity = Int(NI_MAXHOST) let buffer = UnsafeName() -> String { let capacity = Int(NI_MAXHOST) let buffer = Unsafe MutableMutable Pointer<Int8>.allocate(capacity: capacity) defer { buffer.deallocate() } guard gethostname(buffer, capacity) == 0 else { return "localhost" } return String(cPointer<Int8>.allocate(capacity: capacity) defer { buffer.deallocate() } guard gethostname(buffer, capacity) == 0 else { return "localhost" } return String(c String: buffer) }String: buffer) } Even though defer comes immediately after the call to allocate(capacity), its execution is delayed until the end of the current scope. Thanks to defer, buffer will be properly deallocated regardless of where the function returns. Consider using defer whenever an API requires calls to be balanced, such as allocate(capacity:) / deallocate(), wait() / signal(), or open() / This way, you not only eliminate a potential source of programmer error, but make Dijkstra proud. “Goed gedaan!” he’d say, in his native Dutch. Deferring FrequentlyDeferring Frequently If you use multiple defer statements in the same scope, they’re executed in reverse order of appearance — like a stack. This reverse order is a vital detail, ensuring everything that was in scope when a deferred block was created will still be in scope when the block is executed. For example, running the following code prints the output below: func procrastinate() { defer { print("wash the dishes") } defer { print("take out the recycling") } defer { print("clean the refrigerator") } print("play videogames") } play videogames clean the refrigerator take out the recycling wash the dishes What happens if you nest deferstatements, like this? defer { defer { print("clean the gutter") } } Your first thought might be that it pushes the statement to the very bottom of the stack. But that’s not what happens. Think it through, and then test your hypothesis in a Playground. Deferring JudgementDeferring Judgement If a variable is referenced in the body of a defer statement, its final value is evaluated. That is to say: defer blocks don’t capture the current value of a variable. If you run this next code sample, you’ll get the output that follows: func flip Flop() { var position = "It's pronounced /ɡɪf/" defer { print(position) } position = "It's pronounced /dʒɪf/" defer { print(position) } }Flop() { var position = "It's pronounced /ɡɪf/" defer { print(position) } position = "It's pronounced /dʒɪf/" defer { print(position) } } It's pronounced /dʒɪf/ It's pronounced /dʒɪf/ Deferring DemurelyDeferring Demurely Another thing to keep in mind is that defer blocks can’t break out of their scope. So if you try to call a method that can throw, the error can’t be passed to the surrounding context. func burn AfterAfter Reading(file url: URL) throws { defer { try FileReading(file url: URL) throws { defer { try File Manager.default.removeManager.default.remove Item(at: url) } // 🛑 Errors not handled let string = try String(contentsItem(at: url) } // 🛑 Errors not handled let string = try String(contents Of: url) }Of: url) } Instead, you can either ignore the error by using try? or simply move the statement out of the defer block and at the end of the function to execute conventionally. (Any Other) Defer Considered Harmful(Any Other) Defer Considered Harmful As handy as the defer statement is, be aware of how its capabilities can lead to confusing, untraceable code. It may be tempting to use defer in cases where a function needs to return a value that should also be modified, as in this typical implementation of the postfix ++ operator: postfix func ++(inout x: Int) -> Int { let current = x x += 1 return current } In this case, defer offers a clever alternative. Why create a temporary variable when we can just defer the increment? postfix func ++(inout x: Int) -> Int { defer { x += 1 } return x } Clever indeed, yet this inversion of the function’s flow harms readability. Using defer to explicitly alter a program’s flow, rather than to clean up allocated resources, will lead to a twisted and tangled execution process. “As wise programmers aware of our limitations,” we must weigh the benefits of each language feature against its costs. A new statement like guard leads to a more linear, more readable program; apply it as widely as possible. Likewise, defer solves a significant challenge but forces us to keep track of its declaration as it scrolls out of sight; reserve it for its minimum intended purpose to prevent confusion and obscurity.
https://nshipster.com/guard-and-defer/?utm_campaign=Swift%20Weekly&utm_medium=email&utm_source=Revue%20newsletter
CC-MAIN-2019-04
refinedweb
1,842
54.52
Changelog for package rocon_app_manager 0.6.1 (2013-09-11) report details of currently running app. disable uuid arg shunting was not enabled for concert clients. 0.6.0 (2013-08-30) disable uuids by default, also fire up the paired invitations by default for convenience. use a proper regular expression for the target. zeroconf name should match app manager name. bugfix remaps which shouldn't remap. pass on screen parameter settings from rocon_launch. missed an update for the new resource finding rapp lists. protect services from initialising in parallel. diagnostic flips for pairing mode. 0.5.4 (2013-08-07) public is now 11311 now private master is 11312 apply rosparm to set zeroconf parameter add gateway and hub as dependeny 0.5.3 (2013-07-22) install concert directory adding install rule installing pairing_master 0.5.2 (2013-07-17) force faster initialisation of the gateway advertisements in standalone and public pairing. push application namespace underneath the node name in standalone mode to match remote control mode styles - for android apps. app manager icon parameters as resource names. use resource names for rapp lists instead of full paths. flag for disabling the cleanup watchdog and consolidating services locally. pairing mode cleanup when android device is gone. manual pairing invitations now working. convenience pause to ensure small apps flip promptly. no longer need app manager robot_xxx parameters. bugfix missing shutdown of start and stop app services when remote control changes. pairing clients infra. bugfix the list apps service to respond with correct running apps signature. make the default application namespace with a gateway underneath the gateway name, not root. publish an icon with the platform information. fix publishing of listed/running apps. renamed paired launchers to be less confusing. remove trivial debug print about to move on start app latched list apps publisher 0.5.1 (2013-06-10) 0.5.0 0.5.0 (2013-05-27) Point to correct license file Removed (now) incorrect comments fix bad reference to non-exsistant parameter file. fix bad reference to non-exsistant parameter file. fix remappings to match roslaunch style Merge pull request #41 <> from robotics-in-concert/fix_app_list_file_not_found Fix app list file not found warnings and errors if app list file not found, fixes #40 <> . app list to rapp list app_lists args to rapp_lists trivial cleanup of a comment. auto invite false in paired master. trivial comment. eliminating duplicated code between paired and concert client launchers. minor reorginisation of app manager launchers (more modular). android can now finnd us via robot type and name parameters. close down quietly if gateway shut down before the app manager. flip with default application namespace remove old services before updating with new. don't do the hard work of advertisements. pairing updates. a few bugfixes starting the pairing starting to add components for pairing. return values from error status was wrong better errors messages for stop app. fix stop app for naturally terminating apps. create a useful pointer to the running rapp in the manager while it runs. better errors messages for stop app. fix stop app for naturally terminating apps. create a useful pointer to the running rapp in the manager while it runs. apps starts with human readable namespace standalone app manager. 0.4.0 gateway info now a msg. minor pep8 stuff. robot namespace back robot namespacing fix now it supports action_client and action_server public interface remove screen flag in concert_client/gateway logs out app compatibility. 0.3.0 (2013-02-05 15:23) 0.2.0 (2013-02-05 13:18) adding rocon_apps dependency .app -> .rapp correcting wiki url no more concert client taking the concert client out of the loop concert status -> app manager status, part of first redesign. has its own status now, labelled statusd till concert client swaps its own out. remote_control -> invite, start on general app design concert_msgs dependency removed parameter cleanup common create_rule code moved to rocon_utilities much minor refactoring. collapse advertisements. 0.1.1 (2013-01-31) advertising list apps, also correcting advertising behaviour in the client. remove unused logger. stop flipping the platform info. advertising the platform info service. platform info to rocon_app_manager_msgs revert loginfo Rapp->App Manager launch apps under a unique namespace so caller_id's are guaranteed to be unique. refactoring app->rapp.
http://docs.ros.org/hydro/changelogs/rocon_app_manager/changelog.html
CC-MAIN-2019-35
refinedweb
713
52.46
Download presentation Presentation is loading. Please wait. Published byJosephine Stewart Modified over 5 years ago 1 Week 9 PHP Cookies and Session Introduction to JavaScript 2 PHP COOKIES What is a cookie: it is a file that a web server saves on a computer hard disk when a user visits a website that uses cookies. It is used to identify a user. example of its use is for remembering login details, items in shopping chart and so on. When there are different elements embedded on the web page from different domains, each domain can issue its own cookie. This is then referred to as third party cookie. The setcookie() function is used to create a cookie. It must come before the html tag. 3 Syntax The syntax of the set cookie function is thus setcookie (name, value, expire, path, domain, secure, httponly). The name and value parameter are required. All other parameters are optional. Name : the server uses the name parameter to access the cookie. Value: the value of the cookie. Expire: sets the expiry date of the cookie. If not set, the cookie expires when the browser closes. It is written thus, time() + number of seconds. Path: this is indicated by a forward slash, or a subdirectory. If it is a forward slash, the cookie is available over the entire domain. It is a subdirectory, it is available only in that subdirectory Domain: the internet domain of the cookie. Secure: it has the default value of false. If the value is true, the cookie can be transferred only across a secured connection. Httponly: the default is false. If the value is true, the cookie must use only the http protocol. 4 Creating a cookie that expires in 30 days <?php $name = 'chcsl'; $value = 'school of programming'; setcookie ($name, $value, time()+2592000, "/"); ?> cookies <?php echo $_COOKIE["$name"]; ?> 5 Deleting a cookie This is done by issuing the cookie again but with a date in the past. All parameters in the function apart from the expire parameter should be same with the parameters when it was first issued. 6 SESSION it is used to store information that is used across multiple pages. one difference between session and cookie is that for a session, the information is not stored on the users’ computer. Session variables by default, stores user information to be used across multiple pages and last until the browser is closed. To start a session, the session_start() function is used. It must come before any html tag like this session_start();. 7 The session starts a user key on the computer and when a session is opened on another page, it scans the computer for a user key. If there is a match, it access that session and if not, it starts a new session. To remove all session, the session_unset() function is used and to destroy all session, the session_destroy() function is used. The session_unset() and session_destroy() function can be used in the body part of the html. only the session start should come before any html. 8 Introduction to JavaScript JavaScript is the default scripting language in html. To apply JavaScript to a web document, the Script tag is used. In html 5, the type attribute is not required. It is written thus.. It uses the extension.js It can be written in an external sheet and saved with the.js extension then referenced using the src attribute in the script tag thus: 9 JavaScript has no inbuilt print function, there are different ways of displaying JavaScript Using document. write() Using alert() Using innerHTML() Using console. log() 10 First JavaScript Program using document.write () Welcome document.write("Hello World") document. write is has same function as echo or print in php. 11 Using alert () JavaScript var name = prompt("Enter your name", ""); if (name ==“mildred") { alert("Hello Instructor!!"); } else { alert ("hello student"); } 12 Using innerHTML () JavaScript document.getElementById("fox").innerHTML ="the fox jumps over the lazy dog"; The statement tells the browser to write “the fox jumps over the lazy dog” inside an html element with an id of “fox”. 13 Literals and variables Literals are fixed values in JavaScript. A variable is defined using the var keyword. Variables are used to store data. A variable can be declared first then a value assigned to it or a value can be added directly to it when it is declared. var x ; x = 1; Is same as var x = 1; Variables should be declared at the beginning of the script. Numbers can be written with or without decimal points and text (strings) can be written with either single or double quotes. Identifiers are used to name variables and they are case sensitive. Identifier names cannot start with a number and a reserved word cannot be used as a name. 14 comments Comments in JavaScript like any other language, is used to leave notes or explain a code. It is ignored by the browser. A single line comment is written with two forward slash like this // And a multiline comment is written thus /* your text goes here More text */ 15 JavaScript operators Arithmetic Operators: + addition - subtraction * multiplication /division %modulo ++ increment -- decrement Assignment Operators: = assign value to variables += same as x = x+y -= same as x = x-y *= same as x= x*y /= same as x=x/y %= same as x =x%y. it returns the remainder of a division 16 Concatenation Operator: the plus sign + is used to join strings together. Using the plus sign on two numbers will produce the sum. Adding two strings together or adding a number and a string will produce a string. var name = “james”; var age = “15”; name + age = james15; 17 Comparison Operators == equal to === value and type are equal != not equal !== value or type are not equal > Greater than < less than >= greater than or equal to <= less than or equal to. 18 Operator precedence Order of precedence in JavaScript from highest to lowest () -> expression in parenthesis are executed first ++ -- increment and decrement operators are executed before multiplication, division, modulo, addition and subtraction. */% multiplication, division and modulo have equal precedence and are executed from left to right. They have higher precedence than addition and subtraction. + - addition and subtraction have the lowest precedence. 19 JavaScript DATA TYPES String: text quoted with either single or double quotes Number: can be written with or without decimal point Boolean : true or false Array: a variable with more than one value Object: are name value pairs. It is written thus var name ={firstName =“mary”, lastName = “jacob”, age = 20}; JavaScript has dynamic types, which means same variable can be used as different types. For example var x; x = 1; x = “fox”; 20 The typeof operator is used to return the type of a variable or expression. Setting a variable to undefined empties the variable. Data type of null is an object. 21 Functions in JavaScript Function is used to separate a section of code that perform a particular task. It is declared with the keyword function followed by a name for the function and a pair of parenthesis that can take arguments. Functions can also be stored in variables without a name and called with the variable name. JavaScript functions can be called before they are declared. Function definitions: do not specify data types for parameters, do not perform type checking on passed arguments and do not check the number of arguments received. 22 Example Functions Welcome function sum(a, b){ var sum = a + b; return sum; } var x = 5; var y = 8; var answer = sum(x, y); document.getElementById(“add").innerHTML = "the sum of x and y is" +answer 23 Converting Celsius to Fahrenheit using Javascript Functions function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.write("100 F to oC is: "+ toCelsius(80)); 24 Anonymous function Hello World var product = function (x, y){ return x*y ; } document.write(product (2,3)); 25 Changing a text when a button is clicked javascript the story of the fox the dog's reaction Read function changetext(){ document.getElementById("fox").innerHTML = "the fox jumps over the lazy dog"; document.getElementById("dog").innerHTML = "the dog is still sleeping"; } Similar presentations © 2021 SlidePlayer.com Inc.
https://slideplayer.com/slide/7397512/
CC-MAIN-2021-25
refinedweb
1,359
64.91
Introduction. It is highly scalable and there are many sites on the Web that have been built using Ruby on Rails. Besides the use of Ruby with Rails as a Web application development platform, there is another less-heralded side to Ruby, which is Ruby as a powerful scripting language, much in the same league as Python or Perl. It has immense capabilities, owing to the availability of many built-in and external libraries, the power of which can be harnessed to solve a great deal of the scripting needs that might crop up in any work environment. Systems administration is one such work environment that demands a lot of scripting for making things simpler and more efficient. User management, Process management, File Management, Software package management, and other basic automation requirements are better handled with scripting than with monotonous manual effort. Ruby comes in very handy in this scenario. It has a good set of libraries for achieving this. In this article, I will start with examples showing how Ruby can be put to use for simplifying some of the basic scripting needs of systems administration. These examples introduce the capabilities of Ruby as a powerful alternative to shell scripting. The examples definitely provide room for a lot of improvement and can be further enhanced or customized as seen fit. After the basic examples, I will introduce a very powerful system administration library for Ruby called Cfruby. This library incorporates a wide set of functionality to make systems administration and management easier. For this article, I assume that the reader has a working knowledge of Ruby. The basic examples that I present here use pure Ruby and hence should work on any UNIX®-like system supported by Ruby, as well as on Windows®. For the more advanced Cfruby examples, you will need access to a UNIX system. All the examples below have been tried with Ruby v1.8.4 on a Linux® box. They should work with the latest version of Ruby, as well. Ruby in action The first example here searches for files that match the given pattern in the path specified and gives the detailed information of these files in a user-friendly manner. This doesn't depend on any command-line utility, but just uses Ruby's built-in APIs for achieving the objective. Hence, it will work on any platform where Ruby runs. Also, it shows how powerful Ruby can be to greatly simplify such scripting requirements. Here, it does not just emulate the *nix "find" command, but builds upon it, thus showing the customizing power when using Ruby. Listing 1. Search for files matching a given pattern in the given path and display their detailed information require 'find' puts "" puts "-----------------------File Search-----------------------------------" puts "" print "Enter the search path : " searchpath = gets searchpath = searchpath.chomp puts "" print "Enter the search pattern : " pattern = gets pattern = pattern.chomp puts"----------------------------------------------------------------------" puts "Searching in " + searchpath + " for files matching pattern " + pattern puts"----------------------------------------------------------------------" puts "" Find.find(searchpath) do |path| if FileTest.directory?(path) if File.basename(path)[0] == ?. Find.prune # Don't look any further into this directory. else next end else if File.fnmatch(pattern,File.basename(path)) puts "Filename : " + File.basename(path) s = sprintf("%o",File.stat(path).mode) print "Permissions : " puts s print "Owning uid : " puts File.stat(path).uid print "Owning gid : " puts File.stat(path).uid print "Size (bytes) : " puts File.stat(path).size puts "---------------------------------------------------" end end end In this example: - Lines 5-11 - Queries the user for the search path and search pattern. - Line 16 - Uses the Ruby 'find' method from the 'Find' class to traverse through the searchpath specified. - Line 17 - Checks if the file found is a directory. If it is and it is not '.', it traverses recursively into the directory. - Line 24 - Uses the 'fnmatch' method of 'File' class to check if the file found matches the pattern given. - Line 25-34 - Prints the details of the file, if the file matches the pattern. Here is a sample output of this script. Listing 2. Sample output of the first example [root@logan]# ruby findexample.rb -----------------------File Search----------------------------------- Enter the search path : /test Enter the search pattern : *.rb ---------------------------------------------------------------------- Searching in /test for files matching pattern *.rb ---------------------------------------------------------------------- Filename : s.rb Permissions : 100644 Owning uid : 1 Owning gid : 1 Size (bytes) : 57 --------------------------------------------------- Filename : test.rb Permissions : 100644 Owning uid : 0 Owning gid : 0 Size (bytes) : 996 --------------------------------------------------- Filename : s1.rb Permissions : 100644 Owning uid : 1 Owning gid : 1 Size (bytes) : 39 --------------------------------------------------- One of the most common requirement during systems administration is to efficiently work with zip files for managing backups or to move a set of files from one machine to the other. Ruby comes in handy here. The second example, here, builds upon the first example, by incorporating a scenario wherein you would want to zip up the list of files you got as a result of the search. The built-in zlib module helps in handling gzip files and is good enough for most cases. But, here I will use another good Ruby library called "rubyzip" to create and work with zip archive files. Please see the Resources section for a link to download the same. Also, note here that this example uses pure Ruby and doesn't depend on any command-line utility being present on the machine. Installing rubyzip - Download the 'rubyzip' gem from the link provided and copy it into your system. (It was 'rubyzip-0.9.1.gem' when this article was written.) - Run gem install rubyzip-0.9.1.gem Listing 3. Working with zip files require 'rubygems' require_gem 'rubyzip' require 'find' require 'zip/zip' puts "" puts "------------------File Search and Zip-----------------------------" puts "" print "Enter the search path : " searchpath = gets searchpath = searchpath.chomp puts "" print "Enter the search pattern : " pattern = gets pattern = pattern.chomp puts"----------------------------------------------------------------------" puts "Searching in " + searchpath + " for files matching pattern " + pattern puts"----------------------------------------------------------------------" puts "" puts"----------------------------------------------------------------------" puts "Zipping up the found files..." puts"----------------------------------------------------------------------" Zip::ZipFile.open("test.zip", Zip::ZipFile::CREATE) { |zipfile| Find.find(searchpath) do |path| if FileTest.directory?(path) if File.basename(path)[0] == ?. Find.prune # Don't look any further into this directory. else next end else if File.fnmatch(pattern,File.basename(path)) p File.basename(path) zipfile.add(File.basename(path),path) end end end } This script creates a zip named 'test.zip' of the files found as a result of the search based on the provided search path and search pattern. This example does this: - Lines 9-15 - Queries the user for the search path and search pattern. - Line 23 - Creates a new ZipFile, named 'test.zip.' - Line 25 - Uses the Ruby 'find' method from the 'Find' class to traverse through the searchpath specified. - Line 26 - Checks if the file found is a directory. If it is and it is not '.', it traverses recursively into the directory. - Line 33 - Uses the 'fnmatch' method of 'File' class to check if the file found matches the pattern given. - Line 35 - Adds the matched file into the zip archive. Here is a sample output: Listing 4. Sample output of the second example [root@logan]# ruby zipexample.rb -----------------------File Search----------------------------------- Enter the search path : /test Enter the search pattern : *.rb ---------------------------------------------------------------------- Searching in /test for files matching pattern *.rb ---------------------------------------------------------------------- ---------------------------------------------------------------------- Zipping up the found files... ---------------------------------------------------------------------- "s.rb" "test.rb" "s1.rb" [root@logan]# unzip -l test.zip Archive: test.zip Length Date Time Name -------- ---- ---- ---- 996 09-25-08 21:01 test.rb 57 09-25-08 21:01 s.rb 39 09-25-08 21:01 s1.rb -------- ------- 1092 3 files Cfruby - Advanced system administration As the Cfruby site defines, "Cfruby allows managed system administration using Ruby. It is both a library of Ruby functions for system administration and an Cfengine-like clone (in effect a domain specific language or DSL for system administration)." Cfruby is basically a package made up of two parts: - Cfrubylib – A pure Ruby library with classes and methods for system administration. This includes file copying, finding, checksumming, package management, user management, and more. - Cfenjin – A simple scripting language helpful in scripting system administration tasks (without knowing Ruby). Cfruby can be downloaded as a Ruby gem or as a tar zipped file. The gem way is the simplest and the easiest. Get the gem and install it using the "gem install" comand. Installing Cfruby: - Copy the downloaded Cfruby gem file into your system. (Was 'cfruby-1.01.gem' as of the writing this article.) - Run gem install cfruby-1.01.gem. Cfruby should now be installed on your system. Putting Cfruby to use Now I will show Cfruby's capabalities and how it can greatly ease system administration and management. There are two basic ways to access the functionality provided by the Cfruby library: - Using the Ruby classes from libcfgruby directly. - Using the cfrubyscript wrapper, which provides a neater interface to libcfruby. Using Ruby classes from libcfruby directly Libcfruby is the core of Cfruby, a collection of modules providing a variety of functionality for making system maintenance and setup easier. To use libcfruby you need to add 'require_gem 'cfruby'' to the top of the script, after installing the Cfruby gem. This will give direct access to all of the core modules in libcfruby that can be used in the script in any way needed.The only disadvantage with this method is that it libcfruby is big and has all the classes and methods stacked into their own namespaces. So, to access any of the classes, you would need to qualify it with the namespace. For example, libcfruby provides a method to get the type of your system. To get that, you need to do something like this: Listing 5. Getting the type of OS using libcfruby require 'rubygems' require_gem 'cfruby' os = Cfruby::OS::OSFactory.new.get_os() puts(os.name) This is just to get the name of your operating system. So, as you do more with libcfruby, your script will become a lot more cluttered with all the namsepace specifications. This is where the next method of using Cfruby comes in handy. Using the cfrubyscript wrapper, which provides a neater interface to libcfruby To use the cfrubyscript wrapper, you need to add: Listing 6. Using cfrubyscript require 'rubygems' require_gem 'cfruby' require 'libcfruby/cfrubyscript' Doing this includes cfrubyscript into your script, which gives a nice and simpler interface to access the functionality of libcfruby. What cfrubyscript achieves is: - It exports a set of variables to the global namespace like $os, $pkg, $user, $proc, and $sched . - It pulls most of the major modules into the main namespace, so you can call FileEdit.set instead of Cfruby::FileEdit.set. - It adds a number of helper methods to String and Array that do Cfruby things (install programs, edit files, and more). - It also gives you a nice logger. So, no more namespace specification clutter in your scripts. The same example above of getting the type of OS of your system now becomes: Listing 7. Getting the type of OS using cfrubyscript require 'rubygems' require_gem 'cfruby' require 'libcfruby/cfrubyscript' puts($os.name) It just translates into one single call, using the global variable $os. Cfruby is really powerful and provides a wide variety of functionality to manage *nix-like systems. Now look at a few of them and some basic examples of using them. User management One of the most common and most important tasks in any systems administration is the management of users and groups. Cfruby provides a powerful set of methods to achieve it in a portable and simple manner. This is achieved by using the UserManager object that can be obtained from the OS module, like below. Listing 8. Getting the UserManager object using libcfruby require 'rubygems' require_gem 'cfruby' osfactory = Cfruby::OS::OSFactory.new() os = osfactory.get_os() usermgr = os.get_user_manager() If you go the cfrubyscript way, there will already be a global user manager object available as $user, which can be directly used to invoke the methods. I will follow this method as it is much simpler and easier to read. Here is how to use it to create and delete a user. Listing 9. User management using cfgrubyscript require 'rubygems' require_gem 'cfruby' require 'libcfruby/cfrubyscript' $user.adduser('newusername','password') $user.deleteuser('usernametodelete',true) What does it do? - Lines 1, 2 – As usual, here is included libcfruby and cfrubyscript into the script. - Line 3 – This creates a new user with the username as 'newusername' and with the password specified as the second argument. - Line 4 – This deletes the user with username as 'usernametodelete.' The second argument is either true or false, to specify whether to delete the home directory of the user being deleted. Similarly, group operations are possible by using the addgroup() and deletegroup() methods in the UserManager object. Process management The other important task of an administrator is to keep a track of the processes running on the system and manage them. Cfruby comes in handy here as well, providing the means to handle processes efficiently. You can do this with Cfruby. Listing 10. Process management using cfgrubyscript require 'rubygems' require_gem 'cfruby' require 'libcfruby/cfrubyscript' $proc.kill($proc.vim) 'ps –aef'.exec() What does it do? - Line 3 – Uses the global ProcessManager object $proc to kill the 'vim' process specified as the argument. $proc.vim is a ProcessInfo-type object of the 'vim' process running on the system. These are automatically created by the cfrubyscript. - Line 4 – Starts a new process with the specified command 'ps –aef.' You can directly invoke the exec method from your command string. Package management Managing the software on the system is another task that a systems administrator has to take care of. Cfruby provides methods to easily install and remove software from the system. Listing 11. Package management using cfgrubyscript require 'rubygems' require_gem 'cfruby' require 'libcfruby/cfrubyscript' all = $pkg.packages() installed = $pkg.installed_packages() ruby.install() What does it do? - Line 3 – Uses the global $pkg PackageManager object created by cfrubyscript and gets all the packages available on the system by calling the packages() method. - Line 4 – This gets the list of all installed packages. - Line 5 – This installs the Ruby package by invoking the install method. You are able to directly invoke the install helper method from the package name itself. This is the level to which things are simplified. File management Cfruby also helps in managing the files on the system. Creating, editing, deleting, changing ownership, and changing permissions and more are easily achieved with the methods provided by Cfruby Listing 12. File management using cfgrubyscript require 'rubygems' require_gem 'cfruby' require 'libcfruby/cfrubyscript' '/etc/ssh'.chown_mod('root', 'wheel', 'u=rw,g=r,o-rwx', `:recursive` => true) What does it do? - Line 3 – Changes the owner and group and the permissions of the file '/etc/ssh.' Directly invokes the chown_mod() method from the file itself. This is again made possible by cfrubyscript's helper objects and methods. Note how it takes just one line to achieve this. So, the above examples should have given you an idea as to how powerful Cfruby is and how easy it is to use it to administer and manage systems in an easy and efficient manner. Also, it makes the whole task of systems administration more easy and more fun with the higly intuitive set of classes and methods that it provides. There is lot more to know about Cfruby and its complete set of functionality. It has a good set of documentation to go with it. I suggest that you take a look at the documents to unleash the full power of this Ruby library. Please look at the resources section for the links. Summary Ruby is not just for Web application development working with the Rails framework. It can also be used as a powerful as a scripting language and a very good alternative to the usual shell scripting, commonly used to achieve the scripting needs in systems adminstration. With its set of built-in modules and a few external libraries, Ruby can make systems adminstration more efficient and definitely much more fun. Ruby is a very useful and powerful tool that is a must-have tool in every system administrator's toolbox. Resources Learn - Ruby programming language: The Ruby site. - Programming Ruby: The Pragmatic Programmer's Guide. A good guide to learn programming in Ruby. - AIX and UNIX : Want more? The developerWorks AIX and UNIX zone hosts hundreds of informative articles and introductory, intermediate, and advanced tutorials. - developerWorks technical events and webcasts: Stay current with developerWorks technical events and webcasts. Get products and technologies - Ruby: Download the latest version of Ruby - Cfruby: Download the system administration library for Ruby. - RubyZip: Download the zip files handling library for Ruby..
http://www.ibm.com/developerworks/aix/library/au-rubysysadmin/
CC-MAIN-2014-41
refinedweb
2,767
66.23
I'm trying to use ActiveModel instead of ActiveRecord for my models because I do not want my models to have anything to do with the database. Below is my model: class User include ActiveModel::Validations validates :name, :presence => true validates :email, :presence => true validates :password, :presence => true, :confirmation => true attr_accessor :name, :email, :password, :salt def initialize(attributes = {}) @name = attributes[:name] @password = attributes[:password] @password_confirmation = attributes[:password_confirmation] end end class UsersController < ApplicationController def new @user = User.new @title = "Sign up" end end <h1>Sign up</h1> <%= form_for(@user) do |f| %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :email %><br /> <%= f.text_field :email %> </div> <div class="field"> <%= f.label :password %><br /> <%= f.password_field :password %> </div> <div class="field"> <%= f.label :password_confirmation, "Confirmation" %><br /> <%= f.password_field :password_confirmation %> </div> <div class="actions"> <%= f.submit "Sign up" %> </div> <% end %> undefined method 'to_key' for User:0x104ca1b60 I went rooting around the Rails 3.1 source to sort this out, I figured that would be easier than searching anywhere else. Earlier versions of Rails should be similar. Jump to the end if tl;dr. When you call form_for(@user), you end going through this: def form_for(record, options = {}, &proc) #... case record when String, Symbol object_name = record object = nil else object = record.is_a?(Array) ? record.last : record object_name = options[:as] || ActiveModel::Naming.param_key(object) apply_form_for_options!(record, options) end And since @user is neither a String nor Object, you go through the else branch and into apply_form_for_options!. Inside apply_form_for_options! we see this: as = options[:as] #... options[:html].reverse_merge!( :class => as ? "#{as}_#{action}" : dom_class(object, action), :id => as ? "#{as}_#{action}" : dom_id(object, action), :method => method ) Pay attention to that chunk of code, it contains both the source of your problem and the solution. The dom_id method calls record_key_for_dom_id which looks like this: def record_key_for_dom_id(record) record = record.to_model if record.respond_to?(:to_model) key = record.to_key key ? sanitize_dom_id(key.join('_')) : key end And there's your call to to_key. The to_key method is defined by ActiveRecord::AttributeMethods::PrimaryKey and since you're not using ActiveRecord, you don't have a to_key method. If you have something in your model that behaves like a primary key then you could define your own to_key and leave it at that. But, if we go back to apply_form_for_options! we'll see another solution: as = options[:as] So you could supply the :as option to form_for to generate a DOM ID for your form by hand: <%= form_for(@user, :as => 'user_form') do |f| %> You'd have to make sure that the :as value was unique within the page though. Executive Summary: to_keymethod that returns it. :asoption to form_for.
https://codedump.io/share/ABbvMMCbRh5k/1/activemodel---view---controller-in-rails-instead-of-activerecord
CC-MAIN-2018-26
refinedweb
444
50.94
April 24, 2020 Single Round Match 784 Editorials Scissors For each second, let’s observe how many scissors are free (opened): 0: 1 1: 2 2: 4 3: 8 4: 16 … At time t, 2^t of the scissors are free. We want to find the first time that we can have N + 1 scissors free. Use a for loop and find this moment. public int openingTime(int N) { long free = 1, locked = N; int timeElapsed = 0; while (locked > 0) { timeElapsed += 10; long willOpen = Math.min(free, locked); locked -= willOpen; free += willOpen; } return timeElapsed; } MaximumBalances The optimal way is to construct a string like this: ()()()()… This way, having o opening brackets and c closing brackets, the answer is min(o, c) * (min(o, c) + 1) / 2. The proof that this pattern is optimal can be made after observing that whenever we have nested parentheses, we can increase the beauty of the string by removing one level of nesting. E.g., if you have (S), changing it to ()S will increase the number of balanced substrings. public int solve(String s) { int open = 0, closed = 0; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '(') open++; else closed++; } int n = Math.min(open, closed); return (n*(n+1))/2; } ValueDivision Consider the following case: {7, 7, 7, 7} Returns: {4, 5, 6, 7 } The idea comes to mind. Each time you find the maximum number that has more than one occurrence, apply the operation on it. In fact, you do the operation several times such that the number of occurrences of maximum becomes one. It is obvious that it’s impossible to remove the maximum completely. So, what is the best option? Keep the last one and decrease the remaining ones. def getArray(self, A): A = list(A) last_max = 10**9 + 47 while True: curr_max, curr_last = 1, None for i in range(len(A)): if A[i] < last_max and A[i] >= curr_max: curr_max = A[i] curr_last = i if curr_max == 1: break for i in range(curr_last): if A[i] == curr_max: A[i] -= 1 last_max = curr_max return A SpeedingUpBozosort [misof:] The nicest part of this problem is the central idea it illustrates. Did you intuitively expect that making multiple random swaps will actually speed up the algorithm? If not, why? And if you did, what exactly do you now expect about a more general question: how many swaps are optimal? Is there a threshold beyond which you are doing too many? And does the answer change if we count comparisons and swaps together, instead of just comparisons? What is the optimal number of swaps per round in that setting? (The total number of comparisons and swaps is obviously proportional to the actual running time.) The number of states is at most 6! = 720. The first thing we need to calculate is the transition matrix. This is to calculate trans[p][q] = probability to get q from p after numSwaps swaps. For each p, let’s calculate the trans[identity permutation][p] where identity permutation is 1, 2, 3, …, N. Calculating other values is easy then. Let t[p][k] = probability of reaching p from identity permutation after exactly k moves. t[identity permutation][0] = 1. It’s easy to calculate the values in O(numSwaps * N! * N ^ 2). Even it can be solved using matrix multiplication in O(log(numSwaps) * N! * N ^ 2). It is not needed by the way. Now the problem is classical. We have a graph, we start from a vertex. We random walk to other vertices to reach a vertex). It can be solved using a system of equations. Let dp[p] be the answer if we start from vertex p (that stands for a permutation). Let checkNeed(p) be the number of checks need to be done on p to detect if it’s sorted or not. For the destination (where permutation is sorted) dp[dest] is equal to checkNeed(dest). Consider a not sorted permutation p, It leads to a normal system of linear equations. Read about how to solve them using the Gauss method here. int[] factorial = {1, 1, 2, 6, 24, 120, 720, 5040}; int[] nton = {1, 1, 4, 27, 256, 3125, 46656, 823543}; int[] simplify; int[][] generatePermutations(int N) { if (N == 0) return new int[][] { {} }; int[][] answer = new int[factorial[N]][N]; int x = 0; for (int[] prev : generatePermutations(N-1)) { for (int i=N-1; i>=0; --i) { int y = 0; for (int j=0; j<i; ++j) answer[x][y++] = prev[j]; answer[x][y++] = N-1; for (int j=i; j<N-1; ++j) answer[x][y++] = prev[j]; ++x; } } return answer; } int fastCode(int[] perm) { int N = perm.length; int code = 0; for (int x : perm) code = N*code + x; return code; } int encode(int[] perm) { return simplify[fastCode(perm)]; } public double expectedComparisons(int[] A, int numSwaps) { // generate all permutations and implement a handy way of encoding+decoding them int N = A.length; int[][] permutations = generatePermutations(N); simplify = new int[nton[N]]; for (int n=0; n<factorial[N]; ++n) simplify[fastCode(permutations[n])] = n; // check which among them sort A, and precalculate the number of comparisons // made when each of them is checked during bozosort boolean[] isSorted = new boolean[factorial[N]]; int[] comparisonsWhenChecked = new int[factorial[N]]; for (int n=0; n<factorial[N]; ++n) { isSorted[n] = true; for (int i=0; i+1<N; ++i) { ++comparisonsWhenChecked[n]; if (A[ permutations[n][i] ] > A[ permutations[n][i+1] ]) { isSorted[n] = false; break; } } } // for the identity permutation use DP to precalc the probability of getting // each permutation after swaps double[] oldProbs = new double[factorial[N]]; oldProbs[0] = 1.; int[] tperm = new int[N]; for (int sw=0; sw<numSwaps; ++sw) { double[] newProbs = new double[factorial[N]]; for (int n=0; n<factorial[N]; ++n) if (oldProbs[n] != 0) { for (int x=0; x<N; ++x) for (int y=0; y<N; ++y) { for (int i=0; i<N; ++i) tperm[i] = permutations[n][i]; int tmp = tperm[x]; tperm[x] = tperm[y]; tperm[y] = tmp; newProbs[ encode(tperm) ] += oldProbs[n] / N / N; } } oldProbs = newProbs; } // precompute the whole matrix of transition probabilities double[][] trans = new double[factorial[N]][factorial[N]]; for (int n=0; n<factorial[N]; ++n) { int[] cperm = new int[N]; for (int p=0; p<factorial[N]; ++p) { // with probability oldProbs[p], swaps turn the identity into permutation p // we need to calculate the same effect on our permutation for (int i=0; i<N; ++i) { cperm[i] = permutations[n][ permutations[p][i] ]; } trans[n][encode(cperm)] += oldProbs[p]; } } // build a system of linear equations int M = factorial[N]; double[][] E = new double[M][M+1]; for (int n=0; n<M; ++n) { E[n][n] = 1; E[n][M] = comparisonsWhenChecked[n]; if (isSorted[n]) continue; for (int p=0; p<M; ++p) E[n][p] -= trans[n][p]; } // solve the system of linear equations for (int c=0; c<M; ++c) { int rmax=c; for (int r=c; r<M; ++r) if (Math.abs(E[r]) > Math.abs(E[rmax])) rmax = r; for (int c2=c; c2<=M; ++c2) { double tmp=E[rmax][c2]; E[rmax][c2] = E[c2]; E[c2] = tmp; } for (int r=c+1; r<M; ++r) { double q = - E[r] / E; for (int c2=c; c2<=M; ++c2) E[r][c2] += q * E[c2]; } } double[] solutions = new double[factorial[N]]; for (int r=M-1; r>=0; --r) { double rhs = E[r][M]; for (int c=r+1; c<M; ++c) rhs -= E[r] * solutions; solutions[r] = rhs / E[r][r]; } return solutions[0]; } TAASquares (The solution to this problem, including the comment on points, was written by misof.) Below is construction for N = 10 that has all row and column sums distinct. For easier reading, it is split into halves. 00000|00000 00000|00002 00000|00022 00000|00222 00000|02222 —–+—– 00001|22222 00001|22222 00012|22222 00122|22222 01222|22222 12222|22222 The top half are the sums 0, 2, 4, 6, 8; the left half are 1, 3, 5, 7, 9; the right half are 10, 12, 14, 16, 18; and the bottom half are 11, 13, 15, 17, 19. This construction easily generalizes for any even N and it’s clearly optimal. For an odd N, we can take the above matrix for N+1 and, for example, drop the topmost row and the leftmost column. This only decreases the sum of the last row by 1, making one collision: the last row and the last column now have the same sum. What remains in this solution is to show that for odd N we cannot have all sums distinct. (An aside: Obviously, this part was not necessary during the contest. This, together with the observation that the medium problem’s implementation takes time and thus the scores on it will generally be lower, were the two main reasons for setting the point value for this problem only at 800 points. At the same time, this problem does subjectively require more creativity than this round’s medium, which is a part of why it’s worth more.) Suppose N is odd and all line sums are distinct. Imagine that we start in the position where each cell in the matrix is a 1 and thus each line has sum N. We are now going to change some 1s into 0s and 2s so that we shift the sums away from N. On one hand, we know that at the end only one sum can remain N. Only two can be N-1 and N+1, which requires at least one change in each of them. Then, only two can be N-2 and N+2, and so on. Thus, if we count the number of changes for each line separately, we must get the sum of at least 0 + 1 + 1 + 2 + 2 + … + (N-1) + (N-1) + N = N^2 changes. On the other hand, let’s proceed as follows. Imagine you already have an NxN matrix with all line sums distinct. For better imagination, sort both rows and columns according to their sum. (This is clearly independent: when you sort columns you don’t change row sums.) Pick the N lines with the highest sums and use a highlighter to highlight them. If this includes R rows and C = N-R columns, we now have a R*C block that has been highlighted twice. Note that each highlighted line has sum at least N, and each other line has sum at most N. Thus, if we start with all 1s and we want to produce this matrix, we want to shift the sums of highlighted lines up and the sums of other lines down. Changes with this effect are called good, changes with the opposite effect are called bad. From the above observation we can now easily derive that we need (total # of good changes) – (total # of bad changes) >= N^2, but is this possible? Each change in the once-highlighted region is neutral: it’s bad for its row and good for its column, or vice versa. Each change of a 1 to a 2 in the twice-highlighted region is twice good (both in its row and in its column), and each change of a 1 to a 0 in the not-highlighted region is also twice good. Their opposites are twice bad. Thus, the best we can get is (# of good changes) – (# of bad changes) = 2*(number of twice-highlighted cells) + 2*(number of not-highlighted cells) = 4*R*(N-R). If N is odd, regardless of what R we choose, 4*R*(N-R) < N^2 and thus we cannot make enough good changes to make all sums distinct, q.e.d. Additionally, note that this insight tells us that in any valid solution for an even N we must have R = N/2 and all the above good changes must be a part of the solution. This quite significantly limits the space of possible solution patterns. public String[] construct(int N) { if (N == 4) return new String[] { "2212", "2002", "0002", "2102" }; if (N == 5) return new String[] { "12222", "00012", "02221", "00110", "00122" }; if (N == 1) return new String[] { "1" }; String[] answer = new String[N]; for (int n=0; n<N; ++n) answer[n] = ""; for (int r=0; r<N; ++r) { for (int c=0; c<N; ++c) { if (c < N-1-r) { answer[r] += '0'; continue; } if (c > N-1-r) { answer[r] += '2'; continue; } if (r < N/2) answer[r] += '0'; else answer[r] += '1'; } } return answer; } a.poorakhavan Guest Blogger
https://www.topcoder.com/single-round-match-784-editorials/
CC-MAIN-2020-34
refinedweb
2,102
66.67
![if !IE]> <![endif]>. Thus, ServerSocket is for servers. The Socket class is for clients. It is designed to connect to server sockets and initiate protocol exchanges. Because client sockets are the most commonly used by Java applications, they are examined here. The creation of a Socket object implicitly establishes a connection between the client and server. There are no methods or constructors that explicitly expose the details of establishing that connection. Here are two constructors used to create client sockets: Socket defines several instance methods. For example, a Socket can be examined at any time for the address and port information associated with it, by use of the following methods: InetAddress getInetAddress( ) : Returns the InetAddress associated with the Socket object. It returns null if the socket is not connected. int getPort( ) : Returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected. int getLocalPort( ) : Returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound. You can gain access to the input and output streams associated with a Socket by use of the getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw an IOException if the socket has been invalidated by a loss of connection. These streams are used exactly like the I/O streams described in Chapter 20 to send and receive data. InputStream getInputStream( ) throws IOException : Returns the InputStream associated with the invoking socket. OutputStream getOutputStream( )throws IOException : Returns the OutputStream associated with the invoking socket. Several other methods are available, including connect( ), which allows you to specify a new connection; isConnected( ), which returns true if the socket is connected to a server; isBound( ), which returns true if the socket is bound to an address; and isClosed( ), which returns true if the socket is closed. To close a socket, call close( ). Closing a socket also closes the I/O streams associated with the socket. Beginning with JDK 7, Socket also implements AutoCloseable, which means that you can use a try-with-resources block to manage a socket. The following program provides a simple Socket example. It opens a connection to a "whois" port (port 43) on the InterNIC server, sends the command-line argument down the socket, and then prints the data that is returned. InterNIC will try to look up the argument as a registered Internet domain name, and then send back the IP address and contact information for that site. // Demonstrate Sockets. import java.net.*; import java.io.*; class Whois { public static void main(String args[]) throws Exception { int c; Create a socket connected to internic.net, port 43.); } s.close(); } } If, for example, you obtained information about MHProfessional.com, you’d get something similar to the following: Whois Server Version 2.0 Domain names in the .com and .net domains can now be registered with many different competing registrars. Go to for detailed information. Domain Name: MHPROFESSIONAL.COM Registrar: CSC CORPORATE DOMAINS, INC. Whois Server: whois.corporatedomains.com Referral URL: Name Server: NS1.MHEDU.COM Name Server: NS2.MHEDU.COM . . Here is how the program works. First, a Socket is constructed that specifies the host name "whois.internic.net" and the port number 43. Internic.net is the InterNIC web site that handles whois requests. Port 43 is the whois port. Next, both input and output streams are opened on the socket. Then, a string is constructed that contains the name of the web site you want to obtain information about. In this case, if no web site is specified on the command line, then "MHProfessional.com" is used. The string is converted into a byte array and then sent out of the socket. The response is read by inputting from the socket, and the results are displayed. Finally, the socket is closed, which also closes the I/O streams. In the preceding example, the socket was closed manually by calling close( ). If you are using JDK 7 or later, then you can use a try-with-resources block to automatically close the socket. For example, here is another way to write the main( ) method of the previous program: // Use try-with-resources to close a socket. public static void main(String args[]) throws Exception { int c; //Create a socket connected to internic.net, port 43. Manage this //socket with a try-with-resources block. try (); } } // The socket is now closed. } In this version, the socket is automatically closed when the try block ends. So the examples will work with earlier versions of Java and to clearly illustrate when a network resource can be closed, subsequent examples will continue to call close( ) explicitly. However, in your own code, you should consider using automatic resource management since it offers a more streamlined approach. One other point: In this version, exceptions are still thrown out of main( ), but they could be handled by adding catch clauses to the end of the try-with-resources block. Related Topics Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.
https://www.brainkart.com/article/TCP-IP-Client-Sockets---Java_10616/
CC-MAIN-2019-35
refinedweb
844
58.48
Thanks Villep, Its working! :) Type: Posts; User: engrnaveed; Keyword(s): Thanks Villep, Its working! :) Thanks again Villep, I followed the viki article & then added your code to the project. But this time it returns error on the line: root->setContextProperty("eventFilter", &eventFilter); it... 1. Thanks Villep, well I've no understanding of SQL at all but I'll manage it myself. 2. Unfortunately, these lines dont work. there is an error: "TypeError: Result of expression 'Qt.application'... Hi, I am new to game programming. I want to develop Games using Qt Quick. Can any one guide me where I find the tutorials or demos/examples for this. (except the Snake Game, SameGame & 5 in a Row)... Hi every body, I have developed a game for nokia s60v5 (Symbian ^1). Now I want to accomplish following tasks: 1. Save the state of the game as the user exits it & then resume the game from... Of course, I found it at: Hi everybody I installed the Box2d plugin for QML. I ran an example that came with the zip file. Every example ran in desktop but when I tried to run it my Nokia 5530 XpressMusic, it said: ... Hi.. I am facing problems with running this code: import QtQuick 1.0 import QtMultimediaKit 1.1 Text { text: "Click Me!"; font.pointSize: 24; I am using windows7. I build & run the code for desktop but get the error: module "QtMultimediaKit" is not installed import QtMultimediaKit 1.1 ^ adding the lines CONFIG += mobility... Hi everyone! I am facing a problem in playing any audio file in my qml application when I use QML Audio Element or QML Soundeffect Element. It says: module "QtMultimediaKit" is not installed ... Hi everyone! I am facing a problem in playing any audio file in my qml application when I use QML Audio Element or QML Soundeffect Element. It says: module "QtMultimediaKit" is not installed ... Thanks kusumk for helping me yet another time.. Now I need a little more help. Please guide me how to make use of the plugin. i.e. how to compile the code and install the libraries. I have the... Hi everybody.. Can some one please send me the link to download box2d qml plugin? I can't find it at :( please send me at malikontop@yahoo.com, if you can or... Thanks kusumk... It solved the problem.. Hi every one! Can any body please guide me how to distribute columns of QTableWidget evenly using code? I want the QTableWidget to be of maximum width of 360 pixels. but when the number of columns... Thanks kusumk!! It works.. I wanna use this in gui application. in which a user enters a list of doubles. I want to convert that text into an array of doubles for further processing. Hi everyone! Can any body tell me How to Convert a QStringList into an array of doubles??? e.g. I have a QStringList: 1 2 3 4 5 6 7 8 1 9 The Code that I've tried is as under: QString...
http://developer.nokia.com/community/discussion/search.php?s=d3378c79c32d265db8ae9a4e1102ec11&searchid=3280249
CC-MAIN-2014-35
refinedweb
505
77.43
This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project. J Grant <jg@jguk.org> writes: > Hello > > I believe the types.h are part of the compiler rather than lib's etc. That depends on the system. On a typical Linux system, types.h comes from glibc as shown in line 2 of the file: This file is part of the GNU C Library. > I quote from <sys/types.h> > ---------- > #ifdef __USE_MISC > /* Old compatibility names for C types. */ > typedef unsigned long int ulong; > typedef unsigned short int ushort; > typedef unsigned int uint; > #endif > ----------- > > I have an application that I am compiling and porting to a new target, i > noticed that > typedef unsigned char uchar; > > was not present, could anyone comment on this please? If you need this, define it yourself. The other names are just for convenience. > I see there is the "old compatibility' comment, is there a better > alternative to uchar, ulong, uint abbreviations available? Use the new ISO C99 <stdint.h> header, Andreas -- Andreas Jaeger SuSE Labs aj@suse.de private aj@arthur.inka.de
http://gcc.gnu.org/ml/gcc/2001-08/msg01285.html
CC-MAIN-2018-34
refinedweb
184
78.35
#include "lib/cc/compat_compiler.h" #include "lib/cc/torint.h" Go to the source code of this file. Add random noise between INT64_MIN and INT64_MAX coming from a Laplace distribution with mu = 0 and b = delta_f/epsilon to signal based on the provided random value in [0.0, 1.0[. The epsilon value must be between ]0.0, 1.0]. delta_f must be greater than 0. Definition at line 51 of file laplace.c. References sample_laplace_distribution(), and tor_assert(). Transform a random value p from the uniform distribution in [0.0, 1.0[ into a Laplace distributed value with location parameter mu and scale parameter b. Truncate the final result to be an integer in [INT64_MIN, INT64_MAX]. Definition at line 26 of file laplace.c. References clamp_double_to_int64(), tor_assert(), and tor_mathlog(). Referenced by add_laplace_noise().
https://people.torproject.org/~nickm/tor-auto/doxygen/laplace_8h.html
CC-MAIN-2019-39
refinedweb
132
53.88
? I should start by stating the IoC and DI are not unique to ASP.NET MVC. They have been around a long time. It's just that MVC supports these notions particularly well. IoC is a principle, or an architectural pattern. There are quite a few definitions of IoC, but the basis behind it is always the same - it helps towards a loosely coupled architecture. DI is one way in which IoC can be applied, according to one school of thought. DI is IoC according to another. So far, you may be none the wiser, so I will use a bit of code based on the Contact Manager ASP.NET MVC tutorial to help illustrate the basic problem that they or it are/is intended to solve: public class ContactController : Controller { private ContactManagerModelDataContext entities = new ContactManagerModelDataContext(); public ActionResult Index() { return View(entities.Contacts.ToList()); } } public class ContactController : Controller { private ContactManagerEntities entities = new ContactManagerEntities(); public ActionResult Index() { return View(entities.ContactSet.ToList()); } } Just to clear up any initial confusion, yes - the example above is more or less the same code twice. One uses LINQ to SQL (the first one) and the second uses the Entity Framework for data access. Both versions have a dependency on the data access service or layer, in that neither controller can do their thing without it. However, in both versions, the specifics of the dependency is hardcoded into the Controller. That's called "Tight Coupling". In the first version, a LINQ to SQL DataContext is instantiated and referenced, and a System.Data.Linq.Table<T> object is passed to the View. In the second, an Entity Framework ObjectContext is referenced, and a System.Data.Object.ObjectQuery<T> is passed to the View. There is no separation of concerns here in that the data access layer is embedded in the Controller. So what's the problem with that? Well, imagine that the two versions are an example of "before" and "after". In other words, you began by using LINQ to SQL, and then were required to change the data access to the Entity Framework (or ADO.NET, nHibernate, Typed DataSets or any number of other methods). OK, you think - it's just a couple of lines that were changed. Now imagine that these Controllers had 20 or 30 Actions, and that there are 20 or 30 Controllers. Now you begin to see the problem... "Oh, but that will never happen to me", you say. And I can to an extent sympathise with that: the only data access changes I have ever made to an application were through my own choice. Until a couple of weeks ago. We weren't expecting it at all. But it happened nevertheless and was forced on us. When you view Data Access as a "component" of your application, you should also start to see that there are other areas in an application which could be viewed as components. An emailing service, a logging service, caching, validation etc. All of these could be implemented as components. You may already be using ready-built components such as those found within the Enterprise Library. They could all potentially become dependencies of Controllers or even eachother. And all could be subject to change. You might decide to experiment with one, and then after some work, decide it doesn't suit you, so you need to exchange it for another. Now that happens to me quite often. Another problem with the tightly coupled examples is with Unit Testing. If you are taking the trouble to read this article and haven't got round to a structured testing regime for your applications yet, chances are that you will. At the moment, if you write a test for the Index Action of the ContactController, you will cause a call to the database. If you take a Test Driven Design approach, you probably won't even have a database at this point, let alone any useful data in it. And if you have created a database, you need to stuff it with dummy data so that it can return something tangible. And testing against databases (when you have hundreds of automated tests to run) is slow. So you create a Mock. A mock in this case is service that simulates or mimics the database. It will generate collections for you, but you need to replace the data access code in the Controller so that the Controller is dependent on the mock object instead of connecting to and querying the database. And you need to do that every time you run the tests, and then undo it again, which will be time-consuming and messy. Dependency Injection Inversion of Control really describes what happens when you move away from a procedural programming style, where each line of code is run in turn, to a more (for example) event-driven style, where code is fired as a result of external factors. In other words, in procedural programming, control of what happens and when is entirely in the hands of the programmer. In an event-driven application, the control over what happens and when is inverted or placed in the hands of the user. One of the benefits of moving away from a procedural approach to a more object-oriented style of applications development is that you need a lot less boilerplate or repetitive code. In a procedural application, if there was a need to make 4 calls to a database within a function, you would have to write code to connect to the database and interact with it 4 times. When you run the programme, it will run from top to bottom. The code is entirely in control of that. Taking a more abstract approach allows you to write the database code once (as a service or component), and to provide a means of supplying it to the function that needs it at the point it is needed (if at all). In other words, the dependency (the data service) is injected into the calling function. It's a bit like the difference between having to walk around with this lot in your toolbag: and this: Imagine that the main body of the tool in the second image is a Controller. Each of the attachments that plug into it are different data access components. One is for LINQ to SQL, one for the Entity Framework and the last one uses nHibernate internally. The reason that they can so easily be swapped in and out is that they all share a common interface with the main body of the tool. The main body has been designed to expect a component that has been tooled to fit. So long as additional attachments implement the correct interface, there is no reason why you can't build a lot more - a toothbrush, for example, or an egg whisk - and be sure that they will all fit. Ok - this example isn't perfect: the attachment or component is not providing a service to the body of the tool so the analogy falls down a little, but the principle behind common interfaces should be clear. This brings us onto a key Design Principal - Code to an Interface, not an Implementation. Right. First, we need an interface, which will define the methods that the data access component will implement. In this example, there is only one method so far: public interface IContactRepository { IList<Contact> GetContacts(); } Now we move the actual data access out of the Controller into a separate class that implements the IContactRepository interface: public class ContactManagerLinqRepository : IContactRepository { public IList<Contact> GetContacts() { ContactManagerModelDataContext entities = new ContactManagerModelDataContext(); return entities.Contacts.ToList(); } } This particular example uses LINQ to SQL, but the Entity Framework version is very similar: public class ContactManagerEntityRepository : IContactRepository { public IList<Contact> GetContacts() { ContactManagerEntities entities = new ContactManagerEntities(); return entities.ContactSet.ToList(); } } If we go back to the Controller, the change required to make use of the Entity Framework version is as follows: public class ContactController : Controller { private readonly IContactRepository iRepository; public ContactController() : this(new ContactManagerEntityRepository()) {} public ContactController(IContactRepository repository) { iRepository = repository; } public ActionResult Index() { return View(iRepository.GetContacts()); } } When the parameterless constructor is called, it automatically calls the second constructor that has the IContactRepository parameter. That's what the : this(new ContactManagerEntityRepository()) does. It's called constructor chaining. And it is at that point that the dependency (the ContactManagerEntityRepository) gets injected into the Controller.). If you wanted to swap the EF based data access component out and replace it with the LINQ to SQL version, you would simply have to make one change to the Controller. You would no longer pass in an instance of the ContactManagerEntityRepository class into the chained constructor. You would make that ContactManagerLinqRepository instead: public class ContactController : Controller { private readonly IContactRepository iRepository; public ContactController() : this(new ContactManagerLinqRepository()) {} public ContactController(IContactRepository repository) { iRepository = repository; } public ActionResult Index() { return View(iRepository.GetContacts()); } } This is a lot better. The Controller is a lot more loosely coupled to the nature of the component. And this is how both the Contact Manager and the Nerd Dinner samples implement DI. Changes can be made quite simply, although if you have a lot of dependencies things can be a little more complicated. You could use Find and Replace to update multiple controllers, so long as you can be sure you don't accidentally alter other files where the Replace operation breaks things. Hmmm... Do you hear a faint creaking sound in the far off distance? Maybe this approach isn't that rock solid after all, and perhaps that's why the approach outlined above is also known rather derogatorily as "Poor Man's Dependency Injection". IoC Containers Enter the Inversion of Control Container. There is a massive problem with these: Their name. I could go on a rant here about the plethora of simple concepts being totally obscured by the mangling of the English language, but that's for another day. An IoC Container's job is quite simple. You use one to create a mapping between interfaces and concrete types. The containers you tend to see talked about most often for .NET are: Unity CastleWindsor StructureMap Spring.NET Ninject Autofac At runtime, they take care of the responsibility of passing in the correct type. There are lots of IoC containers available. Many of them are open source or freely available. Most of them share the same features, in that they will resolve injection at constructor level (as is required in the above examples) or property or method level. Generally, you would use an xml file to create the mappings - perhaps the web.config file or the container's own configuration file. Some of them also provide an API for configuration in code. On the plus side, xml configuration doesn't require you to recompile when you make changes. On the downside, I dislike xml config files. Using StructureMap StructureMap, at basic level is simple to use. It only takes a couple of steps. The first is to change the Controller code so that the Interface is passed in to the default constructor: public class ContactController : Controller { private readonly IContactRepository iRepository; public ContactController(IContactRepository repository) { iRepository = repository; } public ActionResult Index() { return View(iRepository.GetContacts()); } } You see now that the original empty constructor with its chain has gone. The thing is that the default ControllerFactory used by ASP.NET expects controllers to have parameterless constructors, so we need to create our own ControllerFactory, and get it to pass requests for controllers through StructureMap. StructureMap will examine each one as it comes and look for dependencies in the constructors, and then attempt to resolve those dependencies with concrete types that have been registered with it. So a new ControllerFactory class that inherits DefaultControllerFactory is created: using System; using System.Web.Mvc; using StructureMap; namespace ContactManager.IoC { public class DependencyControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance(Type controllerType) { return ObjectFactory.GetInstance(controllerType) as Controller; } } } The final thing that needs to be done is to register the new Controllerfactory in the Global.asax.cs, along with setting up StructureMap's mappings between interfaces and concrete types. Within the Application_Start() event handler in the Global.asax.cs we add: ControllerBuilder.Current.SetControllerFactory(new DependencyControllerFactory()); to sort out the first bit, and ObjectFactory.Initialize(registry => registry .ForRequestedType<IContactRepository>() .TheDefaultIsConcreteType<ContactManagerLinqRepository>()); to fulfil the second bit. And that's it. How easy was that? OK - a lot of credit goes to Jeremy Miller who is the driving force behind StructureMap itself, but behind that is the fact that IoC containers are a simpler thing than most people who haven't used them realise. There is obviously a whole lot more that StructureMap and other containers can manage for you but they are not difficult to get to grips with. If you find that documentation too obscure, or lacking for one of them, try a different one. Summary Loosely coupling dependencies is pretty much always a good idea. Poor Man's Dependency Injection can be enough for smaller applications that you know won't grow too much, but you can now see that IoC containers are also not that mysterious after all. 24 Comments - AdamA When is your patterns book coming out? ;) You do a great job of explaining these concepts! - Phil Steel Great post. I had a question: Although the IoC container takes care of switching out the IContactRepository concrete instance, the method iRepository.GetContacts() still returns a list of concrete objects of type 'Contact'. Is it best practice to abstract this type out to an interface of type 'IContact' or is this overkill? - Mike Thanks for your comments, but I think if I told my wife I was writing a book, she'd divorce me ;o) - Mike A Contact is a domain object. It's the reason for your application. Data Access (and logging, encryption etc) are services that your application makes use of. The type of service may change, which is why you de-couple them from the main application through Interfaces. Typically for domain objects, if you want to use polymorphism, you would create an abstract superclass (say of type Person) and then for example in a recruitment system which is intended to be used by consultants, you would create concrete implementations that inherit from that class like ClientContact and Candidate. Both of them share a lot of similar properties and behaviour, but one gives you jobs to fill (and would therefore have a Jobs collection as a property) and the other will have a CV property. One will have a MakeOffer() method, and the other will have an AcceptOffer() method. But you would invoke a concrete type depending on which aspect of the workflow the application is handling at that point. You won't decouple your ClientContact object from the application, because it's what that part of the application is all about. - Phil Steel Sorry, yes I understand the Domain object concept. But in your example you say it's easy to switch between the concrete repositories 'ContactManagerLinqRepository' and 'ContactManagerEntityRepository' - LinqToSql and Ef generate their own entities under the hood so the client needs to know about which kind of Contact object (EF or L2S) it's using (i.e. which namespace), right? So don't you need to specifiy that object in your IoC container as an interface as well? E.g.: ObjectFactory.Initialize(registry => registry .ForRequestedType<IContact>() .TheDefaultIsConcreteType<LinqToSqlContact>()); - Phil Steel This link here re-iterates what I actually meant and here on stack overflow Look at the first link, 4 posts down: "If your interface returns objects that are created by the Linq to SQL designer, aren't you tying your interface -- and by extension the controller -- to a Linq to Sql class?" - Mike I checked both links and I can't find anything to suggest that you should create an Interface for the Contact class. There is no such thing as a "LinqToSqlContact" object. If you look at the classes generated by Linq to Sql and EF, when pointed to the same database, they are both "Contact" classes, with more or less the same properties. All the controller knows is that it must obtain an IList<Contact> to pass to the View. It shouldn't know how that list was generated. Run through the code I posted and try to replicate it and get it to work. You will soon see that the only change I had to make using StructureMap was to change the reference to the RequestedType to get it to work. No changes to namespaces either. - Mike Oh - I found the 4th post down (in the video link), and then worked out why you provided the stackoverflow link. At stackoverflow, John Saunders talks about not passing Linq to Sql generated objects across service boundaries because of the baggage they contain. He suggests using DTOs instead, and populating them from Linq to SQL. The DTO will be a basic Contact class with nothing but properties. But there's no hint of an IContact anywhere. - Phil Steel Yup this makes sense. I suppose the only drawback is a) you have to manually populate your domain/business object from your LinqToSQL/EF entities or queries instead of just returning the entities across the boundaries. b) You have to hand craft the stuff which would be done for you otherwise (like INotifyPropertyChanged.) The reason I suggested an interface is so that you could use partial classes in each implementation so your entity could implement an interface and the interface could be passed across the boundary to the presentation layer instead. But I guess a concrete business object makes more sense. Thanks! - Mike Thinking about this a bit more, your approach also makes some sense in some respects. There may come a time when you want to cross service boundaries, but don't know if and when that might happen, so you prepare accordingly. Your points rang a bell somewhere, and when I recently checked the KIGG sample source code, I see that the approach you advocate is used there. Partial classes that implement interfaces. - Evan Larsen Also, I was wondering if its a waste of resources to be always initializing the components on the construction of the controller. Wouldn't tight coupling be more efficient if you only constructed the components when they needed to be used. For instance the 6 components arnt always used in every controller's action. One action might only use 1 component whereas another might use 4. If I used tight coupling, then when an action is called only the compoents that are being used will be constructed as apposed to constructing all 6 everytime with DI. - Mike If you need to instantiate say 6 services within your controller, you will have to produce some code to do that whether you use DI or not. Either way, you will end up with a similar result. If you have services that will only be used by a smalll number of methods within the Controller, you don't have to instantiate them in the controller's constructor. Some IoC containers will allow you to inject them via ActionFilters:. - Sunil Joshi Thanks a lot for the wonderful article. Link to show how we can add structure map in web.config:- Thanks again. Sunil. - Mark - Radu - Erx public ContactController() : this(new ContactManagerEntityRepository()){} being a vb developer who can still read c# code enough to get by, once I didn't know what that did ESP. The : part my comprehension thereafter for everything that followed dropped to less the perhaps 10%... When one thing is missing the rest becomes completely N/A and reading it or not becomes superfluous ... Which is a shame for me because you are very good at explaining things and do so with care, more so then other code bloggers who generally just draw an array of assumptions on the reader and write in a way that explains things for themselves more so than anyone else... Anyway, thanks for the article I have bookmarked you. - Mike The colon after a constructor in C# is what's called a chained constructor. In other words, it calls the overloaded constructor that takes the IContactRepository object as a parameter, and makes sure that the contact repository is instantiated. I have no idea how chained constructors are managed in VB. - jmcilhinney public ContactController() : this(new ContactManagerEntityRepository()){} is equivalent to: Public Sub New() Me.New(New ContactManagerEntityRepository) End Sub It's simply one constructor calling another. 'this' is equivalent to 'Me', i.e. calling a constructor of the same class, while 'base' is equivalent to 'MyBase', i.e. calling a constructor of the base class. - willem d'haeseleer I disagree, if you take the abstraction to the next level you will see that the attachments do provide a service to the body of the tool, but this service is only ever used if the tool it self is being used by a human. If the tool is in use by a human you could say that that the grip of the tool is the contract between the tool and the human, sort off... - Amit Jahanabadi - Chikelue Oji - Preeti - Sunil - yoyo Lionel
http://www.mikesdotnetting.com/article/117/dependency-injection-and-inversion-of-control-with-asp-net-mvc
CC-MAIN-2015-32
refinedweb
3,518
53.71
I am creating a new User model for my Django project. I have been many people calling their custom user model, XXXUser and custom user manager, XXXUserManager. I was wondering if there is a reason for this. Can you just create a custom user and still call it User? Does this create conflicts in the code? Basically you can. But for readability purposes it's better to do it XxxUser, if you see XxxUser you are instantly understand that this is custom one. And you need to keep in mind that you should replace some code that is common for base usage. Such as(should be replaces) from django.contrib.auth.models import User Should be from django.contrib.auth import get_user_model User = get_user_model() And if you reference to User model in your models.py you need to from django.conf import settings class SomeModel(models.Model): field = models.RetationField(settings.AUTH_USER_MODEL) Also do not forget to set your settings.AUTH_USER_MODEL that references to your custom one
https://codedump.io/share/FkwaTOSUNoEw/1/do-you-and-should-you-rename-a-custom-user-model-in-django-19
CC-MAIN-2017-43
refinedweb
167
61.83
include <stdio.h> include <stdlib.h> if defined(WIN32) || defined(WATCOMC) #include <windows.h> #include <conio.h> include <math.h> else #include "../../api/inc/wincompat.h" endif include “../../api/inc/fmod.h” include “../../api/inc/fmod_errors.h” /* optional */ int main() { double samples[44099]; FSOUND_SAMPLE *mysample; //*************************************************** for (int i = 0; i < 44100; ++i) { samples[i] = (10000sin( 2(3.141592)880(i/44100.0)) ); } mysample = FSOUND_Sample_Alloc(FSOUND_FREE, 44100,FSOUND_NORMAL, 44100, 255, 128, 255); FSOUND_Sample_Upload(mysample,samples,FSOUND_NORMAL); FSOUND_PlaySound(FSOUND_FREE, mysample); //*************************************************** return 15; } This code doesn`t work why? - Byte_Junkie asked 13 years ago - You must login to post comments You haven’t studied the example programs why? 😆 But seriously, for a start you need to call FSOUND_Init at the start of your program and FSOUND_Close at the end. You can’t use double for the type of your sample data. Make it unsigned short if you intended to use 16bit samples. Finally, your program exits as soon as it’s called FSOUND_PlaySound. If you want to hear your sound you’ll have to wait for it to play by calling Sleep() or something after FSOUND_PlaySound. - Andrew Scott answered 13 years ago
http://www.fmod.org/questions/question/forum-7126/
CC-MAIN-2016-50
refinedweb
189
69.48
Using LSTM Autoencoder to Detect Anomalies and Classify Rare Events So many times, actually most of real-life data, we have unbalanced data. Data were the events in which we are interested the most are rare and not as frequent as the normal cases. As in fraud detection, for instance. Most of the data is normal cases, whether the data is already labeled or not, and we want to detect the anomalies or when the fraud happens. When dealing with unlabeled data, we usually go to “outliers detection” methods such as Isolation Forest, Cluster-Based Local Outlier Factor (CBLOF), Histogram-Based Outlier Detection (HBOS) etc. While labeled data is considered as a “classification” problem and classifiers like Support Vector Machine (SVM) and Random Forest are used. However, given the positive data points are rare in the data, the algorithm finds it difficult to learn so much from the data. A classifier for example, usually ends up predicting “negative” for all cases to achieve the best accuracy. Here we will look at a different approach that can be used in both supervised and unsupervised anomaly detection and rare event classification problems. Long Short-Term Memory Autoencoders. Long Short-Term Memory neural network is a special type of Recurrent neural networks. LSTMs are great in capturing and learning the intrinsic order in sequential data as they have internal memory. That’s why they are famous in speech recognition and machine translation. On the other hand, an autoencoder can learn the lower dimensional representation of the data capturing the most important features within it. Autoencoder mainly consist of three main parts: 1) Encoder, which tries to reduce data dimensionality. Here we will see how we can combine the two techniques to approach rare event classification. In a previous blog, we have looked at another use case of autoencoders in clustering. Problem Description We will use Credit Card Fraud dataset to predict frauds. The data we will use is available at this GitHub repository. Thanks to this repository, the data is prepared for modelling. Features and normalized and everything is ready for the modeling part. Approach Description Autoencoders try to capture the most important features and structures in data. With the help of LSTMs, it can capture the order in data, and then re-represent it in a denoised lower dimensional form. We will use this power to make the autoencoder learn the features of a normal data point only, i.e. we will train the autoencoder only with the negative/non-fraud observations. The autoencoder will try to compress the data then reconstruct it again. Upon training, the autoencoder will be able to reconstruct the normal observations with small error or difference between the original data. However, when it tries to predict/reconstruct a positive/fraud observation, it will somehow be surprised as it never saw such sequences while trained. So the reconstruction error between original and reconstructed data will be high for fraudulent ones than for normal ones. We will then set the threshold that separates the normal and the fraud observations. Things will be clearer with code. So let’s get into the real work. N.B. This technique is useful for unsupervised anomaly detection as well. Data Preparation As usual we will start importing all the classes and functions we will need. import tarfile import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from keras.models import Input, Model from keras.layers import Dense, LSTM from keras.layers import RepeatVector, TimeDistributed from keras import optimizers from keras.callbacks import ModelCheckpoint, EarlyStopping from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, precision_recall_curve from sklearn.metrics import accuracy_score, precision_score from sklearn.metrics import recall_score, auc, roc_curve np.random.seed(13) Now we will read the downloaded data and look at the percentage of the positive class in it. with tarfile.open("creditcardfraud_normalised.tar.gz", "r:*") as tar: csv_path = tar.getnames()[0] df = pd.read_csv(tar.extractfile(csv_path)) df.head() print("class counts:\n", df["class"].value_counts()) print("\n%% of positive values in data: %.2f%%" % ((df[df["class"] == 1].shape[0] / df.shape[0]) * 100)) # class counts: # 0 284315 # 1 492 # Name: class, dtype: int64 # % of positive values in data: 0.17% To make the problem a little bit harder, we will make the positive observations a little bit more scarse by removing some of it randomly. df = df.drop(df.query("`class` > 0").sample(frac = 0.25).index) print(df["class"].value_counts()) print("\n%% of positive values in data after deleting some: %.2f%%" % ((df[df["class"] == 1].shape[0] / df.shape[0]) * 100)) predictors = df.drop(["class"], axis = 1) target = df["class"] # 0 284315 # 1 369 # Name: class, dtype: int64 # % of positive values in data after deleting some: 0.13% As we have mentioned, the data is already transform, normalized and prepared for modeling, so we will now split the data into train and test. X_train, X_test, y_train, y_test = train_test_split( predictors, target, stratify = target, random_state = 13, test_size = 0.25) We want to train the autoencoder with negative observations only, so we willprepare the train dataset with removing all positive cases. Also from the test dataset we prepare a validation dataset that we will use while modeling and afterwards to se the threshold. X_val = X_test[:3000] y_val = y_test[:3000] X_test = X_test[3000:] y_test = y_test[3000:] X_train_0 = X_train[y_train != 1] y_train_0 = y_train[y_train != 1] X_test_0 = X_test[y_test != 1] X_val_0 = X_val[y_val != 1] y_train_0 = y_train[y_train != 1] LSTMs expect a 3D arrays, so we will define a function that converts 2D to 3D arrays. In addition, we will define a function that flattens a 3D array back to a 2D one. The mse_3d function will calculate the reconstruction error between the original and the reconstructed data. def arr_reshape(x, arr_type = "float32"): return np.asarray(x).astype(arr_type).reshape((-1, 1, x.shape[1])) def flatten(arr): return arr.reshape(-1, arr.shape[-1]) def mse_3d(x, y): return np.mean(np.power(flatten(x) - flatten(y), 2), axis = 1) We now reshape all data that the autoencoder will use. reshaped_train_0 = arr_reshape(X_train_0) reshaped_val_0 = arr_reshape(X_val_0) reshaped_test_0 = arr_reshape(X_test_0) reshaped_val = arr_reshape(X_val) reshaped_test = arr_reshape(X_test) reshaped_train = arr_reshape(X_train) inputs_dim = reshaped_train_0.shape[2] Now to the fun part. The model. We will wrap the model and all its function a Python class so that we have everything in one place. The class methods will have default arguments with the values that we decided to use in our model. Feel free to change them if needed. class LSTMAutoencoder(Model): ## the class is initiated with the number of dimensions and ## timesteps (the 2nd dimension in the 3 dimensions) ## and the number of dimensions to which we want the encoder ## to represent the data (bottleneck) def __init__(self, n_dims, n_timesteps = 1, n_bottleneck = 8, bottleneck_name = "bottleneck"): super().__init__() self.bottleneck_name = bottleneck_name self.build_model(n_dims, n_timesteps, n_bottleneck) ## each of the encoder and decoder will have two layers ## with hard coded parameters for simplicity def build_model(self, n_dims, n_timesteps, n_bottleneck): self.inputs = Input(shape = (n_timesteps, n_dims)) e = LSTM(16, activation = "relu", return_sequences = True)(self.inputs) ## code layer or compressed form of data produced by the autoencoder self.bottleneck = LSTM(n_bottleneck, activation = "relu", return_sequences = False, name = self.bottleneck_name)(e) e = RepeatVector(n_timesteps)(self.bottleneck) decoder = LSTM(n_bottleneck, activation = "relu", return_sequences = True)(e) decoder = LSTM(16, activation = "relu", return_sequences = True)(decoder) self.outputs = TimeDistributed(Dense(n_dims))(decoder) self.model = Model(inputs = self.inputs, outputs = self.outputs) ## model summary def summary(self): return self.model.summary() ## compiling the model with adam optimizer and mean squared error loss def compile_(self, lr = 0.0003, loss = "mse", opt = "adam"): if opt == "adam": opt = optimizers.Adam(learning_rate = lr) else: opt = optimizers.SGD(learning_rate = lr) self.model.compile(loss = loss, optimizer = opt) ## adding some model checkpoints to ensure the best values will be saved ## and early stopping to prevent the model from running in vain def callbacks(self, **kwargs): self.mc = ModelCheckpoint(filepath = kwargs.get("filename"), save_best_only = True, verbose = 0) self.es = EarlyStopping(monitor = kwargs.get("monitor"), patience = kwargs.get("patience")) ## model fit def train(self, x, y, x_val = None, y_val = None, n_epochs = 15, batch_size = 32, verbose = 1, callbacks = None): if x_val is not None: self.model.fit(x, y, validation_split = 0.2, epochs = n_epochs, verbose = verbose, batch_size = batch_size) else: self.model.fit(x, y, validation_data = (x_val, y_val), epochs = n_epochs, verbose = verbose, batch_size = batch_size, callbacks = [self.mc, self.es]) ## reconstruct the new data ## should be with lower error for negative values than ## the error with the positive ones def predict(self, xtest): return self.model.predict(xtest) ## after investigating the error differences, we set the threshold def set_threshold(self, t): self.threshold = t ## after setting the threshold, we can now predict the classes from the ## reconstructed data def predict_class(self, x_test, predicted): mse = mse_3d(x_test, predicted) return 1 * (mse > self.threshold) ## in case we are interested in extracting the (bottleneck) the low-dimensional ## representation of the data def encoder(self, x): self.encoder_layer = Model(inputs = self.inputs, outputs = self.bottleneck) return self.encoder_layer.predict(x) Initiate now the model. lstm = LSTMAutoencoder(inputs_dim) lstm.model.summary() # Model: "model" # _________________________________________________________________ # Layer (type) Output Shape Param # # ================================================================= # input_1 (InputLayer) [(None, 1, 29)] 0 # _________________________________________________________________ # lstm (LSTM) (None, 1, 16) 2944 # _________________________________________________________________ # bottleneck (LSTM) (None, 8) 800 # _________________________________________________________________ # repeat_vector (RepeatVector) (None, 1, 8) 0 # _________________________________________________________________ # lstm_1 (LSTM) (None, 1, 8) 544 # _________________________________________________________________ # lstm_2 (LSTM) (None, 1, 16) 1600 # _________________________________________________________________ # time_distributed (TimeDistri (None, 1, 29) 493 # ================================================================= # Total params: 6,381 # Trainable params: 6,381 # Non-trainable params: 0 # _________________________________________________________________ Setting the callbacks and compiling the model. lstm.callbacks(filename = "./lstm_autoenc.h5", patience = 3, monitor = "val_loss") lstm.compile_() The main step! Model fitting on the negative/non-fraud observations. lstm.train(reshaped_train_0, reshaped_train_0, reshaped_val_0, reshaped_val_0, n_epochs = 10) # Epoch 1/10 # 5331/5331 [==============================] - 15s 2ms/step - loss: 0.0515 - val_loss: 0.0016 # Epoch 2/10 # 5331/5331 [==============================] - 13s 2ms/step - loss: 0.0016 - val_loss: 0.0015 # ... # ... # Epoch 10/10 # 5331/5331 [==============================] - 13s 2ms/step - loss: 8.0738e-04 - val_loss: 7.6509e-04 Now the model seems to have kind of converged. Great! Now let’s try to set the threshold that separates the normal from the fraud cases. We will make the model predict/reconstruct the validation data (including the positive cases) and compute the Mean Squared Error between the reconstructed and original data. Then using the actual classes and the error values, we will calculate and plot the recall and precision and try to spot a suitable error value that gives good recall and precision. val_preds = lstm.predict(reshaped_val) val_mse = mse_3d(reshaped_val, val_preds) val_error = pd.DataFrame({ "mse": val_mse, "actual": y_val }) precision, recall, threshold = precision_recall_curve( val_error["actual"], val_error["mse"]) val_prt = pd.DataFrame({ "threshold": threshold, "recall": recall[1:], "precision": precision[1:] }) val_prt_melted = pd.melt(val_prt, id_vars = ["threshold"], value_vars = ["recall", "precision"]) sns.lineplot(x = "threshold", y = "value", hue = "variable", data = val_prt_melted) Value 0.01 seems to be a good threshold. Having a very low value, can mean that negative and positive cases are somehow so similar in essence. lstm.set_threshold(0.01) Now we look at how this threshold value can separate the cases in the test data. We will first reconstruct the test dataset and again compute the MSE between the reconstructed and original data. test_preds = lstm.predict(reshaped_test) test_mse = mse_3d(reshaped_test, test_preds) test_error = pd.DataFrame({"mse": test_mse, "actual": y_test}) Let’s now see the distribution of the error values and how well the threshold separates the error (high) for the positive cases. g = sns.histplot(x = "mse", hue = "actual", data = test_error, bins = 100) plt.axvline(lstm.threshold, color = "r", label = "threshold") plt.legend(loc = "upper right") g.set_yscale("log") plt.show() It seems that after the threshold, yes the positive cases increase while the negative ones decrease. Another visualization for the threshold g = sns.scatterplot( x = "index", y = "mse", hue = "actual", style = "actual", data = test_error.reset_index(), palette = {0: "#4878CF", 1: "#D65F5F"}, alpha = 0.6) g.set(ylim = (0, max(test_error.mse))) g.axhline(lstm.threshold, color = "black", linewidth = 3) As we see, the normal cases seem to lie down the threshold and most of the fraud cases are above it. Let’s now evaluate the model performance and look at the accuracy, recall and precision as well as the confusion matrix. pred_y = lstm.predict_class(reshaped_test, test_preds) conf_matrix = confusion_matrix(y_test, pred_y) print("Accuracy: %.2f%%" % (100 * accuracy_score(y_test, pred_y))) print("Precision: %.2f%%" % (100 * precision_score(y_test, pred_y))) print("Recall: %.2f%%" % (100 * recall_score(y_test, pred_y))) # Accuracy: 99.84% # Precision: 40.00% # Recall: 64.29% sns.heatmap(conf_matrix, xticklabels = ["normal", "fraud"], yticklabels=["normal", "fraud"], annot = True, fmt = "d") plt.ylabel("actual") plt.xlabel("predicted") plt.show() Looking at the Area Under the Curve (AUC) is also important in evaluating a classifier. fpr, tpr, _ = roc_curve(test_error["actual"], test_error["mse"]) roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, ls = "--", label = "LSTM AUC = %0.2f" % roc_auc) plt.plot([0,1], [0,1], c = "r", label = "No Skill AUC = 0.5") plt.legend(loc = "lower right") plt.ylabel("true positive rate") plt.xlabel("false positive rate") plt.show() The autoencoder with the set threshold seems to perform so well in detecting the anomalies (fraud cases). Another classifier, like SVM or Logistic Regression, would perform better on this data. But LSTM Autoencoder outperforms them when the positive observations are so scarse in data. It is really a great tool to add to your skilset.
https://minimatech.org/lstm-autoencoder-for-anomaly-detection-in-python-with-keras/
CC-MAIN-2021-31
refinedweb
2,216
51.34
Man Page Manual Section... (2) - page: mkdirat NAMEmkdirat - create a directory relative to a directory file descriptor SYNOPSIS #include <fcntl.h> /* Definition of AT_* constants */ #include <sys/stat.h> int mkdirat(int dirfd, const char *pathname, mode_t mode); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): mkdirat(): Since glibc 2.10: _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L Before glibc 2.10: _ATFILE_SOURCE DESCRIPTIONThe mkdirat() system call operates in exactly the same way as mkdirdir(2) for a relative pathname). If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like mkdir(2)). If pathname is absolute, then dirfd is ignored. RETURN VALUEOn success, mkdirat() returns 0. On error, -1 is returned and errno is set to indicate the error. ERRORSThe same errors that occur for mkdir(2) can also occur for mkdirat().. CONFORMING TOPOSIX.1-2008. NOTESSee openat(2) for an explanation of the need for mkdirat(). SEE ALSOmkdir(2), openat
https://linux.co.uk/documentation/man-pages/system-calls-2/man-page/?section=2&page=mkdirat
CC-MAIN-2017-09
refinedweb
165
51.24
Arduino Uno + Wireless proto shield + Wifly module (1/13) > >> sponder: Hi Arduino community!! Let me do a quick introduction here since i'm new, and this would be my first post on these forums. -- a few years back i ran into this project controlling RGB leds using a PIC microcontroller. This project really triggered an interest in finding out how this stuff works, and how to program these microcontrollers. So, a few books (mainly on c for PIC's) later, and a few projects later, i decided to try out Arduino. (Arduino is kind of hard to miss once you get to play with microcontrollers) So i bought myself a Arduino Uno r3 . After doing a few tutorials (bought some getting started books on arduino as well as the Arduino Cookbook.) it was time to do something a little more advanced. To make things a bit more interesting, i bought a Wifly module to put into a Wireless proto shield I would like to start off easy (hello world), by controlling a led: - either wireless by making a socket to a server app. (got one by following ms c# tutorials 8) ) - or control the led through serial, and letting the arduino host a webpage showing the status of the led. Hooking up the Wifly module wasn't very difficult, i hooked the Wifly module up to the Arduino using the Wireless proto shield, and as per instructions in the manual, i got into command mode, scan all the WLANS in my appartment, and associating with my own SSID. The unit got an IP straight away, and it responds to ping requests. So i figure the module is connected to my WLAN! Anyway, i soon found out that there are some compatibility issues with the Wifly library and Arduino 1.0 The example code did not compile, and i don't have the skills (yet XD) to fix this myself. after searching the internet for help i finally found a library which is supposed to be compatible, and made a VERY simple sketch: after the #include "WiFly.h" #include "Credentials.h" //file modifed obviously.. in the setup i have the serial.begin, and in the main loop i just write "hi" to the serial port with a delay before looping. If i upload this sketch i see the "hi" messages coming into my terminal. But, once i do a WiFly.begin(); in the setup part (as in the examples) i can still compile and upload the code, but the arduino seems to get stuck. The lights of the wifly unit blinks as it's telling us it's connected to the network (still can ping the unit), but it never starts sending out the "hi" message to the serial port. If i comment out the WiFly.begin(); the unit starts sending the mssg to the serial port again. So it seems that the arduino hangs on the WiFly.begin(); method. Can someone please tell me how to troubleshoot this? or, get me up and running using the Wifly shield using Arduino 1.0? Any help would be very appreciated! Thanks in advance, Sander. PaulS: Quote Can someone please tell me how to troubleshoot this? or, get me up and running using the Wifly shield using Arduino 1.0? Without seeing your code, no, I'm afraid not. sponder: thanks for your answer. The code i used couldn't be more simple: To see where it hangs i simply stripped out everything :) The code which does give me the mssg to the terminal: Code: #include "WiFly.h" #include "Credentials.h" Server server(80); void setup() { // WiFly.begin(); Serial.begin(9600); } void loop() { Serial.print("Ping"); delay(100); } While this doesn't. Code: #include "WiFly.h" #include "Credentials.h" Server server(80); void setup() { WiFly.begin(); Serial.begin(9600); } void loop() { Serial.print("Ping"); delay(100); } in both cases i can ping the unit though.. thanks again! sponder: Well, it would be a pretty cool device if i could get it to work. Any advice for a newb like myself to find a working library? I'm not the only one without the issue that the library isn't working with arduino > v22 I know i'm not providing much info here, but i don't really know what i could test / try to come up with additional info. Would my conclusion be correct to say that it is the Wifly library which does compile is the cause of the unit hanging? (since unit does not hang without the Wifly.Begin()) Any other tips how to proceed? Many thanks! dhunt: Why not skip using the library to start with and just configure the wifly using the serial monitor? Are you wanting to do anything that would require changing the config on the fly? E.g switching between TCP and UDP protocols, sending packets to more than one host? If not then you don't need the wifly library. Once the wifly is configured it will send anything the arduino writes to its serial port as a UDP or TCP packet to the configured host address and port. The wifly will also send the payload of any packets it receives to the Arduino's serial port. Navigation [0] Message Index [#] Next page
http://forum.arduino.cc/index.php?topic=89501.0;wap2
CC-MAIN-2014-10
refinedweb
878
73.78
41224/namespace-servicehost-exist-namespace-system-servicemodel So, I'm attempting to add this wcf service in an app for Windows IoT(Raspberry Pi) using Visual Studio 2015. Now, I can't add a reference 'on the usual way' .So, I tried adding a nuget reference to System.ServiceModel. using (var host = new System.ServiceModel.ServiceHost (typeof(HelloWorldService), _baseAddress)) { } How can I reach the ServiceHost? Resharper doesn't help either! This is a way I can think ...READ MORE In IoT Hub there is a device ...READ MORE That exception comes when access limited to ...READ MORE IoT-Workbench now uses new improved code generation ...READ MORE Try the PInvoke api methods from Iphlpapi.dll. ...READ MORE Now, data rates of IEEE 802.15.4 are ...READ MORE That's because the XAML designer on Visual ...READ MORE It indicates that you don't have admin ...READ MORE If you look in the solution file ...READ MORE Verify none of your custom user controls ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/41224/namespace-servicehost-exist-namespace-system-servicemodel
CC-MAIN-2020-16
refinedweb
173
62.34
Problems with Pin class Hi. I'm trying to modify the DHT22 class ( to work on WiPy2 No matter what I try to put in line 37: nc = Pin(nc_pin, mode=Pin.OPEN_DRAIN, pull=None, alt=-1) The result is always: Traceback (most recent call last): File "<stdin>", line 13, in <module> File "/flash/lib/dht/DHT22.py", line 37, in init ValueError: invalid argument(s) value This is my code to use the class: from dht import DHT22 DHT22.init(nc_pin=5, gnd_pin = 'GND', vcc_pin='3V3 OUT', data_pin=6) Another question: the original DHT22 class want to know the GND and 3V3 pin: how are they mapped in machine library? Thanks - Xykon administrators last edited by I've had a look at the code... Timers are not yet implemented so this code will not yet work. Also your init should use correct pin names, example: 'P5', 'P6' etc. - Xykon administrators last edited by The possibility to use alternate functions for Pins has not been implemented yet. You could try without the alt=-1 part.
https://forum.pycom.io/topic/205/problems-with-pin-class
CC-MAIN-2022-21
refinedweb
175
72.46
- Multiple Cpp Files - Graphics problems - object orientated programme - Question on how to proceed(Game programming, kinda long). - cube root - Using a doubly-linked list to create a deque class. - Zeller's Formula - grand total - problem with inventory program - When to Allocate or Not to Allocate - COM/ATL or static Library - Small problem I need help with. - Static vs. Automatic Variables - Visual C++ 2005 Express: Run Time Library - Direct X 9.0 - Inheritance! - Problem with floating point numbers - a browser control in a ATL DLL - Using mscorlib & system namespace in an MFC? - Deleting Duplicate Proxies - adding two matrix - Printing an unsorted list - File Output - BST (Binary search tree) - delete invalid data from an array - making a programme - Confusing pointer - Decoding applications? - inline confusion - Word Jumbling - Visual C++ 2005 linking and file sizes - Derived class linking error - Code works in MS Visual C++, not in Dev-C++ - Debug failure error - delete Assertion Failure - Deallocating a character pointer array - Which key should I use? - Pointers - Question about memory taken by list structur. - Reading the frequency of the speaker. - Need help with using strings in classes - Shell Commands - Need some help,GPA program - BYTE, char data corruption - Another newbie Question>Ifstream, Ofstream, DamnStream. - code only works with 3 digits - Easiest 2D drawing library for bloodshed compiler? - Linked Lists Question - reading 3 ints from one line, then 3 from another - clock and cycle times' effect on counter time?
http://cboard.cprogramming.com/sitemap/f-3-p-523.html?s=1bcc0b95420a52a5f00097d0f95e3790
CC-MAIN-2014-35
refinedweb
233
52.39
There are a lot of ways to work with color on the web. I think it’s helpful to understand the mechanics behind what you’re using, and color is no exception. Let's delve into some of the technical details of color on the web. Color mixing A huge part of working with color is understanding that the way that you used color as a child doesn’t work the same as how you use color on a computer because of color mixing. As a child, you’re working with paint. Paint and inks from a printer have tiny particles called pigments that mix together and reflect to present color to your eye. This is subtractive color mixing. The more colors you add to it, the darker it becomes, until we get brown. Primaries are close to what you’re used to: red, yellow, blue. But when you mix these colors with subtractive color mixing, you arrive at brown. On a computer (or any monitor), we’re working with light. Which means that when all of the colors mix together, they make white. Before Isaac Newton’s famous prism color experiment, color was believed to be contained within objects rather than reflected and absorbed from the object. Isaac Newton used a prism to prove his theory that sunlight or bright white light was in fact several colors by using the prism to split apart the colors to make a rainbow, and then subsequently using a prism to attempt to further split the blue. The blue did not split, showing that the color wasn’t within the prism, but rather that the prism was splitting the light. This means that in additive color mixing, the type of color mixing you get in a monitor, red green and blue can be used to produce all colors, or rgb. In this type of mixing, red and green create yellow. Monitors are many combinations of small bits of light combined that resonate to create a myriad of colors. Resolution refers to the number of individual dots of color, known as pixels, contained on a display. Before we had monitors, artists were using this type of light frequency. Seurat and the Pointillists used red and green to create yellow in paintings like “La Grande Jatte” (though he preferred the term chromo-luminarism. Others called it divisionism) This type of painting was created under the belief that optical mixing created more pure resonance in your eye that traditional subtractive pigment color mixing. Monitors are made in a few different display modes that change the way we perceive color through them. We express this the term “color bit depth”. The number of colors that can be displayed at one time is determined by this color bit depth. If we have a bit depth of 1, we can produce two colors, or monochrome. Bit depth of two levels creates 4, and so on until we reach a bit-depth of 32, though commonly monitors that project the web have 24 bit-depth density and 16,777,216 colors which is True Color and Alpha Channel. We call this True Color because our human eyes can discern 10,000,000 unique colors, so 24-bit depth will certainly allow for this. In this 24-bit depth, 8 bits are dedicated to red, green, and blue. The rest are used for transparency or alpha channels. Let’s use this information to unpack our available color properties on the web. Color values RGB Values The last section illustrates what rbga(x, x, x, y); communicates, but let’s break that down a bit more, and show some other properties and their uses. In terms of web color values in an RGB channel, we specify color on a range from 0-255. x is a number from 0-255 y is a number from 0.0 to 1.0 rgb(x, x, x); or rgba(x, x, x, y); Example: rbga(150, 150, 150, 0.5); Hex Values Hex colors are a slightly different format to represent the values in the same way. Hex values are probably the most common way developers designate color on the web. If you recall that a byte is 8 bits, each Hex color or number represents a byte. A color is specified according to the intensity of its red, green and blue components, so we call it a triplet, with each expressed in two places. One byte represents a number in the range 00 to FF (in hexadecimal notation), or 0 to 255 in decimal notation. Byte 1 is Red, byte 2 is green, and byte 3 is blue. Hexadecimal is named this because it uses a base 16 system. The values use ranges from 0-9 and A-F, 0 being the lowest value and F being the highest, or #00000 being black and #FFFFFF being white. For triplets with repeated values, you can eliminate the repetition by writing in shorthand, for instance, #00FFFF becomes #0FF. This system is easy for computers to understand, and it pretty short to write, which makes it useful for quick copy paste and designation in programming. If you’re going to work with colors in a more involved way, though, HSL is a little bit more human-readable. HSL Values Hsl values work with similar semantics and ranges as rgb, but rather than working with values as the monitor interprets the colors, hsl values work with hue, saturation, lightness values. This looks syntactically similar to rgb values but the ranges are different. This system is based on a Munsell color system (he was the first to separate out color into these three channels, or create a three dimensional system based on mathematical principles tied to actual human vision). Hue rotates in 360 degrees, a full circle, while saturation and lightness are percentages from 0 to 100. x is a number from 0 - 360 y is a percentage from 0% to 100% z is a number from 0.0 to 1.0 hsl(x, y, y); or hsla(x, y, y, z); Example: hsla(150, 50%, 50%, 0.5); It’s a relatively easy change (around 11 lines of code, to be precise) for the browsers to exchange between rgb and hsl values, but for us humans, the use of hsl can be a lot easier to interpret. Imagine a wheel, with dense and saturated content at the center. This demo does a pretty good job of showing how it’s expressed. If you don't feel particularly skilled working with color, hsla() allows for some pretty simple rules to create nice effects for developers. We cover more about this in the generative color section below. Named Colors Named colors are also available to us as developers. Named colors, though, have a reputation for being difficult to work with due to their imprecision. The most notable and “famous” examples are that dark grey is actually lighter than grey and lime and limegreen are totally different colors. There’s even a game where you can try to guess named colors on the web, made by Chris Heilmann. Back in the old days, chucknorris was a blood red color (it's only supported in HTML now as far as I can tell), but that was my favorite. Named colors can be useful for demonstrating color use quickly, but typically developers use Sass or other preprocessors to store color values by hex, rgba, or hsla and map them to color names used within the company. Color Variables A good practice is to store color variables and never use them directly, mapping them instead to other variables with more semantic naming schemes. CSS has native variables, like: :root { --brandColor: red; } body { background: var(--brandColor); } But they are fairly new and haven't made their way into Microsoft browsers at the time of this writing. CSS preprocessors also support variables, so you can set up variables like $brandPrimary to use through your code base. Or a map: $colors: ( mainBrand: #FA6ACC, secondaryBrand: #F02A52, highlight: #09A6E4 ); @function color($key) { @if map-has-key($colors, $key) { @return map-get($colors, $key); } @warn "Unknown `#{$key}` in $colors."; @return null; } // _component.scss .element { background-color: color(highlight); // #09A6E4 } Remember that naming is important here. Abstract naming is sometimes useful so that if you change a variable that was representing a blue color to an orange color, you don’t have to go through and rename all of your color values. Or worse yet, put up a sign that says "$blue is orange now." *sad trombone noise* currentColor currentColor is an incredibly useful value. It respects the cascade, and is useful for extending a color value to things like box shadows, outlines, borders, or even backgrounds. Let’s say you have created a div and then inside it another div. This would create orange borders for the internal div: .div-external { color: orange; } .div-internal { border: 1px solid currentColor; } This is incredibly useful for icon systems, either SVG icons for icon fonts. You can set currentColor as the default for the fill, stroke, or color, and then use semantically appropriate CSS classes to style the sucker. Preprocessors CSS preprocessors are great for tweaking colors. Here's some links to different preprocessors documentation on color functions: - Sass functions - Less functions - Stylus functions - Example PostCSS plugin for color functions Here are a few of the cool things we can specifically with Sass: mix($color1, $color2, [$weight]) adjust-hue($color, $degrees) lighten($color, $amount) darken($color, $amount) saturate($color, $amount) There are truthfully dozens of ways to programmatically mix and alter colors with preprocessors, and we won’t go into depth for all of them, but here’s a great interactive resource for more in-depth information. Color Properties Color, as a CSS property, refers to font color. If you’re setting a color on a large area, you would use background-color, unless it’s an SVG element in which case you would use fill. Border is the border around an HTML element, while stroke is it’s SVG counterpart. Box and Text Shadows The box-shadow and text-shadow properties accept a color value. Text shadows accept 2-3 values, h-shadow (horizontal shadow), v-shadow (vertical shadow), and an optional blur-radius. Box shadows take 2-4 values, h-shadow, v-shadow, optional blur distance, and optional spread distance. You can also designate inset at the start to create an inverted shadow. This site has a great demo with easy, pasteable code. Gradients Linear gradients work by designating a direction. From/to (depending on the browser prefix) top, bottom, left, right, degrees, or radial-gradients. We then specify color stops and the color we want at each stop. These can accept transparency too. Here’s an example: See the Pen 0df6e25c52fedba5ed5fd221d082e539 by Sarah Drasner (@sdras) on CodePen. Most of the syntax of gradients isn’t all that difficult to write, but I really enjoy working with this online gradient generator, because it also creates the complicated filter property for IE6-9 support. Here is also a really beautiful UI gradient creator. This one is pretty cool and it is open source and you can contribute to it. Gradients are similarly easy to create in SVG. We define a <linearGradient> block that you reference with an id. We can optionally define a surface area for the gradient as well. <linearGradient id="Gradient"> <stop id="stop1" offset="0" stop- <stop id="stop2" offset="0.3" stop- </linearGradient> These gradients also support opacity so we can have some nice effects and layer effects like animate them as as a mask. See the Pen Animating transparent mask by Sarah Drasner (@sdras) on CodePen. Gradient text is also possible in webkit only, we have a really a nice code snippet for that here on CSS-Tricks. Generative Color There are a few cool ways to drum up a lot of staggering colors at once. I find these to be really fun to play with when creating generative art or UI elements with code. As long as you stay within the ranges designated in the last sections, you can use for loops in either Sass (or any CSS preprocessor) or JavaScript, or Math.Random() with Math.floor() to retrieve color values. We need Math.floor() or Math.ceil() here because if we don’t return full integers, we’ll get an error and do not get a color value. A good rule of thumb is that you shouldn’t update all three values. I’ve had good luck with a lot of deviation in one range of values, a smaller deviation in the second set of values, and no deviation for the third, not necessarily in that order. For instance, hsl is very easy to work with to step through color because you know that looping through the hue from 0 to 360 will give you a full range. Another nice grace of hue-rotate in degrees is that because it's a full circle, you don't need to stick to ranges of 0 - 360, even -480 or 600 is still a value a browser can interpret. Sass @mixin colors($max, $color-frequency) { $color: 300/$max; @for $i from 1 through $max { .s#{$i} { border: 1px solid hsl(($i - 10)*($color*1.25), ($i - 1)*($color / $color-frequency), 40%); } } } .demo { @include colors(20,2); } I use that to make fruit loop colors in this demo: See the Pen React-Motion and Color Animation Experiment by Sarah Drasner (@sdras) on CodePen. As well as this one, with a different range (scroll inside the list really fast): See the Pen Playing with Lists and Scroll by Sarah Drasner (@sdras) on CodePen. In the code below, I'm using Math.random() within rgb values to drum up a lot of color within the same range. This demo is creating a three-dimensional VR experience with React. I could have stepped through it with a for loop as well, but I wanted the color to be randomized to reflect the movement. Sky's the limit on this one. JavaScript class App extends React.Component { render () { const items = [], amt1 = 5, amt2 = 7; for (let i = 0; i < 30; i++) { let rando = Math.floor(Math.random() * (amt2 - 0 + 1)) + 0, addColor1 = parseInt(rando * i), addColor2 = 255 - parseInt(7 * i), updateColor = `rgb(200, ${addColor1}, ${addColor2})`; items.push(<Entity geometry="primitive: box; depth: 1.5; height: 1.5; width: 6" material={{color: updateColor}} ... key={i}> ... </Entity>); } return ( <Scene> ... {items} </Scene> ); } } GreenSock came out with a tool that allows you to animate relative color values, which is useful because it means you can grab a lot of elements at once and animate them relative to their current color coordinates. Here are some turtles that demonstrate the idea: See the Pen Turtles that show Relative HSL tweening by Sarah Drasner (@sdras) on CodePen. TweenMax.to(".turtle2 path, .turtle2 circle, .turtle2 ellipse", 1.5, {fill:"hsl(+=0, +=50%, +=0%)"}); Other Nice Color Effects Mix Blend Modes and Background Blend Modes If you’ve used layer effects in Photoshop, you’re probably familiar with mix blend modes. Almost every site in the 90s used them (mine did. *blush*). Mix and background blend modes composite two different layered images together, and there are 16 modes available. Going through each is beyond the scope of this article, but here are some key examples. The top image or color is called the source, and the bottom layer is called the destination. The area between the two is where the blending magic happens and is called the backdrop. We’re mixing both according to fairly simple mathematical formulas. If you want to get really nerdy with me, the color formulas for the blend modes depend on the type of effect used. For instance, multiply is destination × source = backdrop. Other effects are variations of simple math using subtraction, multiplication, addition, and division. Linear is A+B−1, while Color Burn is 1−(1−B)÷A. You don’t really need to know any of these to use them, though. Here is some more extensive documentation, and here's a very simple demo to illustrate color working with some of these effects: See the Pen Demo-ing Mix Blend Modes with SVG by Sarah Drasner (@sdras) on CodePen. This great article by Robin demonstrates some really complex and impressive effects you can achieve from layering multiple blend modes as well. Below we'll cover mixing them with filters. There's really a lot you can do in the browser these days. Filters CSS Filters provide a lot of cool color effects, as well as the ability to take a colored image and make it greyscale. We have a great resource here on CSS-Tricks that shows how these work, and the browser support is pretty high now. Bennett Feely also has this nice filter gallery if you’re feeling explorative. Filters and Blur modes can work together! Una Kravets created this cool tool called CSS Gram combining some effects to create typical instagram filters, she has some nice documentation at the bottom. feColorMatrix Una has another article exploring the creation of these images with feColorMatrix instead, which is a filter primitive in SVG that can be applied to HTML elements as well. It’s very powerful, and allows you to fine-tune and finesse color. As the name implies, the base markup of feColorMatrix uses a matrix of values, and we apply it using it’s relative id. <filter id="imInTheMatrix"> <feColorMatrix in="SourceGraphic" type="matrix" values="0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0" /> </filter> <path filter="url(#imInTheMatrix)" … /> We can also extend this matrix and adjust the hue, saturation, etc, of these values: <filter id="imInTheHueMatrix"> <feColorMatrix in="SourceGraphic" type="hueRotate" values="150" /> </filter> Una’s article goes into depth exploring all of the capabilities here, but you can get even more information on this and a lot of other crazy SVG colors and gradient tools with Amelia Belamy-Royd’s O’Reilly Book, SVG Colors, Patterns & Gradients or Mike Mullany’s exploratory demo. Accessibility and Other Things to Note about Color A color is only a color in reference to another color. This is part of what makes color so difficult.. Once you’re all set up, WAVE (Web Accessibility Tool) will help you evaluate your web page: Color and Atmosphere Color is affected by atmosphere, which is a pretty important thing to know if you’re going to create any kind of illusion of depth. Things that are closer to you are in higher saturation, and in more contrast. Things that are further away from you are going to look blurrier. Shadows Shadows are not grey, they are the compliment of the color of the light. If the light you shine on your hand has a yellow cast, the shadow will appear purple. This is useful knowledge if you’re making any super hip long shadows. Native Color Inputs There is a native browser color selector that you can employ to help your users select colors dynamically. You can write <input type="color"> or <input type="color" value="#ff0000"> if you'd like to start off with color hinting. It's that simple to use. Good job, browsers. One thing to keep in mind is that the way that it will appear will vary slightly from browser to browser, just like any other native controls. This pen from Noah Blon shows how to use that in tandem with a hue CSS color filter to dynamically select portions of an image to change the color of. The rest of image is greyscale, so it's not affected. Pretty clever. Fun Developer Stuff and Other Resources - The Color Highlighter Plugin for Sublime Text is what I use to easily see what color the browser is going to interpret. I like to use {"ha_style": "outlined"}but I know from this article that Wes Bos prefers “filled”. - There are some different traditional palette combinations, and online web resources that can help you drum these up. For the more scientific, Paletton or Adobe Color. Benjamin Knight recreated Adobe's color tool in d3 on CodePen, which is pretty badass and worth checking out. If you want the web to do the heavy lifting for you (who doesn't?), Coolors is as simple as can be. - If you need help interpreting colors, and want a quick simple tool to exchange types of color properties for you, Colorhexa has you covered in pretty much every type of color exchange you can think of. - For the nerdiest of color nerds, you can even have your console output in colors to you. Here's a great Pen showing how that works. Conclusion The scope of this article is rather large, and the web has a lot of color to delve into, but hopefully this short article gives you a jumping off point for some experimentation and understanding. This is not accurate. 24-bit color is 8 bits per RGB channel, without transparency. 32-bit color is 8 bits per channel including alpha. Which is why HSL is a subset of 24-bit RGB color. HSL can actually only address 3,492,722 different colors (360 × 99 × 98 + 2). Technically, RGB has better fidelity, with multiple RGB values mapping to the same HSL. I was actually in the middle of writing an article on HSL vs. RGB () when I noticed this article, but decided to publish anyhow. Really great article. Thanks correct about rgb being 24-bit and rgba being 32-bit. This is in response to Gary Armstrong’s comment about max colors in hsl, I just did some tests.. Missing a zero. background-clip: texta.k.a. Gradient Text is soon coming to Firefox (already supported on Beta). Wow! This has to be up there with one of my favourite articles. I love the depth you go into each sub-topic; Some enough depth to really understand how and why, and others just enough to know WHY you should be interested in reading more. I didn’t need any breaks while reading, didn’t find myself skipping ahead. Even when you were explaining something I already have a firm grasp of, I was still interested in your overview of it. Now that I look back through other articles written by Sarah I am noticing they are often ones I have bookmarked or committed to memory. Thanks Sarah. Looking forward to your next article with bated breath. WOW! Excellent piece and well written and expertly structured indeed. Your passion for this topic certain comes through. Indeed deserves a bookmark Awesome article!! This should win an award or something :) Fantastic article! One short note. You write: “Back in the old days, chucknorriswas a blood red color (it’s only supported in HTML now as far as I can tell), but that was my favorite.” It’s actually more interesting than you let on. chucknorrisisn’t a named color — the full list is here and was originally based on X11 colors. But then why does chucknorristurn out red? The StackOverflow answer you link to explains it in detail. Browsers are trained to ignore invalid data. Missing digits and invalid hexadecimal digits are treated as 0. So CHUCKNORRISis converted to C00C0000000. The number of hexadecimal colors’ digits has to be a multiple of three; since this has 11 we get an additional padding digit of 0at the end. Browsers then divide the code into three equal chunks for RGB, so we get C00C 0000 0000. And finally, they truncate each chunk to two characters: C0 00 00, aka #C00000, aka dark red. Commenters point out that other random strings also produce colors, including strangely appropriate ones, including grass(green) and crap(brown). You can use this fun tool to type random strings and discover the interpreted color. Anyway, great article! That’s an impressive read. One thing, regarding the currentColorsnippet: The above might not be the best example that shows the power of currentColorbecause in this case currentColoris already the default value for the border-color. I use to dabble with oil paints and would just add black or grey to the sky color for shadows. I could always tell there was something wrong but could not figure it out; now I know. Great tips, thanks! Great article, I go this virus infection warning when I went to the demo mentioned early in the HSL section. I am not sure if it is legit or maybe the demo code confused my virus software, but thought I would mention it…… Infection detected! The requested URL contains malicious code that can damage your computer. If you want to access the URL anyway, turn off the Avast web shield and try it again. Infection type: JS:Redirector-BNI [Trj] The RGB function can also be used with 3 percentage values to represent the proportion of red, green and blue to apply, 0% = 0 (or 00 hex), 100% = 255 (or FF hex). All three values have to be percentages, they can go down to 2 decimal places (12.34%) but do not appear to work with the RGBA function. Why am I just now finding out about console colors?! Love the awesome blend modes demo in the article. Besides that, there’s a useful read on improving your color workflow and creating a color palette for web developers on Smashing: Thanks! — Bo Great job! Thank you. rbga =)
https://css-tricks.com/nerds-guide-color-web/?utm_source=codropscollective
CC-MAIN-2019-47
refinedweb
4,254
62.98
ake Williams2,900 Points Players, dictionary and class challenge. Why does it say "Said-variable" doesn't seem to be a regex object? import re string = '''Love, Kenneth: 20 Chalkley, Andrew: 25 McFarland, Dave: 10 Kesten, Joy: 22 Stewart Pinchback, Pinckney Benton: 18''' players = re.search(r'''(?P<last_name>[+\w ]*), (?P<first_name>[+\w ]*), (?P<score>[\d]{2})''',string, re.M) 2 Answers Andy Hughes8,113 Points Regex just takes practice. The more you do it, the more you understand what characters are used for and therefore where they should go. It's one of the harder concepts to pick up straight away. There is a good cheat sheet on the web that abbreviates every regex character. In your code, you've not allowed for the commas and the colon after the name parts etc. You also missed the re.X and a couple of other letter bits. On the whole you weren't far off at all. :) players = re.search(r''' ^(?P<last_name>[-\w\s]+),\s (?P<first_name>[-\w\s]+):\s (?P<score>[\d]+)$ ''', string, re.X|re.M) Steven Parker215,939 Points The error message might be misleading, perhaps the real issue is that the pattern isn't working on the data. Take a close look at the entries and notice what separates the last names from the scores (Hint: it's not a comma). But you don't need the re.X since you're not spreading your pattern over separate lines like Andy did.
https://teamtreehouse.com/community/players-dictionary-and-class-challenge
CC-MAIN-2022-27
refinedweb
247
75.3
Difference between reshape and transpose operators¶ What does it mean if MXNet gives you an error like the this? Check failed: shape_.Size() == shape.Size() (127872 vs. 25088) NDArray.Reshape: target shape must have the same size as current shape when recording with autograd. This error message tells you that the data being passed to your model or between layers in the model is not in the correct format. Modifying the shape of tensors is a very common operation in Deep Learning. For instance, when using pretrained neural networks it is often necessary to adjust the input data dimensions to correspond to what the network has been trained on, e.g. tensors of shape [batch_size, channels, width, height]. This notebook discusses briefly the difference between the operators Reshape and Transpose. Both allow you to change the shape, however they are not the same and are commonly mistaken. import matplotlib.pyplot as plt import matplotlib.image as mpimg import mxnet as mx from mxnet import gluon import numpy as np img_array = mpimg.imread('') plt.imshow(img_array) plt.axis("off") print (img_array.shape) (157, 210, 3) The color image has the following properties: - width: 210 pixels - height: 157 pixels - colors: 3 (RGB) Now let’s reshape the image in order to exchange width and height dimensions. reshaped = img_array.reshape((210,157,3)) print (reshaped.shape) plt.imshow(reshaped) plt.axis("off") (210,157,3) As we can see the first and second dimensions have changed. However the image can’t be identified as cat any longer. In order to understand what happened, let’s have a look at the image below. While the number of rows and columns changed, the layout of the underlying data did not. The pixel values that have been in one row are still in one row. This means for instance that pixel 10 in the upper right corner ends up in the middle of the image instead of the lower left corner. Consequently contextual information gets lost, because the relative position of pixel values is not the same anymore. As one can imagine a neural network would not be able to classify such an image as cat. Transpose instead changes the layout of the underlying data. transposed = img_array.transpose((1,0,2)) plt.imshow(transposed) plt.axis("off") As we can see width and height changed, by rotating pixel values by 90 degrees. Transpose does the following: As shown in the diagram, the axes have been flipped: pixel values that were in the first row are now in the first column. When to transpose/reshape with MXNet¶ In this chapter we discuss when transpose and reshape is used in MXNet. Channel first for images¶ Images are usually stored in the format height, wight, channel. When working with convolutional layers, MXNet expects the layout to be NCHW (batch, channel, height, width). This is in contrast to Tensorflow, where image tensors are in the form NHWC. MXNet uses NCHW layout because of performance reasons on the GPU. When preprocessing the input images, you may have a function like the following: def transform(data, label): return data.astype(np.float32).transpose((2,0,1))/255.0, np.float32(label) Images may also be stored as 1 dimensional vector for example in byte packed datasets. For instance, instead of [28,28,1] you may have [784,1]. In this situation you need to perform a reshape e.g. ndarray.reshape((1,28,28)) TNC layout for RNN¶ When working with LSTM or GRU layers, the default layout for input and ouput tensors has to be TNC (sequence length, batch size, and feature dimensions). For instance in the following network the input goes into a 1 dimensional convolution layer and whose output goes into a GRU cell. Here the tensors would mismatch, because Conv1D takes data as NCT, but GRU expects it to be NTC. To ensure that the forward pass does not crash, we need to do a tensor transpose. We can do this by defining a HybridLambda.)) network(a) output = network(a) print (output.shape) (1, 999, 128) Advanced reshaping with MXNet ndarrays¶ It is sometimes useful to automatically infer the shape of tensors. Especially when you deal with very deep neural networks, it may not always be clear what the shape of a tensor is after a specific layer. For instance you may want the tensor to be two-dimensional where one dimension is the known batch_size. With mx.nd.array(-1, batch_size) the first dimension will be automatically inferred. Here is a simplified example: batch_size = 100 input_data = mx.random.uniform(shape=(batch_size, 20,100)) reshaped = input_data.reshape(batch_size, -1) print (input_data.shape, reshaped.shape) (100L, 20L, 100L), (100L, 2000L) The reshape function of MXNet’s NDArray API allows even more advanced transformations: For instance:0 copies the dimension from the input to the output shape, -2 copies all/remainder of the input dimensions to the output shape. With -3 reshape uses the product of two consecutive dimensions of the input shape as the output dim. With -4 reshape splits one dimension of the input into two dimensions passed subsequent to -4. Here an example: x = mx.nd.random.uniform(shape=(1, 3, 4, 64, 64)) Assume x with the shape [batch_size, channel, upscale, width, height] is the output of a model for image superresolution. Now we want to apply the upscale on width and height, to increase the 64x64 to an 128x128 image. To do so, we can use advanced reshaping, where we have to split the third dimension (upscale) and multiply it with width and height. We can do x = x.reshape(1, 3, -4, 2, 2, 0, 0) print (x.shape) (1L, 3L, 2L, 2L, 64L, 64L) This splits up the third dimension into [2,2], so (1L, 3L, 4L , 64L, 64L) becomes (1L, 3L, 2L , 2L , 64L, 64L) The other dimensions remain unchanged. In order to multiply the new dimensions with width and height, we can do a transpose and then use reshape with -3. x = x.transpose((0, 1, 4, 2, 5, 3)) print (x.shape) x = x.reshape(0, 0, -3, -3) print (x.shape) (1L, 3L, 64L, 2L, 64L, 2L) (1L, 3L, 128L, 128L) Reshape -3 will calculate the dot product between the current and subsequent column. So (1L, 3L, 64L , 2L , 64L, 2L ) becomes (1L, 3L, 128L , 128L ) Most Common Pitfalls¶ In this section we want to show some of the most common pitfalls that happen when your input data is not correctly shaped. Forward Pass¶ You execute the forward pass and get an error message followed by a very long stacktrace, for instance: *** Error in `python': free(): invalid pointer: 0x00007fde5405a918 *** ======= Backtrace: ========= /lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fdf475927e5] /lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fdf4759b37a] /lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fdf4759f53c] /home/ubuntu/anaconda3/lib/python3.6/site-packages/mxnet/libmxnet.so(MXExecutorReshape+0x1852)[0x7fdecef2c6e2] /home/ubuntu/anaconda3/lib/python3.6/lib-dynload/../../libffi.so.6(ffi_call_unix64+0x4c)[0x7fdf46332ec0] /home/ubuntu/anaconda3/lib/python3.6/lib-dynload/../../libffi.so.6(ffi_call+0x22d)[0x7fdf4633287d] /home/ubuntu/anaconda3/lib/python3.6/lib-dynload/_ctypes.cpython-36m-x86_64-linux-gnu.so(_ctypes_callproc+0x2ce)[0x7fdf46547e2e] /home/ubuntu/anaconda3/lib/python3.6/lib-dynload/_ctypes.cpython-36m-x86_64-linux-gnu.so(+0x12865)[0x7fdf46548865] python(_PyObject_FastCallDict+0x8b)[0x56457eba2d7b] python(+0x19e7ce)[0x56457ec327ce] python(_PyEval_EvalFrameDefault+0x2fa)[0x56457ec54cba] python(+0x197dae)[0x56457ec2bdae] [...] This happens when you your data does not have the shape [batch_size, channel, width, height] e.g. your data may be a one-dimensional vector or when the color channel may be the last dimension instead of the second one. Backward Pass¶ In other cases the forward pass may not fail, but the shape of the network output is not as expected. For instance in our previous RNN example, nothing is preventing us to skip the transpose.)) output = network(a) print (output.shape) (1, 196, 128) Instead of (1, 999, 128) the shape is now (1, 196, 128). But during the training loop, calculating the loss would crash because of shape mismatch between labels and output. You may get an error like the following: mxnet.base.MXNetError: [10:56:29] src/ndarray/ndarray.cc:229: Check failed: shape_.Size() == shape.Size() (127872 vs. 25088) NDArray.Reshape: target shape must have the same size as current shape when recording with autograd. Stack trace returned 6 entries: [bt] (0) 0 libmxnet.so 0x00000001126c0b90 libmxnet.so + 15248 [bt] (1) 1 libmxnet.so 0x00000001126c093f libmxnet.so + 14655 [bt] (2) 2 libmxnet.so 0x0000000113cd236d MXNDListFree + 1407789 [bt] (3) 3 libmxnet.so 0x0000000113b345ca MXNDArrayReshape64 + 970 [bt] (4) 4 libffi.6.dylib 0x000000010b399884 ffi_call_unix64 + 76 [bt] (5) 5 ??? 0x00007fff54cadf50 0x0 + 140734615969616
https://mxnet.incubator.apache.org/tutorials/basic/reshape_transpose.html
CC-MAIN-2019-04
refinedweb
1,444
57.16
Custom WebGL Operation in TensorFlow.js16 Feb 2019 TensorFlow.js is a framework that enables us to run a deep learning model in the web browser easily and efficiently. As you may imagine, tensor manipulation requires a huge amount of computation power. The defacto standard way for that is currently using accelerator such as GPU. GPU provides us with a large amount of parallelism so that we can distribute the tensor calculation in the multiple threads. TensorFlow.js make it possible even in the web browser by using WebGL. WebGL is a standard API to use GPU from web browser mainly for graphical processing. Thanks to WebGL, we can see the rich web contents smoothly. Chrome experiments shows a bunch of fun experience realized by using WebGL. In this article, I’m going to briefly explain how to create a custom operator that is leveraged by WebGL acceleration in TensorFlow.js. This explanation based on the official documentation so please refer “Creating custom WebGL operations” more detail. Table Of Contents - Operators in TensorFlow.js - Using WebGL as GPGPU - Fragment Shader in TensorFlow.js - Configuration of GPGPU Program - Recap Operators in TensorFlow.js First, it’s necessary to know the structure of the kernel in TensorFlow.js. Each operator is implemented as the collection of multiple basic kernels. Kernels are the minimal unit of tensor manipulation. For example, tf.oneHot operator runs oneHot kernel implemented for CPU and WebGL respectively. If WebGL is available, TensorFlow.js chooses the WebGL backend transparently so that the application can be leveraged by WebGL acceleration without rewriting application code. backend provides the interface to access the kernels. It has CPU and WebGL implementations. Once a kernel has WebGL implementation, it can be run on GPU without any modification to the above layer over backend. import * as tf from '@tensorflow/tfjs'; // oneHot operator is executed by the backend implementation. tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print(); Currently, TensorFlow.js supports three types of backend officially. CPU is just a JavaScript runtime running in the web browser so it’s the slowest implementation. TensorFlow.js should fallback to this implementation if any other backend implementation is not available. WebGL will be described later. You can use TensorFlow core implementation via Node.js. TensorFlow provides C API so that it can be bound by any other languages which support C extension. Node.js backend delegates the computation to TensorFlow core. It indicates that we can use any kind of functionality of TensorFlow technically by using Node.js backend. If you are interested in Node.js backend, the detail is described in the repository. So how does WebGL look like? Using WebGL as GPGPU Since WebGL was originally designed for acceleration of graphical processing, it requires some tricky technique to use WebGL for tensor computation. Input tensors are copied as texture to GPU memory. It can be regarded as the simple square and the computation is executed as fragment shader in WebGL pipeline. The following example shows how adding two tensors is done in WebGL. As you can see, tensor A and tensor B are represented as 2x2 images in GPU memory buffer. Hence, each element of these tensors are the pixels of the texture. In general, the texture has RGBA in each element since it’s an image. But it is redundant and memory consuming when it comes to GPGPU case. In the environment supporting WebGL 2.0, gl.R32F texture type is used to avoid allocating memory space for green, blue and alpha pixels. So basically WebGL backend only uses R channel in the tensor computation. Fragment Shader in TensorFlow.js A fragment shader runs in parallel by each pixel, which is accelerated by underlying GPU threads. The function called in parallel in the fragment shader is named main. The main function in TensorFlow.js looks like for example. void main() { // This is the 2 element vector representing the coordination of output position. ivec2 coords = getOutputCoords(); // Get an element in tensor A whose position is exactly to the output. float a = getA(coords[0], coords[1]); float b = getB(coords[0], coords[1]); float result = a + b; setOutput(result); } This function is called in parallel so that the calculation of each tensor is much faster than single thread calculation by CPU. In order to mitigate the difficulty to write a shader program, TensorFlow.js shader compiler provides some utility functions such as getOutputCoords, getA etc. You can get an element from input tensor safely by using these functions. For example, getOutputCoords returns the position of the output element. By using that you can calculate the position of the input element. The previous code shows the example which is adding two tensors in element-wise. This is the core logic of fragment shader. But how can we decide the shape of the input and output? Can we specify the name of the input tensor? Of course, you can by using GPGPUProgram class defined in TensorFlow.js. Configuration of GPGPU Program The interface of GPGPUProgram is defined as follows. interface GPGPUProgram { variableNames: string[]; outputShape: number[]; userCode: string; supportsBroadcasting?: boolean; } variableNames is the name list of input variables. It is case insensitive. If you define variableNames = ['A', 'B'], you can get the element of these tensors by calling getA or getB. GPGPUProgram automatically creates the function referred by this name. You can define the shape of the output tensor by defining outputShape. If the output tensor is a 2x2 tensor, the outputShape will be [2, 2]. userCode is the shader code compiled by TensorFlow.js shader compiler. Let’s say you want to implement a GPGPU program to calculate the squared value of each element. That program can look like this. class SquaredProgram implements GPGPUProgram { variableNames = ['A']; outputShape: number[]; userCode: string; constructor(inputShape: number[]) { // Element-wise operator generates the tensor whose shape is exactly same with the input one. this.outputShape = inputShape; this.userCode = ` void main() { float a = getAAtOutCoords(); float output = a * a; setOutput(output); } `; } } Since we defined variableNames as 'A', we can use getAAtOutCoords to get the element in A in the position same as the output position. If the function is called for the position [0, 2], getAAtOutCoords returns an element in the position [0, 2] in tensor A. The function is very helpful for us to write an error durable shader program. Other than that, there are several utility functions defined by TensorFlow.js side. Of course, you can use the standard GLSL functions such as sin or cos in GPGPUProgram. Please visit the official OpenGL specification for more detail about the available built-in functions. Once you can create your own GPGPUProgram, TensorFlow.js can compile and run the program on behalf of you. For instance, running a program to add two tensors looks like this. Since compileAndRun is defined in the backend implementation, all you need to do is just passing your own program, input, and output. const program = new BinaryOpProgram(binaryop_gpu.ADD, a.shape, b.shape); const output = this.makeOutputArray(program.outputShape, dtype) as Tensor; return this.compileAndRun<Tensor>(program, [a, b], output); The code is available in src/kernels/backend_webgl.ts Recap In this article, I described how to write your own GPGPU program runnable in TensorFlow.js. It’s maybe topic diving into the internal of TensorFlow.js. If you are interested in the usage or application of TensorFlow.js, “Deep Learning in the Browser” is a good resource to learn that kind of thing. That covers the latest technologies to run a deep learning algorithm in modern web browsers. I hope this book would be helpful for you to start the journey to the world of high-performance deep learning in web browsers. Thanks!
https://www.lewuathe.com/custome-webgl-operation-in-tensorflow.js.html
CC-MAIN-2021-49
refinedweb
1,285
50.94
Opened 8 years ago Closed 8 years ago #14668 closed (invalid) apps def unicode->error Description Hi, i am a beginner and tried the steps : but when I write def unicode(self): return self.name there is an error. I use Python27 and Django-1.2.3 in win7 (64bit). thanks juan Change History (2) comment:1 Changed 8 years ago by comment:2 Changed 8 years ago by Note: See TracTickets for help on using tickets. Please post this question to the django-users mailing list or the #django IRC channel on Freenode and provide the complete error traceback so people can help you.
https://code.djangoproject.com/ticket/14668
CC-MAIN-2018-26
refinedweb
105
80.62
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. When I try to save a form it raises an error AttributeError: 'NoneType' object has no attribute 'ids' [Closed] I want to fetch some values from res.partner use browse method.But i got this error why need a help,Here I attached my code sample class res_partner(osv.osv): _inherit='res.partner' _columns={ 'total':fields.char('First Name'), } def create(self, cr, uid, ids, context=None): for i in self.browse(cr,uid,ids): val_name=i.name val_email=i.email val_total=val_name+val_email return super(res_partner, self).create(cr, uid, ids,{'total':'val_total'}, context=context) Need a help... Hello Libu Koshy, Def Create method is used for create a new record into the database. so in create() method you have not specify the id because there is no id for record because there is no record. If there is a ny record you want to update it so you have to use write() methods with perticular id. but Create() doesnt contain any ids. you are about to create a new record . def create(self, cr, uid,vals, context=None): if context is None: context = {} for i in self.browse(cr,uid,ids): for record in i: val_name=record.name val_email=record.email val_total=val_name+val_email vals = {'total':val_total} return super(res_partner, self).create(cr, uid, vals, context=context) Please use abow code. I tried your code but still have same problem...####ERROR File "/opt/openerp/server/openerp/addons/partner_custom/cust_invoice_info.py", line 61, in create val_name=i.name AttributeError: 'NoneType' object has no attribute 'name' check it File "/opt/openerp/server/openerp/addons/partner_custom/cust_invoice_info.py", line 1016, in create for record in i: TypeError: 'NoneType' object is not iterable The create() method works only for a single record. The function signature is: create(cr, user, vals, context=None) EDIT: When either name or mail are not entered on creation, their value will become False (though I thougt they wouldn't be in the value dict). So make sure both fields are filled, using required=True, or change the code to catch the missing field values. For the latter, change your function to: def create(self, cr, uid, values, context=None): name = values.get('name',''); mail = values.get('email',''); total = ''; if name: total += name; if mail: total += ', ' + 'mail; values['total'] = total; return super(res_partner, self).create(cr, uid, values, context=context); Regards. I tried your code but error occurs####### TypeError: cannot concatenate 'str' and 'bool' objects Ofcourse. Sorry. I will fix it immediately! About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/when-i-try-to-save-a-form-it-raises-an-error-attributeerror-nonetype-object-has-no-attribute-ids-61357
CC-MAIN-2017-26
refinedweb
469
59.6
Concept of Map vs List Comprehension in Python Suppose you want to execute a code where you want to define a function in a single line to make your code look simpler in that case you can use List Comprehension or Map() function and you can use it in many parts of your code. The topic like Map vs List comprehension in python is much common and equally important that any python developer will come across. The difference in the implementation of these function and methods and the concept behind is what need to understand and will explain through my views Map() function in Python- Map() function executes each item in an iterates way present in list, tuple, set, etc. The respective items passed as a parameter to the map function present in the list. List Comprehension in Python- - The list comprehension is a replacement of for loop. Example: You define a list – list=[2,3,4,6,7] But you need to define list of longer range like(0,100): list=[] for i in range(0,1000): list.append() This code will give the output elements in the range like 0,1,… 999. But using list comprehension the code will look clear. list=[i for i in range(0,1000)] This list implementation will give the same output, but this methodology is much simpler, and time- saving and easy to debug. The list is an alternate way of using for lambda in the map(), filter() and reduce() because the use of map or filter function needs to write the number of lines while use list comprehension we can implement the same operation within one line. It is considered to be Pythonic, due to its simplicity, code is easy to understand. Syntax of Map() function: variable=map(function-name,iterable) Function-name-The function which is needed to be executed. Iterable-The value in the list or tuple that is automatically iterated calculating along with the function. EXAMPLE: def square(num): #declaring the function return num**2 #return the function output In the above code, you define the function with the respective argument ‘num’ and returning the argument value. list=[2,3,5,7,8] # declaring & defining the list Then you define the list, or you can use a tuple or also a set over here. x=map(square,list) Here we use the map function to map the respective function & list used in the code and with the help of map function. It iterates each element of the defined list to give the output in the form of their square value. Here you print the list and you get the element of the list in their square value. print(x) #print the value of x print print(list(x)) # print x in form of list OUTPUT- [4,9,25,49,64] [4,9,25,49,64] The lambda function is also implemented along with map function to generate the new list as output. num_list = [5, 7, 6,8] final_list = list(map(lambda x: x**2 , num_list) Here you can see I have to define num_list and with the help of map and lambda function, I tried to map the element to give their square value as output as a new list. But this approach makes the code look complicated. print(final_list) OUTPUT- [25,49,36,64] This is the following output of the above code. Syntax of List comprehension: list=[expression for element in iterable] Expression-variable use for each element to iterate. Element-items on the list. EXAMPLE- list = [2, 3, 4, 6, 7,8] Here you define the respective list. x = [i * 3 for i in list ] Here in the above code a variable “i” is used to iterate the items in the list that get store in the variable “x”. print(x) OUTPUT- [8,27,64,216,343,512] The print function gives the output of x which the cube root value of elements in the defined list. The list comprehension method is easier to implement, saves time, a single line of code can make the code look more clear and easy to debug. Pros and cons of list comprehension: - List comprehension method is fast- The list comprehension method is easier to implement due to the single line of its expression. Its time saving mostly when you are engaged to debug a big code that time you can implement list comprehension method to make the code look consistent, rather than implementing map() or for loop() where you have to define function then iterate it by mapping elements of the list with it or using loop where you have created an empty list and append element accordingly as it iterates to the condition given. - It is a concise way to generate a list along with the implement the loop and respective operation rather than creating a list then performing loop or using functions. - It looks easier to understand than map function., due to its simplicity in its definition. - It is a more approachable way to expresses the list to define and it is content at the same time rather than creating an empty list and putting element at the end. Pros and Cons of Map function: - It is slower than the list comprehension method. Map faster in terms of calling the function that is already defined in the code. - The map function is more time consuming to implement like writing several lines makes code more complicated to understand whereas using list comprehension you can implement it just one list just time-saving and easy to debug. Also read: List and dictionary comprehension in python
https://www.codespeedy.com/concept-of-map-vs-list-comprehension-in-python/
CC-MAIN-2020-45
refinedweb
937
64.95
Migrate from GTK+ to Qt Contents - 1 Introduction - 2 GObject vs QObject - 3 GtkWidget vs QWidget - 4 Tree/Model/View architecture of Qt - 5 Special notes for using Qt with glib/GObject and gio - 6 Using CMake to Build Your Code - 7 Translation (i18n) - 8 ABI Issues For C++ Libraries - 9 Appendix: List of equivalent GTK+ and Qt functionality - 9.1 Development Tools - 9.2 Windows - 9.3 Display Widgets - 9.4 Buttons and Toggles - 9.5 Numeric/Text Data Entry - 9.6 Multiline Text Editor - 9.7 Tree, List and Icon Grid Widgets (Tree Model/View architecture) - 9.8 Menus, Combo Box, Toolbar - 9.9 Selectors (Color/File/Font) - 9.10 Layout Containers - 9.11 Scrolling - 9.12 Printing - 9.13 Miscellaneous - 9.14 Abstract Base Classes - 9.15 Cross-process Embedding - 9.16 Recently Used Documents - 9.17 Choosing from installed applications - 9.18 Interface builder - 9.19 Application support - 9.20 Deprecated Introduction Qt is a nice platform for GUI application development. More and more people are using Qt. One of the famous Linux distros, Ubuntu, is also moving from Gnome/GTK+ to Qt. Normally, people start learning Qt from reading the Qt tutorial/books and the "hello world" example. For those who already know GTK+, learning Qt is much easier since most of the GTK+ concepts still applies. Only some "translation" is needed. This document focuses on translating your existing GTK+ knowledge and experience to Qt. So you can start to develop with Qt "immediately". - If you don't know what's GTK+ or Qt, this doc is not for you. Go to find a Qt tutorial and read it. - If you're using GTK+ and want to use Qt instead, this is definitely for you - If you plan to use QML, this is not for you. We focus on desktop development with Qt Widgets. A very efficient shortcut for a GTK+ developers to migrate to Qt is: - Read a Qt tutorial (hello world) [1] - Read this guide - Start coding immediately (Create your project with KDevelop or QtCreator can make your life much easier. Personally I highly recommend KDevelop) - If you encounter any problem, use Qt assitant to look it up in Qt API doc, or ask questions in the KDE/Qt community. At the end of this document we provide a table listing the Qt equivalence of some common Gtk+ classes. GObject vs QObject In Gtk+, nearly everything is a GObject. In Qt, almost all major classes are derived from QObject. They provides very similar functionality but also differs in many ways. GtkWidget vs QWidget Tree/Model/View architecture of Qt In Qt, it also has model/view architecture, just like GTK+ has GtkTreeModel and GtkTreeView. Their designs, however, differ in some ways. In GTK+, To create a list-like view, you need to do this: - Create a GtkListStore as the model providing data source - Create a GtkTreeView for display the model - Add several GtkTreeViewColumn objects to the GtkTreeView to add columns - Set column attributes to map columns in the model (list store) to the visible columns in the view. - Pack several GtkCellRendererPixbuf and GtkCellRendererText renderers into GtkTreeViewColumn to paint the content of that column - Set the model to the view In Qt, you have two choices for your model - QStandardItemModel: a ready-to-use generic model class which has more feature than GtkListStore and GtkTreeStore. This should work in most of the cases. - QAbstractItemModel: a base class for deriving your own model class if QStandardItemModel is not enough. more complicated, roughly equals to implementing your own GtkTreeModel interface with GObject. There are several places where Qt is quite different: - Columns in the view are created by adding GtkTreeViewColumn objects while in Qt the column information (title, size, ...) is "provided by the model", not the view. However, if you need to change the column header, it's managed by QHeaderView which can be retrieved by calling QTreeView::header(). - Qt does not use cell renderer layout. Every cell can have an optional icon and text, and even other data associated with it. Qt calls different data stored in a cell "roles". Icons are decoration roles, and text for display in the cell is called display role. - In Gtk+, to refer to a row, you have to use GtkTreePath and GtkTreeIter. In Qt what you only need is QModelIndex, which provides functionality of GtkTreePath + GtkTreeIter. - In Gtk+ every "row" have a GtkTreePath and GtkTreeIter. Different cells in a row are referenced by using different column indicis or IDs. In Qt, every single cell can have their own QModelIndex. - If you need to draw custom content in a cell, in Gtk+ you can create a custom GtkCellRenderer. With Qt, derive your own QStyledItemDelegate, which is essentially a Qt cell renderer. - Gtk+ provides various kinds of cell renderers, Qt does not. You have to derive your custom item delegates for this. This is not difficult and a Google search usually gives you many examples for how to do it. - Gtk+ cell renderers provides rich text rendering (markup text), but Qt does not provide it. You can emulate the same feature with a custom delegate. Here are some good examples from Razor-Qt project and Stack overflow Here are some good Qt model/view examples: At the end of the article, we have a table summarizing equivalent Gtk+ and Qt classes for model/view architecture. Jump to the table Special notes for using Qt with glib/GObject and gio Forget the political issues. Qt and Gtk/Gnome are not enemy and there are many really nice non-GUI libraries from the Gnome/Gtk world. Qt now has glib mainloop integration. So using glib-based libraries is possible in Qt programs. (The Qt library must be compiled with glib support turned on, thogh) There are some issue developers need to pay attention to. Initialize GObject type system You need to call g_type_init() before using any GObject-based stuff. Normally gtk_init() calls g_type_init() for us if you're using Gtk. With Qt, however, you need to initialize the GObject type system manually. Disable the Qt keywords To make programming easier, Qt added some "Qt-specific" reserved words to C++, such as the notorious "signals", "slots", "emit", and "foreach". They received much criticism on not using standard C++ syntax here. Non-standard, however, is not the real issue. The problem is, these words are used in other C++ libraries for class, methods, or variable names. The most famous one is boost::signal. These Qt keywords create significant name clashes. Glib/gio also uses these Qt keywords for variable names in their header files. So it creates a big headache. Fortunately, in Qt 4 this improved. Instead of new keywords, you can replace all of the "keywords" with macros. Use Qt macros Q_SIGNALS (or Q_SIGNAL), Q_SLOTS (or Q_SLOT), Q_EMIT, and Q_FOREACH to replace the old "keywords" and everything will compile. You also need to define "QT_NO_KEYWORDS" with compiler flags -DQT_NO_KEYWORDS to make it work. String encoding issues - While glib uses UTF-8 to encode all strings, Qt uses UTF-16 internally. A C-style string, if not specified, is treated as a latin1 string. To convert from UTF-8 to UTF-16, calling QString::fromUtf8() explicitly is needed. If you don't do this, UTF-8 strings will be treated as latin1 by default and the bug can be hard to find. - To avoid the error, define QT_NO_CAST_FROM_ASCII flag to disable automatic conversion from C string to UTF-16. Make C Header Files C++ compatible - Avoid using C++ reserved words as variable or function names in your C code, especially in the header files. The most common example: Replace "class" with "klass" in your C code because class is a reserved word in C++. Don't use "new" as your function or variable name since its a C++ operator. - If you use glib, add G_BEGIN_DECLS and G_END_DECLS in your C language *.h files like this: #include <glib.h> G_BEGIN_DECLS // Your function declaration here // ... G_END_DECLS Please refer to glib API doc for the explanation of these two macros. They're translated to something like this: #ifdef __cplusplus extern "C" { #endif // Your function declaration here //... #ifdef __cplusplus } #endif This prevent C++ compilers from doing name mangling. - If you're not using glib, do the above ifdef and extern "C" manually Known bugs or limitations of the Qt glib support - Qt QTBUG-32859: Calling QObject::deleteLater() inside a glib signal, timeout, or idle handlers has no effect. To workardound this bug, use QTimer::singleShot(0, object, SLOT(deleteLater())); Using CMake to Build Your Code While using Autotools to build Qt code is possible, I won't recommend doing that. The officially suggested way to build Qt code is to use qmake bundled with Qt and *.pro project file. This approach, however, is not suitable for more complicated real world applications. Many huge projects developed with Qt, like KDE, uses CMake instead. CMake Basics TODO Using pkg-config in CMake TODO Qt support in CMake TODO Some useful macros: - qt4_add_resources to add embedded resources to your app, - qt4_wrap_ui to add a widget form, - qt4_create_translation for translation, - qt4_add_dbus_adaptor & qt4_add_dbus_interface to generate D-Bus-related code. Add compiler flags - The -DQT_NO_KEYWORDS flag: turn off Qt specific keywords - The -fpermissive flag: If you're using some C libraries in your Qt code, you may encounter some type-casting related errors. Because C++ is more strict on type safety, some code allowed in C is not allowed in C++. You should fix the code if possible. Otherwise, add -fpermissive flag to omit the errors to make it compile. Add linker flags TODO Build binary programs TODO Build libraries TODO Build tarballs TODO Translation (i18n) GNU gettext vs QTranslator TODO Generate *.ts file from the source code TODO Integrate with CMake Load the translation in Qt code TODO Use GNU gettext in Qt TODO ABI Issues For C++ Libraries What's ABI? ABI = application binary interface. It's extremely important for you if you're developing a library. Wikipedia has introduction for it. [3] How to prevent breaking ABI compatibility Due to the design and language features of C++, ABI (application binary interface) can break much more easily than in C if developers do not pay special attention to it. KDE teams provide a very comprehensive guide about how to prevent C++ ABI breakage. Please read the nice article here [4]. What if I really need to break the ABI Then make sure you bump the libtool version number. See this doc explaining how to set the version info correctly: Appendix: List of equivalent GTK+ and Qt functionality Development Tools The following list of Gtk classes is taken from gtk+ API doc here: Windows Display Widgets Buttons and Toggles Numeric/Text Data Entry Multiline Text Editor Tree, List and Icon Grid Widgets (Tree Model/View architecture) Menus, Combo Box, Toolbar Selectors (Color/File/Font) Layout Containers In Gtk+, widget layout are largely done with boxes. In Qt, however, there are no box containers. Instead, they used QLayout objects to manage the layout of widgets. QLayout and its derivatives are not containers nor widgets. They're just "managers" of the layout of child widgets. The child widgets belongs to their parent container widgets, not belongs to the layout managers. This is totally different from Gtk+.
https://wiki.lxde.org/en/Migrate_from_GTK%2B_to_Qt
CC-MAIN-2017-34
refinedweb
1,881
57.06
Copyright © 2011. A conformance section has been added. The example service description is now marked as informative, includes use of entailment properties, and is shown in both RDF/XML and Turtle. The sd:defaultSupportedEntailmentProfile property and sd:BasicFederatedQuery feature were added. The sd:url property was renamed to sd:endpoint, and the phrase "service URL" was changed to "service endpoint". The modeling of properties and classes (including the use of rdf:type, rdfs:domain, rdfs:range, and rdfs:subClassOf) was improved. Terminology in this document was aligned and linked with the SPARQL 1.1 Protocol, SPARQL 1.1 Update, SPARQL 1.1 Query, SPARQL 1.1 Graph Store HTTP Protocol, SPARQL 1.1 Entailment Regimes, RDFa, and Architecture of the World Wide Web documents. 2 Accessing a Service Description 3 Service Description Vocabulary 3.1 SPARQL Service Description NamespaceDescription 3.2.13 sd:availableGraphDescriptions. The SPARQL service description namespace IRI is: The prefix used in this document for this namespace is sd. The SPARQL endpoint of an sd:Service that implements the SPARQL Protocol service [SPROT]. The object of the sd:endpoint property is a URI reference. Relates, or BIND clause. Relates an instance of sd:Service to an aggregate that may be used in a SPARQL HAVING clause or SELECT expression. Relates an instance of sd:Service to a resource representing an implemented extension to the SPARQL Query or Update language. Relates an instance of sd:Service to a SPARQL language subset (e.g. Query and Update) that it implements. Relates an instance of sd:Service to a resource representing an implemented feature of the SPARQL Query or Update language that is accessed by using the named property. Relates an instance of sd:Service to a description of the default dataset available when no explicit dataset is specified in the query or protocol request. Relates an instance of sd:Service to a description of the graphs that may be used in the construction of a dataset either via the SPARQL Protocol or with FROM/FROM NAMED clauses in the query. an HTTP PUT as described by SPARQL 1.1 Graph Store HTTP Protocol [SPARQLHTTP]). URIs for commonly used serialization formats are defined by Unique URIs for File Formats. For formats that do not have an existing URI, the and properties defined in that document SHOULD be used to describe the format., or BIND clause. An instance of sd:Aggregate represents an aggregate that may be used in a SPARQL aggregate query HAVING clause or SELECT expression.. In addition to the instances listed here, the following documents list instances that may be used with the properties listed below: clauses and use the resulting RDF in the dataset during query evaluation. sd:UnionDefaultGraph, when used as the object of the sd:feature property, indicates that the default graph of the default dataset used during query evaluation is comprised of the union of all the named graphs in the default dataset. sd:RequiresDataset, when used as the object of the sd:feature property, indicates that the SPARQL service requires an explicit dataset declaration (based on either FROM/FROM NAMED clauses in the query or the appropriate SPARQL Protocol parameters). sd:EmptyGraphs, when used as the object of the sd:feature property, indicates that the underlying graph store supports empty graphs. A graph store that supports empty graphs SHOULD Federation Extensions [SPARQLFED].Description> Description> <Description [.2 2013-01-28 01:44:48 sandro snapshot Revision 1.1 2011/05/05 22:57:15 apollere2 moved from gen.html to Overview.html Revision 1.4 2011/05/05 20:16:00 gwilliam s/h4/h3/ Revision 1.3 2011/05/05 19:29:58 gwilliam Changed case of "Status of This Document". Revision 1.2 2011/05/05 19:26:46 gwilliam Added status boilerplate. Revision 1.1 2011/05/05 19:16:55 gwilliam First HTML version of SD for LC 2011-05-12.
http://www.w3.org/2009/sparql/docs/pub/20110512/WD-sparql11-service-description-20110512/
CC-MAIN-2016-26
refinedweb
651
58.18
I'm having some trouble trying to make a function using the prototype.js library. I want the function to return a value based on an Ajax.Request object. function isLoggedIn(){ var isLogged; url = "../script/isLoggedIn.cfm"; xhr = new Ajax.Request(url,{method:'get', onComplete:function(){return ([I]text from the isLoggedIn.cfm page[/I])}}); if ([I]text from page is true[/I]){return true;}else{return false;} } The problem I'm having is getting at the return value from the onComplete function while I'm outside of the function. I'm sure it's something stupid that I'm missing, but I can't find it. The problem is that you are using an anonymous function for 'onComplete:' and this ends up limiting the scope of the return text to that function. Try using something like 'onComplete: myOnCompleteFunction()' and then defining the function later: function myOnCompleteFunction(text) { // Do whatever you want here. if (text from page is true){return true;}else{return false;} return boolean; } If I wanted to get at the value from the myOnCompleteFunction while I was in the parent function (isLoggedIn()), how would I do that? Well your isLoggedIn() function is starting an Ajax call, but that doesn't mean it will get to complete it. Essentially I have a function that starts the call, and then separate functions that handle the possible return values. For instance: function bounce() { $e('enter').disabled=true; var h = $e('horiz').value; var v = $e('vert').value; var g = $e('grav').value; var e = $e('ela').value; ptext("display","<img src=\\"images/loading.gif\\" alt=\\"loading..\\" />"); $.ajax({type: "POST", url: "php/bounce.php", data: "v=" + v + "&h=" + h + "&g=" + g + "&e=" + e, success: printHTML, error: handleError}); return; } function handleError (obj, input) { ptext("display","Experiencing a server error"); return; } function printHTML(input) { $e('display').innerHTML = '<img src="' + input + '" alt="' + input + '" class="animated"/>'; $e('enter').disabled = false; return; } // Hide a given element function hide(el) { $e(el).style.display = "none"; return; } // Show a given element function show(el) { $e(el).style.display = "block"; return; } // Update the innerHTML for an element function ptext(el, t) { $e(el).innerHTML = t; return; } function $e(el) { return document.getElementById(el); } Here I'm using the jQuery JS library to handle the Ajax for me so I don't have to learn what the various differences between the browsers are. So the $.ajax function handles the request back to the server, and you can see that two of the arguments for it are the name of a return function, and an error function (in case of a timeout or something similar). Basically the script doesn't just wait there for a reply from the server, it keeps moving along, so typically, an Ajax request should be the last line of a dummy function. Then once you have a return value from the server, you handle the return value in a separate function. What this means for you is that you can't access the return value in your isLoggedIn function, you need to handle that part of the logic (handling what happens with the user) in a different function. Btw, this script is part of a script I wrote which takes some user entered values, and creates an animated Gif out of them using Php, and uses Ajax to send the information about the Gif to the server, then the server sends back the name of the image file it's created, wrapped in an image HTML element. Thanks for all your help. I did end up figuring out a way to get at that responseText though. The reason I couldn't get it before was that the Ajax.Request call was going asynchronously. Once I switched that over, I was able to get at the variable after the Request call. Here's the code: function isLoggedIn(){ url = "../script/isLoggedIn.cfm"; xhr = new Ajax.Request(url,{[B]asynchronous:false[/B], method:'get', onComplete:null}); if(trim(xhr.transport.responseText)== 'true'){ return true; } else { return false; } } Thanks again for your help though
http://community.sitepoint.com/t/gettting-return-values-from-ajax-request/2974
CC-MAIN-2015-40
refinedweb
674
65.22
#include <stdint.h> #include <rte_compat.h> Go to the source code of this file. RTE FIB6 library. FIB (Forwarding information base) implementation for IPv6 Longest Prefix Match Definition in file rte_fib6.h. Maximum depth value possible for IPv6 FIB. Definition at line 32 of file rte_fib6.h. Modify FIB function Definition at line 44 of file rte_fib6.h. FIB bulk lookup function Definition at line 48 of file rte_fib6.h. Type of FIB struct Definition at line 38 of file rte_fib6.h. Size of nexthop (1 << nh_sz) bits for TRIE based FIB Definition at line 58 of file rte_fib6.h. Type of lookup function implementation Definition at line 65 of file rte_fib6.h. Create FIB Find an existing FIB object and return a pointer to it. Free an FIB object. Add a route to the FIB. Delete a rule from the FIB. Lookup multiple IP addresses in the FIB. Get pointer to the dataplane specific struct Get pointer to the RIB6 Set lookup function based on type
https://doc.dpdk.org/api-20.11/rte__fib6_8h.html
CC-MAIN-2021-39
refinedweb
167
70.5
KnockoutJS provides the plumbing to create very powerful web applications, but leaves most of the logic up to the developer. That's great, and I don't think it should be any different, but developers need to look out for common use case scenarios where there is often the potential to be a lot of duplicated boiler-plate code. One such case (I have found) is creating paged datasets. The Simple Case Say I just have an array of simple JS/JSON objects, all I want to do is build a ko.computed computed observable that simply pulls out the slice of the array that represents the current "page". Simple. Someone reasonably adept at knockout can knock that out pretty quickly. Starting with our viewmodel (which in my examples will follow a constructor pattern, however this does not have to be the case): var ExampleViewModel = function(data){ // ... // other viewmodel data we don't care about // ... // the array of items that I want to page this.items = ko.observableArray(data); }; Cool. Okay, well I have my viewmodel here... I might as well start slamming some observables related to my pager on there! var ExampleViewModel = function(data){ // stuff that matters // --------------------------------------------- this.items = ko.observableArray(data); // pager related stuff // --------------------------------------------- this.currentPage = ko.observable(1); this.perPage = 10; this.pagedItems = ko.computed(function(){ var pg = this.currentPage(), start = this.perPage * (pg-1), end = start + this.perPage; return this.items().slice(start,end); }, this); this.nextPage = function(){ if(this.nextPageEnabled()) this.currentPage(this.currentPage()+1); }; this.nextPageEnabled = ko.computed(function(){ return this.items().length > this.perPage * this.currentPage(); },this); this.previousPage = function(){ if(this.previousPageEnabled()) this.currentPage(this.currentPage()-1); }; this.previousPageEnabled = ko.computed(function(){ return this.currentPage() > 1; },this); }; And there ya have it. A pager in Knockout.JS. Wiring it up to the view is somewhat trivial: <ul class="pager"> <li data- <a href="#" data-Previous</a> </li> <li data- <a href="#" data-Next</a> </li> </ul> This is a relatively simple result to accomplish with knockout... but if you feel like this is a little bit lacking, you are not alone. The problem is there is just a bunch of logic up there that just shouldn't matter to us. This is not really business logic... it is a common UI implementation that has nothing to do with the core of our application - so I don't want to look at it! More than that, I have just added a bunch of properties to my viewmodel which might end up getting serialized to JSON and sent to my server, which I don't want. Even more, this is about as simple as your situation will possibly be. Chances are, you are probably wanting to do something more complicated, like pull data from the server asynchronously via ajax... In this case, these methods are going to get more and more complicated, making our viewModel even more messy! Getting DRY Nevermind loading data via AJAX for a moment. Let's just get this thing out of our viewmodel. In order to do this, we are going to extend the prototype of ko.observableArray. This feels appropriate, since we are typically going to want to page an array, and our viewModel might have several arrays, each of which need to be paged. This has a slight limitation in that it prevents us from creating a paged array around a plain old JS array (ie, only works on a ko.observableArray), but I am okay with that right now. So, we rework our code a bit and come up with this: ko.observableArray.fn.paged = function(perPage){ var items = this; items.current = ko.observable(1); items.perPage = perPage; items.pagedItems = ko.computed(function(){ var pg = this.current(), start = this.perPage * (pg-1), end = start + this.perPage; return this().slice(start,end); }, items); items.next = function(){ if(this.next.enabled()) this.current(this.current()+1); }.bind(this); items.next.enabled = ko.computed(function(){ return this().length > this.perPage * this.current(); },items); items.prev = function(){ if(this.prev.enabled()) this.current(this.current()-1); }.bind(this); items.prev.enabled = ko.computed(function(){ return this.current() > 1; },items); return items; }; All of the code here is essentially the same as before. The main difference here is that we are now hanging all of our pager methods off of the actual ko.observableArray instance, instead of our viewModel directly. Remember, this is possible because an instance of ko.observableArray is actually just a function. And functions can have properties just like any other object in JavaScript! This results in the functionally equivalent, but a much cleaner viewmodel: var ExampleViewModel = function(){ this.items = ko.observableArray().paged(10); }; And the modified HTML: <ul class="pager"> <li data- <a href="#" data-Previous</a> </li> <li data- <a href="#" data-Next</a> </li> </ul> But of course, we do gain some other benefit of the added abstraction: the benefit of being DRY. For example, we could have multiple paged arrays in the same View Model if we wanted without sharing any state! var Example = function(){ this.apples = ko.observableArray().paged(10); this.oranges = ko.observableArray().paged(20); }; Handling The More Common Case: Lazy-Loaded paged data-sets via AJAX Paged lists are nothing new. Turns out there is lots of data on the internet, and it often times is not economical or practical to display it to the user all at once. The example above helps us stay DRY, but only helps us in the cases where we have all of the data already on the client. Although this is helpful some of the time, a much more practical scenario is when we have a (potentially) large dataset that is being stored on the server (likely in a database), and we want to display results to the user querying it, but we obviously don't want the client to have to download all of the data at once! So although the code above is a fun little exercise, it is hard to really say that it is useful. I like useful things, so let's take another stab at it. Being useful: handle any case So we don't want to just rewrite the above code to work asynchronously, but forget the static case altogether! Let's provide an API that is flexible enough to let the user (read: developer) decided how he/she wants the pager to behave. To demonstrate this, I am merely going to provide some of the key snippets. The code here is getting a bit lengthier and the point is lost with boiler-plate logic. When loading data asynchronously, you want to minimize trips to the server, so we must store whether or not we have retrieved a certain page or not. To do this, we create a local array called loaded which is an array of booleans. Thus, to check if the 5th page has been loaded, we simply see if loaded[5] === true. var loaded = [true]; // set [0] to true just because. var goToPage = function(pg){ if(loaded[pg]){ //data is already loaded. change page asynchronously to simulate a *really fast* ajax call isLoading(true); setTimeout(function(){ current(pg); isLoading(false); },0); } else { // request data from server $.get('/path/to/server?pg=' + pg, function(res){ onPageReceived(pg,res); // handle server response isLoading(false); }); } }; var onPageReceived = function(pg,data){ // append data to items array (in correct spot) var start = cfg.pageSize*(pg-1); data.unshift(start,0); Array.prototype.splice.apply(items(),data); items.notifySubscribers(); loaded[pg] = true; // indicate this page has been loaded current(pg); // change current page }; The devil might be in the details, but this demonstrates the main mechanics of it all. The key things to note here are: .pushis not used to add items to the array. This is because .pushadds elements to the end of an array. Since we are lazy loading, we may end up loading page 3 before we have page 2. In this scenario we need to add elements to the correct index on the array. It's kind of messed up that JavaScript arrays let you do this... but that's another discussion in and of itself. even when we have the data, setTimeoutis used. This is a rather important principle when writing code for others to use: Don't write methods that are asynchronous or synchronous only part of the time. By using setTimeoutwe are effectively emulating an AJAX call that is just really fast. This allows the user to write code against the .goToPage()method in a consistent way. the items.notifySubscribers()call is required here. This is because we are using the array .splicemethod on the underlying array in order to add data to it. Because we are unwrapping the observable to do this (and never calling the setter method, or any of the special ko.observableArraymethods), knockout doesn't know that the array has changed. To let knockout know that the data has changed, we call the .notifySubscribers()method. Although this works, you may have noticed it only works for asynchronously-loaded datasets, and doesn't allow for much configuration. Building configurable API's adds a considerable amount of code, and thus I have removed it above. I did, however, take the time to build a first-version of a knockout plugin which I have put on github. It allows for the flexibility that I was calling for above, and used the above code as a starting point. For this plugin, one calls it in an almost identical fashion to the examples above. The API is as follows: What is returned? When calling .paged on a ko.observableArray instance, the result is the same observable array, augmented with several different paging-related properties which are added to the observableArray itself (not the underlying array). The following properties are added: current(Type: ko.observable(Number)) An observable of the current page number (starting from 1) pagedItems(Type: ko.observableArray) An observable array containing only the items of the current page. (ie, the "paged items") pageSize(Type: Number) The integer value of the page size (default is 10) isLoading(Type: ko.observable(Boolean)) An observable indicating whether or not data is currently being retrieved from the server (only ever true for Ajaxified datasets) next(method) If enabled, loads the next page. previous(method) If enabled, loads the previous page. goToPage(method( Number)) Goes to the designated page. (Indexed starting at 1) The paged observable array can be created by using one of the three different method signatures: Page locally available data easily // data is already loaded on the client .paged(Number pageSize) => ko.observableArray (self) pageSize: A Number(Integer expected) indicating the desired page size for the observable array - returns : The ko.observableArrayinstance that .pagedwas called on, augmented with the paging methods Example: var ExampleViewModel = function(){ this.apples = ko.observableArray().paged(10); //... data can be loaded at any time this.apples.push({type: 'Jazz', state: 'Ripe'}); }; Page server-side dataset with Url Template // data is to be loaded via ajax, with a regular URL structure .paged(Number pageSize, String templateUrl) => ko.observableArray (self) pageSize: A Number(Integer expected) indicating the desired page size for the observable array templateUrl: A Stringrepresenting the URL template to be used to grab the data from the server. - returns : The ko.observableArrayinstance that .pagedwas called on, augmented with the paging methods Example: var Example = function(){ // apples is empty. will automatically load first page, and any other page which is requested // by using the provided url template this.apples = ko.observableArray().paged(10,'/url/to/get/apples?page={page}&pageSize={pageSize}'); }; Configure it to do what you need with options hash .paged(Object config) => ko.observableArray (self) In this case we simply pass in an object hash with whatever options we want to set. The following options are made available: You can see it in action in this fiddle: Unfortunately, the source had to be hacked a little bit in order to work with jsFiddle's JSON echo API, but it demonstrates the asynchronous nature of the pager that can be achieved. If I get a bit further with this project, I will provide some more complete examples and update this article. Future Development As this is a plugin that I believe I myself will use, I would like to keep improving on it. I am open to suggestions on the best way to do that. If you have opinions on how this API should change or be improved, please share! (or submit a pull request). I have the source available on GitHub: lelandrichardson/knockout-paged My major plans for it right now (other than fixing bugs and making it more robust) is to add support for RESTful endpoints. My thoughts is this could go something like this: var Example = function(){ // instead of providing a url template, you would simply provide the resource name // and it would do the rest of the work this.apples = ko.observableArray().paged({ pageSize: 10, resource: '/apple' }); }; RESTful API's have an entirely different way of handling paged datasets, which is by sending back one or more "next", "prev", "first", and "last" URLs along with the response. I intend on adding handling of this by default soon, and I think this could result in a very clean API. I am certainly open to suggestions here as well. Very good article! Do you code also in asp.net MVC 4? There is a cool package called PagedList I use it in my MVC project(it's also used in NerdDinner) and I generate a JsonResult, the json contains metaData such as nr of items, pages etc. maybe it could be interesting for your plugin. UPDATE: I tried your plugin in my environment. I had to adapt the generated JSON (it looked like this: [{ "success": true, "stories": stories, metaData: {"PageCount":2, "TotalItemCount":21, "PageNumber":2, "PageSize":20, "HasPreviousPage":true, "HasNextPage":false, "IsFirstPage":false, "IsLastPage":true, "FirstItemOnPage":21, "LastItemOnPage":21} }] I had to remove success and metaData and just provide the stories in the result... please also update your documentation, the url to call is wrong: /MyWorld/Stories?page={page} ... {page} is not recognized. Your plugin uses {pg}. UPDATE 2: fix for the next.enabled = ko.computed(function() Thanks again and cheers Paolo Paging correctly is always a beast of a task. It's cool how you encapsulated the paging functionality into the array itself, but I wonder if you have to worry about KnockoutJS possibly adding a keyword that would conflict with yours. I probably would create my own PagedViewModel and then explicitly have it declared and be reusable that way. Cool post, I can see why you wrote it too since this site is heavy on KnockoutJs :). @Khalid, You definitely always have to worry about keywords/namespacing to prevent klobbering something else. Using the code here, it is quite easy to modify it to either a.) use a different keyword off of ko.observableArray.fn, b.) use as a function which is namespaced differently. For example, b) would look like: I am not terribly concerned about this, however. Ryan Neimeyer has recommended this approach as a method of "extending" observables in precisely this fashion, although "paged" is a fairly generic word... Sure, just name drop :) But seriously, I do think your way is really nice, I'll have to remember it next time I do some KnockoutJs work. Paging is such a common scenario that I'm surprised the structure isn't built in to frameworks like KnockoutJs or AngularJs. I like how Angular has resources that let you abstract calls to your server-side resource, but like you mentioned, you need a RESTful resource. Sadly most .NET devs don't follow resource centric design. I've seen a lot of controller actions in the style of "SendEmailToUser()" and it makes me cry.
http://tech.pro/tutorial/1235/handling-paged-datasets-in-knockoutjs
CC-MAIN-2013-48
refinedweb
2,634
57.06
Dear Type Technicians, I have posted a little piece of software in your favorite script language that you can use to hack your OpenType features into your fonts. Dancing Shoes does not invent the features for you. But it takes care that they are put out in the correct order and syntax, and works around some possible bugs with FontLab’s built-in FDK compiler that should work according to the manual. For instance some script and language tags must not be preceded by others, although that should not be important according to the manual. Dancing Shoes is especially useful if you generate feature code with multiple scripts, languages and lookupflags within one feature. But it can also ease the recurring task of applying features to all your fonts. Because you’ll most likely always use the same naming scheme for your glyphs (.sc for SmallCaps etc), you can keep these in a separate, hard-coded file, and re-apply them with one click or from within another script. You initialize the DancingShoes object: from dancingshoes import DancingShoes shoes = DancingShoes(glyphs, features) glyphs is a list of your font’s glyph names and features your hard-coded and ordered list of feature names. Then you can add substitutions like this: shoes.AddSubstitution('liga', 'f i', 'fi') or, more complicated: shoes.AddSubstitution('rlig', 'afii57457 afii57455', 'uniFC61', 'arab', '', 'RightToLeft,IgnoreBaseGlyphs', 'ARABIC LIGATURE SHADDA WITH DAMMA ISOLATED FORM') You can then print the feature code like this: print shoes.GetFDKCode() or, in case of a FontLab font object, use the helper funtion (font being your FontLab’s font object: from dancingshoes.helpers import AssignFeatureCodeToFontLabFont AssignFeatureCodeToFontLabFont(font, shoes) For now, only substitutions and positioning lookups (Type 1 and 2) are supported. Which should be enough for most use scenarios. Other lookup types (like mark positioning) will be added later. You’ll find it here, along with documentation: It’s free. But as always: Should you use it for production of your professional fonts, a donation is highly appreciated. I'm looking forward to playing with this, thanks. Yanone, by "manual", do you mean the FontLab Studio manual or the Adobe FDK for OpenType documentation? ( ). We certainly recommend using both documents for reference. However, one needs to remember that FontLab Studio 5 uses the AFDKO library version 1.6, while Adobe now ships AFDKO library version 2.5. The new version of the library will be used in Fontographer 5 and in FontLab Studio 6. Cheers, Adam Hi Adam, I meant the AFDKO Feature File Syntax. I'm aware that the FDK compiler in FLS5 is much older, which is why Dancing Shoes tries to provide work-arounds to some of its quirks. Adam Will FontLab Studio 6 be up-datable if and when Adobe bring out an update to their AFDKO after the release of FontLab Studio 6? Malcolm yanone: ‘But it can also ease the recurring task of applying features to all your fonts.’ Which is a sensible thing to do. As you probably know, in the FM tools, including DTL OTMaster, listed OT Layout features that don't match the character set are simply removed during compiling. This makes it possible to use a standardized OT Layout features file that contains all possible features and to generate OpenType fonts (in batch with DataMaster). Everything that is supported by the AFDKO is supported by the FM tools also. Like DataMaster, OTMaster supports the latest build of the AFDKO 2.5. Because it is possible in OTM to export the features in a file, one can re-use this file in the app for compiling OT Layout tables for other fonts (batch is on the to-do list). For instance FontLab Studio users can easily update their fonts this way. The exported features file needs some updating then though, because of the syntax changes since the AFDKO 1.6. In contrast with DataMaster, OTM will not supply the user with detailed info concerning syntax errors, so some knowledge of the matter is required. Malcolm, the Adobe FDK for OpenType library used by FontLab Studio is incorporated into the source code of FontLab Studio. Fontlab Ltd. has a license for the source code of AFDKO. We do not use the freely downloadable binary version of AFDKO, since the use of AFDKO inside of FontLab Studio requires direct linking into the source code. Wo when Adobe releases an updated version of the AFDKO source code, Fontlab Ltd. will be able to update FontLab Studio — but this is not always completely trivial. Since version of 1.6 of AFDKO, Adobe have extended and changed many aspects of the library, and introduced new functionalities (such as intelligent outline scaling or the Adobe autohinting). Also, support for mark attachment and additional lookup types have been added. Finally, some major changes to the syntax have been done. So we do need to modify FontLab Studio on our end to make it work with newer version of the library — therefore it's not a change that the users will be able to do themselves. Our work on Fontographer 5 is well under way, quickly approaching release. This will be the first product that will incorporate the new AFDKO library. FontLab Studio 6 and TransType 4 will follow later this year. Best, Adam
http://www.typophile.com/node/65355
CC-MAIN-2017-13
refinedweb
881
62.68
08 November 2012 14:46 [Source: ICIS news] LONDON (ICIS)--Major Poland synthetic rubber producer Synthos is suffering from weak tyre demand in ?xml:namespace> “Amid weak European tyre demand, the styrene butadiene rubber (SBR) market remained tough in Q3, with synthetic rubber prices extending declines from €2,375/tonne ($3,045/tonne) in June to €2,210/tonne in September,” Piotr Drozd, a chemical sector analyst at the bank, wrote in a note to investors. Average third-quarter European emulsion styrene butadiene rubber (ESBR) contract prices fell 16% quarter on quarter and were down 29% year on year, the analyst said. While the butadiene price slump was even more pronounced - down 27% quarter on quarter and 38% year on year - styrene prices held up quite well, declining only 1% versus the second quarter and increasing 12% year on year, he added. “This had a negative effect on benchmark ESBR margins,” Drozd said, which according to WOOD & Company's estimates compressed by 5% quarter on quarter and 31% year on year. “Against these headwinds, we expect “With ESBR prices heading south”, Drozd forecast a 9% quarter on quarter pullback in Synthos' third-quarter revenues to zlotych (Zl) 1.49bn ($0.46bn, €0.36bn). Net profit would likely sink 50% to Zl 142m, he added. ($1 = €0.78, $1 = Zl 3.24, €1 = Zl
http://www.icis.com/Articles/2012/11/08/9612391/weak-europe-tyre-demand-hurting-polands-synthos-bank.html
CC-MAIN-2015-06
refinedweb
223
56.69
I thought that this would be simple I was given a formula to use and was given an assignment to make a simple program that computes the area of a polygon. Here is the code I used: import math #Input n = eval(input("Enter the number of sides: ")) s = eval(input("Enter the length of the side: ")) #Calculation area = area = ((n * s**2) / ((4 * math.tan)*(math.pi/n))) #Output print("The area of the polygon is",area) print('') print('') Here is the error I get : Traceback (most recent call last): File "/home/barrett/Documents/32-Lab3.py", line 10, in <module> area = area = ((n * s**2) / ((4 * math.tan)*(math.pi/n))) TypeError: unsupported operand type(s) for *: 'int' and 'builtin_function_or_method' Any help with this would be greatly appreciated I am new at this and I look forward to learning and contributing to this forum site as I learn more. Thanks so much!
http://forums.devshed.com/python-programming-11/help-program-computes-polygon-951600.html
CC-MAIN-2017-13
refinedweb
154
57.61
the process as other operations are generally performed, such as disassociating the daemon process from any controlling tty. Convenience routines such as daemon(3) exist in some UNIX systems for that purpose.. Terminology could not be bothered with, much as computer daemons often handle tasks in the background that the user cannot be bothered with. BSD and some of its derivatives have adopted a daemon as its mascot, although this mascot is actually a cute variation of the demons which appear in Christian artwork. Unix users sometimes spell daemon as demon, and most usually pronounce the word that way. Pronunciation The word daemon is an alternative spelling of demon, and taken out of its computer science context, it is pronounced /ˈdiːmən/ DEE-mən.[3][4][5] Perhaps due to the relative obscurity of this spelling elsewhere, the computer term daemon is sometimes pronounced /ˈdeɪmən/ DAY-mən. Types of daemons In a strictly technical sense, a Unix-like system process is a daemon when its parent process terminates and is therefore 'adopted' by the init process (process number 1) as its parent process and has no controlling terminal. However, more commonly, a daemon may be any background process, whether a child of init or not. that may be on a mounted file system (allowing it to be unmounted). - Changing the umask to 0 to allow open(), creat(), et al. calls to provide their own permission masks and not to depend on the umask of the caller - Closing all inherited open Windows equivalent In the Microsoft DOS environment, such programs were written as Terminate and Stay Resident (TSR) software. On Microsoft Windows NT systems, programs called services perform the functions of daemons. They run as processes, usually do not interact with the monitor, keyboard, and mouse, and may be launched by the operating system at boot time. With Windows NT and later versions, one can configure and manually start and stop Windows services using the Control Panel → Administrative Tools or typing "Services.msc" in the Run command on Start menu. Mac OS equivalent. Mac OS X, being a Unix system, has daemons. There is a category of software called services as well, but these are different in concept from Windows' services. Etymology In the general sense, daemon is an older form of the word demon. In the Unix System Administration Handbook, Evi Nemeth states the following about daemons:.403) Sample Program in C on Linux #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <syslog.h> #include <errno.h> #include <pwd.h> #include <signal.h> /* Change this to whatever your daemon is called */ #define DAEMON_NAME "mydaemon" /* Change this to the user under which to run */ #define RUN_AS_USER "daemon" #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 static void child_handler(int signum) { switch(signum) { case SIGALRM: exit(EXIT_FAILURE); break; case SIGUSR1: exit(EXIT_SUCCESS); break; case SIGCHLD: exit(EXIT_FAILURE); break; } } static void daemonize( const char *lockfile ) { pid_t pid, sid, parent; int lfp = -1; /* already a daemon */ if ( getppid() == 1 ) return; /* Create the lock file as the current user */ if ( lockfile && lockfile[0] ) { lfp = open(lockfile,O_RDWR|O_CREAT,0640); if ( lfp < 0 ) { syslog( LOG_ERR, "unable to create lock file %s, code=%d (%s)", lockfile, errno, strerror(errno) ); exit(EXIT_FAILURE); } } /* Drop user if there is one, and we were run as root */ if ( getuid() == 0 || geteuid() == 0 ) { struct passwd *pw = getpwnam(RUN_AS_USER); if ( pw ) { syslog( LOG_NOTICE, "setting user to " RUN_AS_USER ); setuid( pw->pw_uid ); } } /* Trap signals that we expect to receive */ signal(SIGCHLD,child_handler); signal(SIGUSR1,child_handler); signal(SIGALRM,child_handler); /* Fork off the parent process */ pid = fork(); if (pid < 0) { syslog( LOG_ERR, "unable to fork daemon, code=%d (%s)", errno, strerror(errno) ); exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or for two seconds to elapse (SIGALRM). pause() should not return. */ alarm(2); pause(); exit(EXIT_FAILURE); } /* At this point we are executing as the child process */ parent = getppid(); /* Cancel certain signals */ signal(SIGCHLD,SIG_DFL); /* A child process dies */ signal(SIGTSTP,SIG_IGN); /* Various TTY signals */ signal(SIGTTOU,SIG_IGN); signal(SIGTTIN,SIG_IGN); signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */ signal(SIGTERM,SIG_DFL); /* Die on SIGTERM */ /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { syslog( LOG_ERR, "unable to create a new session, code %d (%s)", errno, strerror(errno) ); exit(EXIT_FAILURE); } /* Change the current working directory. This prevents the current directory from being locked; hence not being able to remove it. */ if ((chdir("/")) < 0) { syslog( LOG_ERR, "unable to change directory to %s, code %d (%s)", "/", errno, strerror(errno) ); exit(EXIT_FAILURE); } /* Redirect standard files to /dev/null */ freopen( "/dev/null", "r", stdin); freopen( "/dev/null", "w", stdout); freopen( "/dev/null", "w", stderr); /* Tell the parent process that we are A-okay */ kill( parent, SIGUSR1 ); } int main( int argc, char *argv[] ) { /* Initialize the logging interface */ openlog( DAEMON_NAME, LOG_PID, LOG_LOCAL5 ); syslog( LOG_INFO, "starting" ); /* One may wish to process command line arguments here */ /* Daemonize */ daemonize( "/var/lock/subsys/" DAEMON_NAME ); /* Now we are a daemon -- do the work for which we were paid */ /* Finish up */ syslog( LOG_NOTICE, "terminated" ); closelog(); return 0; } See also - Server - List of computer term etymologies - Windows service - Terminate and Stay Resident - User space - Service Wrapper References - ^ Eric S. Raymond. "daemon". The Jargon File.. Retrieved on 2008-10-22. - ^ Fernando J. Corbató (2002-01-23). . - ^ "The BSD Daemon". Freebsd.org.. Retrieved on 2008-11-15. External links This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)
http://www.answers.com/topic/daemon-computer-software
crawl-002
refinedweb
940
51.58
This section describes the possible problems that you may encounter when you develop applications or libraries on the Symbian platform based on Standard C++. These problems can occur in the following scenarios: Use of one definition rule Standard C++ calling Symbian C++ functions The function signatures of the global operator new on Symbian C++ and Standard C++ differ only in the exception specification. As per Standard C++, global operator new has the following signature: void* operator new(std::size_t size) throw(std::bad_alloc); While in Symbian C++, it is: void* operator new(unsigned int aSize) throw(); Since the compiler name-mangles references to both these symbols as the same, it is possible (for the linker) to resolve a reference to one with the definition to the other. If such a combination is not identified at build time, the memory allocation may fail in the following cases: If a reference to Symbian C++ operator new is resolved against the definition of Standard C++ operator new , then it throws an exception which may leave the CleanupStack in an unstable state. If a reference to Standard C++ operator new is resolved against the definition of Symbian C++ operator new , then the operator new returns NULL (while an exception was expected). Since the return is not checked by the compiler, it may cause a bus error. So, the declarations must be kept separate in the translation unit. In this case only one of them can appear in a translation unit. Also, since they have the same mangled names, they cannot appear in the same link unit. As per Standard C++, one definition rule (ODR) says that there must be only one definition of a symbol in a program. But to be able to maintain a single definition in a program, symbol pre-emption must be possible. This functionality is not supported on the DLL model of the Symbian platform. Example The following example illustrates the problem with the use of one definition rule: //MySingleton.h template <class T> class MySingleton { public: static T& GetInstance() { static T * aT = NULL; if (!aT) aT = new T; return *aT; } }; class X: public MySingleton<X> { public: X(): iX(0) {}; int Prod() { return ++iX; } private: int iX; }; Foo.cpp #include <MySingleton.h> EXPORT_C int Foo() { return X::GetInstance().Prod(); } Bar.cpp #include <MySingleton.h> EXPORT_C int Bar() { return X::GetInstance().Prod(); } In a scenario where Foo.cpp is in Foo.dll and Bar.cpp is in Bar.dll. To call Foo and Bar from an application: int Baz() { return Foo() + Bar(); } int E32Main() { printf("%d\n", Baz()); } This example must have displayed the output as 1, 2 . But on the Symbian platform, it displays 1,1 . The problem here is, the Symbian platform's DLL model. In particular, the Symbian platform does not support symbol pre-emption. static T * aT gets allocated in each DLL in which X::GetInstance is invoked. Here the problem arises because the Symbian platform cannot redirect the references in distinct DLLs to a single unique location as required by the ODR. The following example illustrates the nature of one of the problems associated with achieving seamless integration of Standard C++ with Symbian C++. Here seamless means: without the manual introduction of additional harness or barrier code to effect the integration. SymbianCallerLC calls two different functions: one which expects standard C++ semantics ( CppCallee ), and another which expects the Symbian platform semantics ( GetAK1LC ). SymbianCallerLC itself belongs to the Symbian C++ world since it participates in the LC convention (it imposes a contract on its caller with respect to the object that it returns). K1 * SymbianCallerLC() { K1 * aK1 = GetAK1LC(); CppCallee(aK1); return aK1; } The sole point of this function is to demonstrate that stack depth cannot be used as an implicit means to synchronize the cleanup stack with the control stack. It might be thought that recording stack depth at the point at which an object is pushed onto the cleanup stack can be used by the runtime to determine if the object should be popped and destroyed during a standard C++ throw . Such a belief would be erroneous. For example, a stack allocated object of sufficient size ( aArray in this case). The stack depth when the object allocated by K1::NewLC is pushed on the cleanup stack is bound to be greater than the stack depth when the try statement is executed in CppCallee . From this example, therefore, that the stack depth at which an object was allocated (or rather pushed onto the cleanup stack) gives no indication of the ordering of various operations and can therefore not be used to determine the inclusion of one extent within another. K1 * GetAK1LC() { int aArray[100]; // stack frame for GetAK1LC has space for 100 ints - i.e. sp in this call to K1::NewLC // will be less than at the 'try' in CppCallee return K1::NewLC(aArray); } In the current context the object returned by GetAnotherK1LC will be pushed on the cleanup stack when stack depth is less than it was in the earlier call to GetAK1LC , more evidence that stack depth cannot be used to determine ordering or extent inclusion. K1 * GetAnotherK1LC() { return K1::NewLC(); } CppCallee(K1 * aK1) is a catcher which calls CppCallee(K1 * aK1, K1 aK2) which can throw. It also calls GetAnotherK1LC() in the extent of the try statement. If CppCallee(K1 * aK1, K1 aK2) throws it might seem desirable that anotherK1 must be cleaned up by the runtime as part of the throw. void CppCallee(K1 * aK1) { try { K1 * anotherK1 = NULL; anotherK1 = GetAnotherK1LC(); CppCallee(aK1, anotherK1); } catch (...) { } } All rights reserved. Unless otherwise stated, these materials are provided under the terms of the Eclipse Public License v1.0.
https://akawolf.org/documentation/sdk/GUID-AF2CE612-F12E-5A18-81A5-C303992D2D46.html
CC-MAIN-2019-04
refinedweb
943
60.45
#include <hallo.h> * Michael Gilbert [Sat, Mar 11 2006, 10:21:46PM]: >. First, this Howto is not completely correct ("modprobe evdev" to run xev? wtf). Second, I assume that the evdev X module is going to replace all that ugly workarounds with mouse button counting for ZAxisMapping and guessing the correct driver etc. The only thing I am missing in the evdev driver is the ability to pick up the correct device by itself. X in /dev/input/eventX may change all the time, the thing would not as smooth as /dev/input/mice for the old drivers untill somebody implements autodetection of the supported devices. Cc'ed to correct list. Eduard.
https://lists.debian.org/debian-devel/2006/03/msg00453.html
CC-MAIN-2014-15
refinedweb
112
62.38
Resource-Oriented Architecture: Resource Metadata Introduction This series is an investigation of how the Web and its related technologies can help solve many of the information management, data integration and software architectural problems that have been plaguing us for years. The goal is to achieve some of the promises of the Service-Oriented Architecture vision in a scalable and flexible way. These ideas do not represent the only way to successfully build modern systems and there are places they do not apply. The series is intended, however, to pitch a consistent, coherent and viable vision based on the choices that have made the Web such a success. In some ways, it will seem to fly in the face of the guidance the software industry has been providing. In other ways, it represents some of the best thinking by an amalgam of researchers and practitioners who have spent more time thinking about these problems than we can comprehend. In the first article of this series, we took a deeper dive into the REpresentational State Transfer (REST) architectural style as a unifying basis for the subsequent discussion. Non-RESTful systems can certainly participate in this vision, but there are specific benefits to taking an information-focused approach. The clients of our systems rarely care what tools we use to satisfy their needs unless there is a compelling optimization or productivity gain from a particular choice. They do care, however, about being able to browse information and control the context in which it is used. The benefits afforded by RESTful systems are flexibility, discoverability, productivity, scalability and a consistent, simple interaction style. Fully embracing the style is not easy, but it does have some clear rewards. While we usually focus on the invocation of the service through a uniform interface (URL), we often forget its role as an identifier. The following URL: certainly looks like an interface to some kind of a reporting system we could invoke via HTTP. It is also a unique identifier to a specific report. Keep in mind that URLs are also URIs, so they serve the dual purpose of identifying resources and being resolvable. If we wanted to comment on the report, provide a rating, indicate authorship or any other kind of metadata, this URL is a useful handle with which to do so even if we do not resolve the reference. It is a global name to uniquely identify an instance of the reporting service. In this way, the URIs of the Web (usually URLs) unify access to documents, data, services and, as we shall see, concepts. This consistent naming scheme is the start. Being able to resolve the references on demand in a content-negotiated way is a powerful next step. Now that we have names for all of our various information resources we need a way to describe them collectively via arbitrary data through a common mechanism. Resource Metadata As an example of describing these resources, we might like to say: - Brian Sletten created the service. - Brian Sletten is a Person. - The service published on 2010-01-05. - The service a Payroll Reporting Service. These facts represent different kinds of relationships, but they all follow the same pattern: Associate a value with a subject through some kind of a relationship. How you choose to identify and represent the subjects, relationships and values will have important consequences, so let's dig into the topic a bit more. The publication date statement seems relatively straightforward; a date is date is a date. The authorship statement is a little more complicated. We could simply use the name "Brian Sletten" as the value of the statement. In some circumstances, this might be sufficient. But what if someone wants to contact the person responsible for creating the service. Without more information, we are putting the burden on them to track down the contact information. It would be just as easy for us to use a URL (assuming one existed) to refer to the creator. Something like would do nicely. It allows us to disambiguate references to "Brian Sletten" in a global context. A side benefit of minting resource locators for people is that they become resolvable content like anything else. Once we know who created the service, we can resolve the reference to retrieve things like contact information. This is where we bump into REST again. We can define a default response format of HTML for the person reference if the user is coming in through a browser. This would make sense to make it easy for another human to find what she is looking for. However, we can also support content negotiation to request the information back as XML, JSON or RDF. Whether we express information as data about the resource (retrieved when we resolve the reference) or as metadata (stored externally about the resource) will be resource-specific. In some cases, you may wish to do both. Giving resolvable URLs to non-network resources such as people and concepts has traditionally been problematic. Are you referring to the person or a document about the person? We will discuss some solutions in subsequent articles. For now, we'll just assume that we have a mechanism for solving the ambiguity. Another benefit of using a URL to represent "Brian Sletten" is that we can hang statements on it, such as that he is a Person, he has an email address, etc. In this way, we can grow a graph of related facts organically. We connect facts about one subject to other subjects (as values in that relationship). We can imagine asking questions about the values that are related to other subjects as we discover references to the new subjects. A graph is a much more extensible model than a table, so we can easily support new facts about any of our nodes over time. As we learn new things about resources, we can attach them to our model. This has the benefit of allowing us to accumulate knowledge from a variety of sources. It also allows a decentralized system where anyone can express facts about anything. Whether we choose to include their facts in our consideration is up to us. The final value we identified above, Payroll Reporting Service, is a term that means something to our organization. Presumably there are other kinds of services and they are organized in a meaningful fashion (e.g. a Payroll Reporting Service is a type of a Reporting Service). We will need additional mechanisms for organizing terms into these relationships but we will return to that in the next article. We must first consider the relationships that connect these values to the subject. If we were using a relational database to capture these results, we might create column names such as "creator", "publish_date" or "instance_of". We would likely use a technology like Hibernate to map these column names into an object model so we could write software to use the information. This approach might work for a small number of relationships, but it clearly will not scale up to support arbitrary metadata; we cannot keep adding columns anytime someone says something new about a resource. We would have lots of shallow tables with only a few entries. Assuming we did head down that path, however, we would run into further problems when we consider merging multiple databases of resource metadata. Perhaps the engineering and marketing departments have different IT staff who capture the metadata differently. In order to allow a common view across these systems, we will probably have to write a new layer, create a merged database or do something else painful and harder than it needs to be. Doing so once or twice is possible. Doing it for every new integration is unthinkable. Once we contemplate partner integration strategies of services across organizational boundaries we can pretty much just give up. Advocates of the WS-* technology stacks might jump up and say that they have solved the problem with common schema systems, UDDI metadata repositories and the like, but they really have not. The problem is that any approach that involves a common model outside of a particular community of interest is likely to fail. Forcing partners to use the same schemas ignores the fact that, collectively, we simply do not see the world the same way. Nor do we have the same information needs. Common models become least common denominator models; invariably, someone's needs are left on the floor. This is not to say that the WS-* technology stack does not solve some problems, it simply does not solve this one. But again, let us assume we have committed to a strategy that relies on some kind of common model. Inevitably, we will have to integrate with another partner who has not committed to the same strategy. How do we align our metadata then? How do we explain what the terms mean? How do we connect our terms and relationships to their terms and relationships? Finally, once we decide to move beyond the realm of metadata how does actual data fit in? Do we have to start from scratch with a new common data model? How do we connect our metadata to our data? By now it should be clear that many of the technology choices of the past twenty years or so have simply entered the fray at the wrong level. We attempt to model domains and processes and people and data separately using insufficient and rigid abstractions. We ignore realities about how information is produced and consumed. Information does not have a format and rarely has boundaries. There is no explicit distinction between data and metadata. Perhaps most fundamentally, we do not and usually will not agree to a consistent world view. Any top down IT initiative that ham-handedly tries to get around this reality is doomed to fail as we have seen time and time again. We need another strategy that combines the efficiencies of top down efforts with the reality of organic, bottom up perspectives. We need a data model that frees us from the constraints of a particular schema, language, object model, product or world view. We need to encourage people to agree where they do, but allow them to disagree as well. We need to let them care about different things and be fully supported by any modeling activities. Where we cannot support them centrally, we need to allow their needs to be met on the edge. This is not to say we are heading toward anarchy. Where we need to validate and restrict, we certainly can. The W3C's Semantic Web initiative is a collection of technologies that helps provide just these features. We will explore the larger goals of the effort over time, but for now, we will focus on the Resource Description Framework (RDF) and SPARQL for their capacity to describe, link and query resource metadata. RDF RDF is a building block technology. It represents an extensible data model that supports the Open World Assumption. It is useful as a metadata model for describing information resources. As we shall see in later articles, however, it provides a mechanism for expressing data as well. When we build upon a consistent naming scheme (URIs and URLs) and the Web Architecture of loosely-coupled resources negotiated into different forms, RDF gives us the ability to link and describe all of these resources in powerful ways. At a basic level, you can imagine a series of facts expressed in RDF. We can accumulate these facts over time and from a variety of sources into a model backed by a directed graph. Whatever form the source data is in, we can usually convert it into RDF relationships and add them to our knowledge base. In this way, we lose the problem of schema integration efforts. RDF "facts" are expressions that relate the subject to a value. The subjects are either URI-addressed resources or unnamed blank nodes. The values can be literal values (strings, dates, numbers) or other URI-addressed nodes. The subject of one statement might be the value of another. Let's consider the facts we wanted to express about the reporting reporting service above. The subject is easy. The date value is also easy: '2010-01-05'. How we wish to connect them requires a bit more thought. We want to refer to the publication date of the service. We could make up our own term but we do not need to. There is a widely used metadata specification called Dublin Core () that involves publication metadata. It was developed by a group of librarians interested in standard terms for referring to journals, books, online articles, etc. We are not required to use their terms, but there is no reason not to. By browsing around their site we see that there are quite a few useful terms such as title, description and license. To indicate when the service was published, the 'date' term seems promising. By clicking through the link, we see a description of the term, how it applies and what its intent is. This collection of RDF terms is referred to as a vocabulary. An RDF vocabulary is usually domain-specific (in this case publication metadata). Each term is described so as to be useful by both software and humans. What we quickly see is that in addition to being well-described, the term is grounded in a URL:. This is a globally unique name for the term. If we choose to use this term, others will know exactly what the term means even if they have never seen it before. Besides the human readable description, there is a machine-readable description as well. We can get to it by resolving the URL for the term. By clicking through the URL above, we get redirected to:. This redirection is an important aspect of URI curation, but we will return to that in a future article; it is not necessary for simply publishing RDF vocabularies. What we get back when we resolve an RDF vocabulary is usually an RDF/XML serialization of an RDF model. In this way, RDF is used to describe itself. Don't get too stressed about how to interpret the complex model yet, but if you are curious, it is a series of facts encoded in hierarchical XML entity relationships. <rdf:RDF xmlns: . . . <rdf:Description rdf: <rdfs:label xml:Date</rdfs:label> <rdfs:comment xml: A point or period of time associated with an event in the lifecycle of the resource. </rdfs:comment> <dcterms:description xml: Date may be used to express temporal information at any level of granularity. Recommended best practice is to use an encoding scheme, such as the W3CDTF profile of ISO 8601 [W3CDTF]. </dcterms:description> <rdfs:isDefinedBy rdf: <dcterms:issued>2008-01-14</dcterms:issued> <dcterms:modified>2008-01-14</dcterms:modified> <rdf:type rdf: <dcterms:hasVersion rdf: <rdfs:range rdf: <rdfs:subPropertyOf rdf: </rdf:Description> . . . </rdf:RDF> Terms relate to an outer rdf:Description resource referenced by an rdf:about or rdf:id attribute. Again, we'll dig deeper into these ideas later, but for now try to read it as follows. Find the the things that are being talked rdf:about (remember, the full URI expands within the rdf namespace ground at). Here, this indicates the subjects of the RDF facts. As an example, we can unwind the relationships expressed about the dc:date term: <> <rdfs:label>"Date". <> <rdfs:comment>"A point or period of time associated with an event in the lifecycle of the resource.". - ... <> <dcterms:issued>"2008-01-14". - ... By now, you are probably thinking this is incredible overkill and that a column in a database is a much simpler implementation strategy. That may be, but you lose a lot in the process. A database column means nothing outside of the database; you cannot even refer to the relationship outside of a SQL script or object-relational mapping (ORM) configuration file. Because you cannot refer to the relationship, you cannot connect that aspect of the record to another, unrelated database. Or information captured in a spreadsheet. Or a report. Or an RSS feed. Or an online service. Information comes to us in many forms these days and we simply cannot rely on relational database tables to be where we do all of our integration. We need a way to capture and represent how information is connected outside of any particular programming language or database technology in order to unify it all. Another problem is that we generally cannot refer to our records outside of the context of our databases either. Certainly, we have identifiers, but how expressive is a long series of digits? Is that the primary key? A global key? In what context? One of the main values of a URL is that it grounds the identity into a global context. Any reference in any context can be connected to other references. You might assume that this means that we all need to use the same terms, but this is not the case. There are efficiencies to doing so, but we will learn how to get around this later in the series. Fortunately, we are not suggesting you toss your relational databases. They are well-understood, ubiquitous, well-tooled and here to stay. The RDF model can still be used though. Logical references to records can be achieved by using a RESTful URL. Where we need to, we can map column names to RDF relationships (or just make them up on the fly -- this is not as crazy as it sounds). What we have accomplished is having a logical way of referring to information in whatever form it is, outside of the context of that form. When we come across a resource reference, we can query a metadata repository for more information about it or we can simply resolve it and see what we get back. The MIME type of what is returned will give us an indication of how to parse the response. We can discover references to new and related information within the responses. We can also discover alternative forms to retrieve the information in a more convenient format. The devil is still in the details, but this is the basic concept of the vision. We are embracing Webs of information, public and private. Now that we understand more of the environment, how do we express an RDF fact? There are several RDF serialization formats we can use. We have already seen RDF/XML and it is pretty verbose. Expressing the fact in the Turtle format is deceptively simple: <> <> "2010-01-05" . We have a subject, a predicate and a value; a triple, or single fact. Keep in mind that RDF is a graph model. The serialization formats are simply how we store or transfer the information. The graph from the above triple would be parsed into a model that looks conceptually like this: Now we can extend our knowledge base with some more metadata about the resource in question: <> <> <> . We now have two triples and our graph would look like: Our facts serialized in RDF/XML would look like this (yes, it is kind of ugly): <rdf:RDF xmlns: <rdf:Description rdf: <creator xmlns="" rdf: <date xmlns="">2010-01-05</date> </rdf:Description> </rdf:RDF> The point in highlighting this is that RDF data can be incredibly fluid. It can exist in a native RDF format (such as RDF/XML) or it can be generated on the fly from another data source. It is also eminently portable. Whatever form the native data is stored in, once converted into RDF, it can be exported from one store and imported into another RDF-aware store trivially. Let's add a few more facts to our knowledge base while we are at it. <> <> <> . <> <> <> . <> <> "bsletten@example.com" . Here we have indicated that "Brian Sletten" is a Person. We have chosen the term 'Person' from the Friend-of-a-Friend (FOAF) vocabulary (). This is another widely-used collection of terms involved with social networks, professional interests, educational backgrounds, etc. We also indicate that a different service was created by the engineering department. We have used a made up URL for our 'engineering department' example to have another Dublin Core 'creator' that is not a person for our query examples. We also added Brian's (fake) e-mail address. Our final knowledge base is shown in the following RDF/XML serialization: <rdf:RDF xmlns: <rdf:Description rdf: <type xmlns="" rdf: <mbox xmlns="">bsletten@example.com</mbox> </rdf:Description> <rdf:Description rdf: <creator xmlns="" rdf: </rdf:Description> <rdf:Description rdf: <creator xmlns="" rdf: <date xmlns="">2010-01-05</date> </rdf:Description> </rdf:RDF> We will defer code examples until the next article, but programmatically, you would read triples into a model and then query it for certain patterns. In order to do that, we need a query language. Fortunately, SPARQL is a W3C standard available for querying RDF graphs. Querying RDF SPARQL is a recursive acronym that stands for the SPARQL Protocol and RDF Query Language. We will dive more deeply into it in part three of this series, but now we will touch upon the basics to extract information from our knowledge base. For our purposes now, SPARQL allows you to express patterns that are matched against an RDF graph. This is either considered a "default graph" (specified outside of the query) or from a series of one or more named graphs (from within the query). We are going to use Twinkle's SPARQL handling to keep things simple. If you want to follow along, go download Twinkle. It is a tool for querying SPARQL data sources. Copy the final RDF/XML serialization above and paste it into a file such as /Users/brian/facts.rdf. Now run Twinkle: java -jar twinkle.jar You should see a Swing user interface show up with a default query window. In that window, select the File button and browse to the file you just saved out. Select it. This will now establish that data as the default graph for our queries. If you are comfortable with SQL, SPARQL will (eventually) feel very comfortable to you as well. We are going to match patterns to select results from the graph. A basic query that lists all of the facts in a graph is: select ?s ?p ?o where { ?s ?p ?o . } Your results should look something like the following: We have asked SPARQL to find all triples that match the pattern of unbound variables. Avoid doing this on large graphs! The result set is shown in the image above as a table with each triple spelled out. We used the names s, p and o to represent the unbound variables that we want to match based on their positions in statements: subject, predicate and object. The query engine will match these patterns against the arcs and nodes of the graph. The names of the variables are less important than their positions in the patterns. As always, good variable names make queries easier to understand. A more constrained query might be something like: select ?service where { ?service <> ?creator . } In this case, we have chosen different names for the variables and are only selecting for one of them. At this point, we do not care who the creator was, we just want to know any service that has a creator. Try modifying the query so you get both the service and the creator. Now, how about just the creator? You will quickly get tired of typing URLs. To make it easier, SPARQL has support for prefixes: PREFIX dc: <> select ?service where { ?service dc:creator ?creator . } The final query we will do for now shows how we can use the shape of the graph to ask more pointed questions. We have two creators in our knowledge base, one Person and one non-Person. To be accurate, we don't know what the non-Person creator is, we have just discussed it being the Engineering department in our text. As far as our facts are concerned, we do not know anything about it. If we wanted to ask for the e-mail address of anyone who is a Person and the creator of a service, we could use: PREFIX dc: <> PREFIX foaf: <> PREFIX rdf: <> select ?mbox where { ?s dc:creator ?c . ?c rdf:type foaf:Person . ?c foaf:mbox ?mbox . } There are some other syntactic conveniences we could have leveraged, but for now we just want to introduce the idea that when can query along the graph. For every thing (?s) that has a dc:creator ?c, if that thing (?c) is a foaf:Person, grab that thing's (?c) e-mail address if we know it. Perhaps you can start to see how we can explore information spaces by querying how information resources are connected: people to publications to topics to geographic regions and on and on. In the process, we will discover what relationships exist and how things are related and allow people to take advantage and build upon what they know as never before. Conclusion We have touched on only the beginning of these concepts, but hopefully the idea of loosely-coupled information resources is starting to make some sense. We can keep the information in the form it is stored in natively, but access it in a different form, on demand. The technology stack associated with the Semantic Web is by no means perfect. The parties involved have spent years arguing over the most minute details. These disagreements continue to this day. But, they have made some very important discoveries about how we can name and resolve information flexibly in a wide variety of contexts. These initial choices compound to create a vibrant ecosystem of information. We can get around many of the high inertia obstacles that have thwarted our IT systems in the past. In the next article we will take another step down the Rabbit Hole to explore the deeper realities of these webs of data. Yes, but what *knid* of date? by Pete Miller The captn The Right Level of Abstraction by Tim Berglund Abstracting in the wrong way produces disappointing results. C, which is not much of an abstraction on top of a VonNeumann machine, has been rejected over the course of my adult lifetime as a good way to build large systems, because we are not smart enough to build big things while having to babysit so many details. RPC-based distributed computing mechanisms, while hardly rejected by the majority right now, also fail by imposing too rigid—perhaps too high?—an abstraction on the designer.* SemWeb stuff really seems to get this right. It wants to provide a generalized architecture for building information systems, and in the process it presents us with abstractions that correlate very neatly to intellectual categories that function as peers to the absurdly large category of "information." Liberally educated programmers can't talk about the semantic web for long before also talking about disciplines like linguistics, epistemology, and metaphysics. Since "the world of things, what they are, how we know about them, and how we talk about them" is the subject matter of enterprise computing, it's a reassuring smell that the formal disciplines that deal with these topics are easily invoked when trying to describe what the semantic web is. *One might say that comparing C to SOAP is like comparing trees to rational numbers. Sure, kinda, but they're both computing abstractions, and both could be proposed as the way to build the next generation of information systems. Re: The Right Level of Abstraction by Alexander Bronshtein About Common models and about RDF by Andrés Ferrando Nice article. Two things about it: When you're talking about WS stack and the like, you are against common models ("Common models become least common denominator models"); but then, when you start talking about RDF you propose to use one ("There is a widely used metadata specification called Dublin Core (dublincore.org/) that involves publication metadata."). What is the difference? Why one is bad and the other ok? And one question about RDF: how can you express more info (for instance, for things that change in time). If you need to add for instance info about time or location for a fact. Andrés. Re: About Common models and about RDF by Brian Sletten I am going to skip your second question because I will be discussing it during the article series (it's a very good question though). The first question (also very good), is a common one. It seems like we all have to use the same terms and that isn't the case. I will be discussing these ideas further in the series, but the short version is that a common object model or schema tends to be fairly static and rigid. It comes about through a consensus gathering process and then everyone participating in the system must abide by those decisions. Vocabularies such as Dublin Core also come about through a process of consensus gathering but the difference is, if you do not feel like your needs are met by those terms and relationships, you are free to participate in the exchange of metadata using your own terms. If we need to connect your terms to standards such as Dublin Core, we can. You are also free to use a single term from someone else's vocabulary if it works or you can extend it in some way. So, there are efficiencies if people reuse existing vocabularies, but unlike the common model/schema approach, you are not required to. The RDF model allows us to mix and match and connect terms. Even within an organization that specifies what terms are used centrally, you are free to add your own terms at any point. I will dig into these ideas more as we go, but I hope this answers your question now. Re: Yes, but what *knid* of date? by Brian Sle
http://www.infoq.com/articles/roa-resource-metadata/
CC-MAIN-2014-35
refinedweb
5,008
62.88
For better understanding on Entity Framework, I recommend you to read EF Series by Anders Abel on his blog here . I learnt lot from his post about Entity Framework. You may want to follow Julie Lerman for better learning on ADO.NET Entity Framework. In this post we will walk through basics of Entity Framework migration commands and learn about Code First Approach. Entity Framework allows you to create database from plain classes. You can model your domain into classes and subsequently database can be created or updated from the model using Entity Framework. We model domain into classes and database gets created form model classes is known as Code First Approach. Here you can create database from plain old classes. Model classes does not have to extend any base class etc. The other two approaches are, - Model First Approach - Database First approach Code First Approach in Entity Framework reduce task of modelling database on designer and working with XML etc. Let us start rolling, suppose we need to model School database. For this we have created two POCO classes as below. Public class School { public int Id { get; private set; } public string Name { get; set; } public Icollection<Student> Students { get; set; } } public class Student { public int Id { get; private set; } public string Name { get; set; } public string Grade { get; set; } } School and Student classes are representing School and Students real time entities respectively. Next we need to create Context class. This class must inherit DbContext class. Public class Context : DbContext { public Context() :base() { } public DbSet<Student> Students { get; set; } public DbSet<School> Schools { get; set; } } Regardless what kind of application you are working with and following Code First approach, you need to add reference of EntityFramework. You can use NuGet manager to install EntityFramework library in project you are working. When you execute code, surprisingly you will find database has been created. You may wonder that where Context database (we created class Context which is inheriting DbContext class) has been created? Let us go back to context class, we have not provided any connection string in constructor. In this case database would get created in local SQL Express comes with Visual Studio. Alternatively connection string name can be provided in constructor to create database on a particular database server. Connection string can reside in configuration file. You can launch Server Explorer to view created database. Let us go ahead and examine schema of created table, Student table is created as below, And School table being created as below, EF is intelligent enough to construct primary key on the column with name Id. If you don’t have Id column then EF will search for column with *Id and construct that column as primary key. For example if there is a property EmployeeId in model class then EF will construct column EmployeeId as primary key. Other thing you may notice that for string properties EF is creating columns with type nvarchar(MAX). You may not want this and have control on size of the columns in database. This is allowed in EF using data annotations. Let’s go ahead and modify POCO classes with data annotation. Public class School { public int Id { get; private set; } [Required] [StringLength(50)] public string Name { get; set; } public Icollection<Student> Students { get; set; } } public class Student { public int Id { get; private set; } [Required] [StringLength(50)] public string Name { get; set; } [Required] [StringLength(10)] public string Grade { get; set; } } We have put data validation annotations like Required (in db null not allowed) and StringLength. Other data validation annotations are MaxLength and MinLength. Let’s go ahead and run again to recreate or update database schema. On running application I got following exception. Poor me, EF is throwing very clear error message. We can break error in message in two parts, - Model backing Context has changed - It has changed since database has created It is suggesting us to consider Code First Migration. So let’s learn Code First Migration. Before we go ahead and explore various migration techniques, let’s have a look on Database initialization strategies. There are four database initialization strategies, - CreateDatabaseIfNotExist - DropCreateDatabaseIfModelChanges - DropCreateDatabaseAlways - Cutsom DB Initalizer All options are self-explanatory. One option is to use DropCreateDatabaseIfModelChanges database initializer to get rid of above exception. Let’s go ahead and modify Context class by adding database initializer in constructor, public class Context : DbContext { public Context() :base() { Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>()); } public DbSet<Student> Students { get; set; } public DbSet<School> Schools { get; set; } } Okay so we did not get any exception and database schema has been updated as well. You may notice Name column has been updated with length 50 and Nulls are not allowed. All good? Not really because we have lost all the data. Since in database initializer we have used option to drop database and create again if model changed. I am sure you don’t like this option and must be looking for some better options. Other option is to Enable Migrations. You can enable migration by EF command. You can run EF command from Package Manager Console. Enable Migrations run command PM> Enable-Migrations I have run command to enable automatic migration. Let’s go back to solution explorer, you will find a Migration folder is being added with a class Configuration.cs . This class got a seed method. Configuration class will look like below, internal sealed class Configuration : DbMigrationsConfiguration<SchoolDbApplication.Context> { public Configuration() { AutomaticMigrationsEnabled = true; ContextKey = “SchoolDbApplication.Context”; } protected override void Seed(SchoolDbApplication” } // ); // } } As you see that, - AutomaticMigrationEnabled is set to true - There is Seed method which will get executed after migrating to the latest version. So if you want to have some default data after migration, you will write code in Seed method. Let us consider another scenario that we want to add one more column in Student table and for that we need to add a property in Student class. Modified Student class will look like below, public class Student { public int Id { get; private set; } [Required] [StringLength(50)] public string Name { get; set; } [Required] [StringLength(10)] public string Grade { get; set; } [Required] public int Age { get; set; } } I have added Age property with basic data annotation [Required]. Previously when we tried modifying class and later database we lost all the data. This time we don’t want to repeat the mistake. So after modifying model class, add a migration with a name. Let’s run a command and give a name Student_Age to newly added migration. You are allowed to give any name of your choice. PM> Add-Migration Student_Age Further if required you can change Model and include in the same migration by running the same command. Let us go ahead and explore solution explorer again. In solution explorer inside Migrations folder you will find somenumber_Student_Age.cs file. This class contains information about this particular migration. Remember that we gave name of the migration as Student_Age. Namespace SchoolDbApplication.Migrations { using System; using System.Data.Entity.Migrations; public partial class Student_Age : DbMigration { public override void Up() { AddColumn(“dbo.Students”, “Age”, c => c.Int(nullable: false)); } public override void Down() { DropColumn(“dbo.Students”, “Age”); } } } There are two methods inside this class Up and Down method. In Up method a column being added to Students table whereas in Down method column is dropped. Don’t forget to run Update-database command to update model changes in database. PM> update-database –verbose This time you will find database has been updated and age column is added to Students table with no loss of data. For complete reference of EF Migrations commands you may want to refer here Summary In this post we learnt Code First approach in ADO.NET Entity Framework and some of the EF commands. I left you reference to learn further on same subject also. I hope after learning this post you should able to understand what is going around various EF commands and don’t accidently delete data while updating the schema. In further posts I will talk about Custom DB Initalizer and other important bits of Entity Framework. Happy Coding. One thought on “Getting started with Code First Approach and Entity Framework Migrations Commands”
https://debugmode.net/2014/08/26/getting-started-with-code-first-approach-and-entity-framework-migrations-commands/
CC-MAIN-2022-05
refinedweb
1,363
55.64