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
import datetime bree = datetime.datetime(1981, 6, 16, 4, 35, 25) nat = datetime.datetime(1973, 1, 18, 3, 45, 50) difference = bree - nat print "There were", difference, "minutes between Nat and Bree" yields: There were 3071 days, 0:49:35 minutes between Nat and Bree That's fine, but I'd like to start with two dates as strings, as "1961/06/16 04:35:25" and "1973/01/18 03:45:50" > t1=datetime.datetime.strptime("2009/01/02 13:01:15","%y/%m/%d %H:%M:%S") > doesn't do it. > ValueError: time data did not match format: data=2009/01/02 13:01:15 > fmt=%y/%m/%d %H:%M:%S The first thing that jumps out at me is that %y is the two-digit year. You want %Y for 4-digit year. One thing to keep in mind is that "2009/01/02 13:01:15" is ambiguous without a time zone. Even if you assume that both timestamps were from the same location, you need to know what daylight savings rules that location uses, to do this right. > As the error message indicates, the data input (the string) doesn't match the specified format. See the time format specifications at the ‘time.strftime’ documentation <URL:>. Note especially that ‘%y’ and ‘%Y’ are distinct. -- \ “Science doesn't work by vote and it doesn't work by | `\ authority.” —Richard Dawkins, _Big Mistake_ (The Guardian, | _o__) 2006-12-27) | Ben Finney what's strange about it? the difference between 2009/01/02 13:01:15 and 2009/01/04 13:01:15 is indeed 2 days... Can you elaborate what do you mean by 'strange'? > Changing > t2=datetime.datetime.strptime("2009/01/04 14:00:30","%Y/%m/%d %H:%M:%S") > and differencing gives me, > datetime.timedelta(2, 3555), which seems to indicate a 2 day and 3555 > second difference. Interesting, but I think there must be another way to > do this. Maybe not. to do... what? >. In both cases it produces not a function, but a ‘datetime.timedelta’ object:: >>> import datetime >>> t1 = datetime.datetime(2009, 1, 2, 13, 1, 15) >>> t2 = datetime.datetime(2009, 1, 4, 13, 1, 15) >>> type(t1) <type 'datetime.datetime'> >>> type(t2) <type 'datetime.datetime'> >>> dt = (t2 - t1) >>> type(dt) <type 'datetime.timedelta'> What you're seeing in the interactive interpreter is a string representation of the object:: >>> dt datetime.timedelta(2) This is no different from what's going on with any other string representation. The representation is not the value. > How does one "unload" this structure to get the seconds and days? It's customary to consult the documentation for questions like that <URL:>. > To find the difference more clearly. Why not just return (0,2,3555) Because the ‘datetime.timedelta’ type is more flexible than a tuple, and has named attributes as documented at the above URL:: >>> dt.days 2 >>> dt.seconds 0 >>> dt.microseconds 0 -- \ “If you have the facts on your side, pound the facts. If you | `\ have the law on your side, pound the law. If you have neither | _o__) on your side, pound the table.” —anonymous | Ben Finney > BTW, all times are local to my city. Same time zone. Yes, but how much time has elapsed between "2009/0/04 13:01:15" and "2009/06/04 13:01:15"? Even if I tell you that both timestamps were done in the same city, you don't have enough information. Hint #1: The answer in Sydney, Bangalore, and New York are all different. Hint #2: Two of those cities are in temperate zones, and one is in the tropics. Hint #3: If you don't pay attention to this, you will be bitten twice a year. > Yes, but how much time has elapsed between "2009/0/04 13:01:15" Typo. Should be "2009/01/04 13:01:15". Not really. Some areas don't have DST and the answer to that is always exactly 5 months. Depends on which DST problem you have. There is more than one solution depending on what the problem is. Store and compare in UTC and display in local time is one solution but it may not be yours. -- D'Arcy J.M. Cain <da...@druid.net> | Democracy is three wolves | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner.> >>> t1=datetime.datetime.strptime("20091205_221100","%Y%m%d_%H%M%S") >>> t1 datetime.datetime(2009, 12, 5, 22, 11) >>> type(t1) <type 'datetime.datetime'> >>> t1: 2009-12-05 22:11:00 <type 'datetime.datetime'> but in the program: import datetime t1=datetime.datetime.strptime("20091205_221100","%Y%m%d_%H%M%S") print "t1: ",t1, type(t1) produces t1: 2009-12-05 22:11:00 <type 'datetime.datetime'> Where did the hyphens and colons come from? print some_object first converts some_object to a string invoking str(some_object) which in turn calls the some_object.__str__() method. The resulting string is then written to stdout. Quoting the documentation: datetime.__str__() For a datetime instance d, str(d) is equivalent to d.isoformat(' '). datetime.isoformat([sep]) Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS Peter >> How does one "unload" this structure to get the seconds and days? > > It's customary to consult the documentation for questions like that > <URL:>. No no no, it's customary to annoy everyone on the list by asking the question *without* consulting the documentation, and then to be told to Read The Fine Manual. To be serious for a moment, if you're in the interactive interpreter, you can get some useful information by calling help(datetime.timedelta). -- Steven Not "as though", it *is* a datetime object. And it knows how to show as something meaningful to the user when printed These are very basic concepts that apply to all Python objects. I suggest that you take a moment to go through the tutorial before you continue with your efforts. Peter > Ben Finney wrote: >> "W. eWatson" <wolft...@invalid.com> writes: >> >>>. [...] > Well, it just seems weird to me. <g>. I'm modestly familiar with > objects, but this seems like doing the following. > >> No, that's an invalid analogy, because trig functions are defined to return unitless numbers and so there is no point in distinguishing between the 1.0 you get from the sine of 90 degrees and the 1.0 you get from halving 2.0. They are the same thing. But time is different. Not only do times have a unit, but we also distinguish between two different concepts: times as points on a calendar, as well as differences between such times. A calendar time of 1000 seconds is not the same as a time difference of 1000 seconds: 1000 seconds is 'Thu Jan 1 10:16:40 1970' according to the POSIX standard, Windows may pick a different moment for zero. But a time difference doesn't correspond to any specific moment in time at all, and represents a distance between two points on the calendar -- a duration. Hence Python provides timedelta objects for working with time differences, and datetime objects for working with calendar times. Of course, one might have chosen to take a different approach, and use (say) raw ints only for working with dates no matter whether they represent an absolute time or a relative time. Then the programmer would be responsible for interpreting 1000 as either 10:16:40 Jan 1 1970 or a duration of 16 minutes 40 seconds, whichever is appropriate. That's a legitimate design choice too, but not the one Python uses. -- Steven > So as long as I don't print it, it's datetime.datetime and I can make > calculations or perform operations on it as though it is not a string, > but a datetime object? No, it remains a datetime object regardless of whether you print it or not. Printing doesn't turn the object into a string, it leaves the object as-is and produces an additional string suitable for printing. This is no different from any other object: if you print a dict, or a int, or a list, the object doesn't turn into a string. When you say "print x", Python has no idea what information is appropriate to display for some arbitrary object x. So it asks x what is appropriate, by calling the __str__ method. That way Python only needs to know how to print one data type: strings. -- Steven > print some_object > > first converts some_object to a string invoking str(some_object) which > in turn calls the some_object.__str__() method. The resulting string is > then written to stdout. In fairness to the OP, that's a misleading way of describing it. Python doesn't convert objects in the standard senses of "convert lead into gold" or "convert to <insert name of religion here>". some_object.__str__ returns an independent string object while leaving some_object alone. But I'm sure you knew that already -- it's only the OP who was confused. -- Steven BTW, I had looked at some Python doc that seems to be apart from the reference above. So I'm not entirely remiss on this. I do look first. However, on the other hand, regarding the reference, 29 pages is a bit steep for any document. > It doesn't seem to be standard practice to more or less teach the > environment that Python is in. If they do, it's jumbled around. Most > books start with Python itself and skirt the issues of the environment > and interaction. There are no Python documentation police enforcing standards on documentation, so I don't know why you'd expect any consistency between non-official documents. The official documentation, though, contains an excellent tutorial <URL:>. As has been suggested to you several times already: Please work through the entire tutorial, executing every exercise and experimenting until you understand it, then progressing to the next one. Once you've done that, you will have a much better grasp of Python and can save a lot of time in discussions like this. -- \ “I'm having amnesia and déjà vu at the same time. I feel like | `\ I've forgotten this before sometime.” —Steven Wright | _o__) | Ben Finney It's nothing to do with whether you print it or not. When you print it, an equivalent string is produced, and the string is what gets printed. This is necessary, because humans only understand character-based output. >>> type(x) <type 'float'> >>> print x 82.2 >>> type(x) <type 'float'> The type of something is unchanged by printing it. The print statement merely calls methods of the object to produce strings that it can print. >>> x.__str__() '82.2' >>> x.__repr__() '82.200000000000003' >>> People talk loosely about "converting an object to a string", but that doesn't mean transmogrifying the object to something else, it means producing an equivalent value of some other type which can be used instead of the original object for some specific purpose. In this case, printing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 Holden Web LLC UPCOMING EVENTS: Here's how you'd do this with mxDateTime: >>> from mx.DateTime import * >>> bree = DateTimeFrom("1981/06/16 04:35:25") >>> nat = DateTimeFrom("1973/01/18 03:45:50") >>> bree <mx.DateTime.DateTime object for '1981-06-16 04:35:25.00' at 2b99c7881088> >>> nat <mx.DateTime.DateTime object for '1973-01-18 03:45:50.00' at 2b99c6e342f0> Now, let's look at the date/time difference: >>> bree - nat <mx.DateTime.DateTimeDelta object for '3071:00:49:35.00' at 2b99c6e36500> i.e. 3071 days, 49 minutes, 35 seconds. If you want a more human readable, relative format use Age(): >>> Age(bree, nat) <RelativeDateTime instance for '(+0008)-(+04)-(+29) HH:(+49):(+35)' at 0x2b99c6e37ef0> i.e. 8 years, 4 months, 29 days, 49 minutes, 35 seconds. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec Pyfdate has a numsplit function that should do the trick: It splits a string into its numeric parts and return a list containing the numeric parts converted to ints. >>> from pyfdate import * >>> numsplit("2007_10_09") [2007, 10, 9] >>> numsplit("2007-10-09T23:45:59") [2007, 10, 9, 23, 45, 59] >>> numsplit("2007/10/09 23.45.59") [2007, 10, 9, 23, 45, 59]
https://groups.google.com/g/comp.lang.python/c/8r33F4KMJ-Q
CC-MAIN-2022-40
refinedweb
2,076
66.54
Task: Copy All Records to Another File Program in C Plus Plus This program will open the source file in reading ( in ) mode. It will open the destination file in writing (out) mode. Then the program will read all records from source file one by one. And copy every record to destination file. C++ Program to copy all record from binary file to another file This record copy process is in a while loop. It will continue to copy records as long as end of file (source file) is not reached. Finally, this C++ file copy program will display a message: ‘File Copied successfully’ etc. The source code of Copy All Records to Another File Program in C Plus Plus /* Write a C++ Program to copy all records of a binary file 'cppfile.dat' into'copyfile.dat' */ #include<iostream> #include<fstream> #include<conio.h> #include<stdlib.h> #include<string> using namespace std; struct student { int rollno; char name[30]; }srecord; int main() { char ans; fstream file1, file2; //opening source binary file in writing mode // if we run this program again, it will //overwrite the destination file file1.open("d://cppfile.dat",ios::binary |ios::in); if(!file1) { cout<<"Source File could not open"; exit(0); } //opening destination binary file in reading mode file2.open("d://copyfile.dat",ios::binary |ios::out); if(!file2) { cout<<"Destination File could not open"; exit(0); } while(!file1.eof()) { file1.read((char*)&srecord,sizeof(srecord)); if(!file1.eof()) file2.write((char*)&srecord,sizeof(srecord)); } file1.close(); file2.close(); cout<<"\nFile copied successfully.\n Thanks for visiting"; return 0; } A sample run output :C++ Program to copy all record from binary file to another file C++ Program to copy all record from binary file to another file Output: File copied successfully. Thanks for visiting ——————————– Process exited after 4.238 seconds with return value 0 Press any key to continue . . .
https://easycodebook.com/copy-all-records-to-another-file-program-in-c-plus-plus/
CC-MAIN-2020-05
refinedweb
313
56.66
taylorsneadMember Content count17 Joined Last visited Community Reputation139 Neutral About taylorsnead - RankMember Multiple Scripting Languages With Identical User-work taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingI'm going to bump this, because I still haven't figured it out, and I'm still trying to implement it. I'm able to make a system for multiple languages, but it then forces the programmer to rebind their classes for each language. So, I was attempting to do something like what Hodgman suggested, but I don't really know how I'd reaccess the data later, since it would be a solely automatic grabbing and using of the data and I can't store a type as a variable so that it's known what type to bind it as. Once I can have the data grabbed later on in a separate function with the correct type and stuff, then I can have an easily extensible system to add new languages that work with no changes to existing binding code. Maybe it would be better to bind one language (eg. Squirrel) and use its dynamic typing to create a binding system there that routes back to C++, allowing someone to bind their classes in either Squirrel or C++? Can't resolve problematic dlopen() call. taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingBump. Still not solved, and not sure how to attempt to. Can't resolve problematic dlopen() call. taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingI had already done that with relative and absolute directories, the correct dir, and setting the dir to empty. Either way doesn't work. Can't resolve problematic dlopen() call. taylorsnead replied to taylorsnead's topic in General and Gameplay Programminggetcwd(), in fact, does output the correct directory when launching from terminal and not the IDE (Which is what I do anyway). Can't resolve problematic dlopen() call. taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingNow, using full strace (just "strace ./Launcher"), it seems that it detects the file correctly with an absolute path, but then it does a few things, and then it tries opening the file with some relative directory that wouldn't be correct anyways. This is the part of the output that applies: brk(0) = 0x1310000 brk(0x1331000) = 0x1331000 open("/home/taylorsnead/Documents/ShadowFox/NewEngine/BinLinux/SFGame.so", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\300!\0\0\0\0\0\0"..., 832) = 832 fstat(3, {st_mode=S_IFREG|0755, st_size=27024, ...}) = 0 mmap(NULL, 2122168, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f8d2ab03000 mprotect(0x7f8d2ab09000, 2093056, PROT_NONE) = 0 mmap(0x7f8d2ad08000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x5000) = 0x7f8d2ad08000 close(3) = 0 open("../../BinLinux//SFEngine.so", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) munmap(0x7f8d2ab03000, 2122168) = 0 fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f8d2bcfe000 write(1, "Failed to load /home/taylorsnead"..., 82Failed to load /home/taylorsnead/Documents/ShadowFox/NewEngine/BinLinux/SFGame.so ) = 82 write(1, "../../BinLinux//SFEngine.so: can"..., 87../../BinLinux//SFEngine.so: cannot open shared object file: No such file or directory ) = 87 But, I don't know where it gets this new directory. Even using a relative directory, as with Boost.Filesystem, it sees the file, but dlopen (I guess) just converts it to a directory relative to the code/project files, which won't work with the executable. I'm using the same compiler for the libraries and executable, all (I guess, I don't specify to the compiler (G++)) 32-bit. Trying "LD_PRELOAD=SFGame.so /bin/ls" just says that SFGame.so can't be preloaded: ERROR: ld.so: object 'SFGame.so' from LD_PRELOAD cannot be preloaded: ignored. Using LD_PRELOAD with the path to Launcher instead of ls makes it run Launcher, which of course fails. Setting it without a path doesn't change the result of the strace of Launcher. Can't resolve problematic dlopen() call. taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingOh, I mean, Code::Blocks has an option for "Execution working dir", and I tried it empty, but the same problem occurred. Running the binary result either through the IDE or from the terminal makes no difference, unless I compile it via terminal. That is why the option seemed suspicious to me. Through this, I should think I do understand "working directory" as it would be used for file paths within the executable. Despite these, I don't know how the problem persists even using an absolute directory to the file, but I feel it's something with libdl.so, and less to do with working directory, but I have no idea what to do about it. Can't resolve problematic dlopen() call. taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingOkay, it seems like that was correct, though it seems that I do have to use an absolute path to the file, it works when compiled via terminal using g++-4.7, not using LD_LIBRARY_PATH (though I guess that would allow me to use relative paths). Code::Blocks still has the problem with the execution directory empty. Any thoughts on how to fix this? I guess I could just compile my Launcher with the terminal when I need to, but I'd prefer to be able to compile with my IDE (especially since it works fine on Windows, I feel like there should be an easy way to resolve this). It also seems like the same problem occurs with two dynamic libraries linked at compile/link time (of course, through Code::Blocks) (I use my Launcher as an executable to run my Game.so, which uses Engine.so to run and control the other, lower-level libraries (boost, glfw, alut, etc), so dynamic linking is important (though I use static linking when possible)). Can't resolve problematic dlopen() call. taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingI should have mentioned that, yes, I already tried setting LD_LIBRARY_PATH, and that didn't help either. It seems that at compile-time, the string passing to the dlopen gets set to that path local to the main.cpp. strace shows that it is trying to open that directory, not just displaying it, whereas filesystem is really opening the correct directory (which I already knew since it showed it). I don't know how to get it using the correct path, unless I moved my source to the folder where it should compile, but that seems like a horrible solution. EDIT: Or it has something to do with the "Execution Working Dir" Option in Code::Blocks. I've tried setting that relatively and absolutely to BinLinux, but no change. Can't resolve problematic dlopen() call. taylorsnead posted a topic in General and Gameplay ProgrammingI've been working mainly in Windows with VC11, but a few days ago switched to using MinGW (I had already been planning on switching, I just liked Visual Studio's plugins too much). Very quickly, I then installed GCC/G++ 4.7 on my Linux (Mint). Making a launcher executable for my library (This makes it easier for separation, or changing which library is launched without recompiling a large amount of code), I use Boost.Extension's shared_library (which simply uses LoadLibrary and dlopen (depending on the platform)) to load my dynamic/shared library (SFGame.so). This worked great on windows with both compilers, but on Linux, dlopen will fail however I use the path. Using the same path, Boost.Filesystem confirms (through the application) that the file can be accessed with the paths I'm using. My simple code: ("<" and ">" replaced with "^") [source lang="cpp"]#include "iostream" #include "functional" #include "boost/extension/shared_library.hpp" #include "boost/filesystem.hpp" #if _WIN32 || _WIN64 # define EXT ".dll" #elif __APPLE__ # define EXT ".dylib" #elif __linux # define EXT ".so" #endif int main( void ) { using namespace boost::extensions; using namespace boost::filesystem; std::string libpath = "./SFGame.so"; path pfile( libpath ); if( exists( pfile ) ) { std::cout ^^ "Game library: " ^^ complete( pfile ).generic_string() ^^ " exists\nSize: " ^^ file_size( pfile ) ^^ "\n"; } shared_library lib( libpath ); if( !lib.open() ) { std::cout ^^ "Failed to load " ^^ libpath ^^ "\n" ^^ dlerror() ^^ "\n"; return 0; } lib.get^void^( "Launch" )(); return 1; }[/source] This same code works perfectly on Windows, as I said. My output: ../../BinLinux//SFGame.so: cannot open shared object library or: SFGame.so: cannot open shared object library depending on whether I use "./SFGame.so" (I assume because my Code::Blocks project file and main.cpp are in "Engine/Code/Game/" and SFGame.so is in "Engine/BinLinux/") or "SFGame.so". I can use the full path from "complete(pfile).generic_string()", which gives the same dir in the error as "./SFGame.so". Any ideas on how I could fix this from failing EVERY time? I even tried linking Launcher to Engine.so in the compiler (GNU GCC (well, g++) within Code::Blocks), but no dice. Multiple Scripting Languages With Identical User-work taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingI understand both of your concepts. I tried to implement both. For the first (Ashaman73) concept, I did it like so: [source lang="cpp"]//SClass has Var, Func, Prop, and Bind functions without implementations //SqClass is a child and implements the functions for squirrel //ScriptSystem::NewClass() returns a pointer to a child SqClass or eg. LuaClass, based on mLang (set by SetLang(); ScriptSystem::SetLang("Squirrel"); SClass $Player# & scp = ScriptSystem::NewClass<Player>(); scp.Var("Health", &Player::mHealth); scp.Bind("Player"); Script& sqs = ScriptSystem::NewScript(); sqs.Compile("Test.nut"); sqs.Run();[/source] Now, this should basically work, except that if I want to, say, shut off the Squirrel VM and launch the Lua VM, I have to rebind those classes. Using something closer to the other given concept (Hodgman), I'd be able to bind once, and it should keep a list of the classes to be bound in ScriptSystem (Since then the SClass holds actual data), then on VM binding (called just before script launching begins), it would take the data from all SClass instances in the list, using it to create VM specific Classes, binding their members and vars, then binding the actual class (Also, then it's easy to remove them from the bind list). The only problem is, I can't really figure out how I should manage the structures to use for data containment, and later usage for binding to the specific VM. I was thinking something like this: [source lang="cpp"] struct VarData { string label; void* ref; }; struct ClassData { vector $VarData# vars; }; struct SClass { template $class T, typename V# void Var(string label, V T::*val) { VarData newvar; newvar.label = label; newvar.ref = val; data.vars.push_back(newvar); } void Bind(string label); ClassData data; }; [/source] But, the problem is about using that given data later. [source lang="cpp"]Class $Player# cls; for(int i=0; i $ play.data.vars.size(); ++i) { cls.Var(play.data.vars[i].label, play.data.vars[i].ref); RootTable().Bind("NameHere", cls); }[/source] ("<>" are replaced by "$#", the code block doesnt like those characters, for some reason) Something like that for Squirrel, except I can't use the void pointer directly, so would I use a different type for storage, or how can I cast to the correct type for this situation? I'm just not really sure how I'd approach it. Multiple Scripting Languages With Identical User-work taylorsnead posted a topic in General and Gameplay ProgrammingI am attempting to make a system that would allow a user (in C++) to bind classes to their scripting language of choice, then compile the script and run it. The primary language I am using for any scripting needs is Squirrel, but I want to be able to switch languages at runtime (possibly with an enum), and using the [b]same[/b] code, bind to, say, Python. I was thinking of doing it by having a class for each language's Class (eg. has Var, Func, Prop, Bind, etc, functions for binding) and a class for it's Script (eg. Compile and Run functions), then instantiating those runs through the Subsystem (which changes based on the enum to a child class with creation methods), which passes back a Class* pointer or Script* pointer, but I'd prefer it to be implicit. Like this: [source lang="cpp"]void BindPlayer() { scriptLang = "Squirrel"; // SClass is for ScriptClass, the parent top class, not for Squirrel specifics SClass<Player> pclass; pclass.Var("TestVar", &Player::TestVar); // Bind other vars/funcs/props pclass.Bind("Player"); Script scr; scr.Compile("TestPlayer.nut"); scr.Run(); scriptLang = "Python"; // Do the bind again, same code. Script scrp; scrp.Compile("TestPlayer.py"); scrp.Run(); }[/source] How feasible is this method; if at all, how exactly would I go about the implicit creation via another class? If that method wouldn't work well, then what would? OpenGL New to OpenGL. Trying to figure it all out. taylorsnead replied to taylorsnead's topic in Graphics and GPU ProgrammingThanks. So for using the struct as my vertices, to specify offset, I can simply do that with glVertexAttribPointer? Like this? [source lang="cpp"] glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, mesh->mVertexId); glVertexAttribPointer( // Vertex Position 0, // The attribute we want to configure 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 52, // stride (void*)0 // array buffer offset ); // Then the next item in my struct: (The struct is padded to 64-byte, values are float(4-byte)) glEnableVertexAttribArray(1); glVertexAttribPointer( // UVs 1, // The attribute we want to configure 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 56, // stride (void*)12 // array buffer offset );[/source] I think most of what I was asking is answered. Do I still have to do the ClientState enabling/disabling? Lastly, I am just confused a bit with matrix manipulation. As I understand, I would have my matrix, use GLMs translate, rotate, and scale functions upon it (well, for rotation its easier to me to simply use matrix *= mat4_cast(quatrot);) then pass the "MVP" to the shader. This MVP stands for Projection * View * Model, correct? So, model would be the transform of my object, projection is my perspective matrix from the camera, and view is the transformation matrix of the camera (created using lookAt())? Then set the position in the shader with: gl_Position = MVP; If that is all correct, then my inquiries for now seem to be answered. Almost forgot, know of any reasons shaders/GLSL can be better for certain things than C++? I know that it runs on the GPU, but for what things is that an advantage? OpenGL New to OpenGL. Trying to figure it all out. taylorsnead posted a topic in Graphics and GPU ProgrammingI have looked around at tutorials for OpenGL, and found that I like these: [url=""][/url] alot. I'm not sure if those have the best methods though. My real questions are a range. First of all, using VBOs, what would be the best method of updating the data each frame? Initializing a mesh to render(not every frame): I don't believe there is much of a problem or difference between using 3-4 buffers of arrays and using 1 buffer of a struct array. Then, indexing that vertex data. Lastly, creating pointers for each data area of a vertex (position, UV, normals, color), and sending the buffered indices. [source lang="cpp"]glGenBuffers(1, &mesh->mVertexId); glBindBuffer(GL_ARRAY_BUFFER, mesh->mVertexId); // Bind the buffer (vertex array data) glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * mesh->mVertices.size(), NULL, GL_STATIC_DRAW); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vertex) * mesh->mVertices.size(), &mesh->mVertices); IndexArray(mesh->mVertices, mesh->mIndex); glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), OFFSET(12)); glNormalPointer(GL_FLOAT, sizeof(Vertex), OFFSET(20)); glColorPointer(4, GL_FLOAT, sizeof(Vertex), OFFSET(32)); glVertexPointer(3, GL_FLOAT, sizeof(Vertex), OFFSET(0)); glGenBuffers(1, &mesh->mVertexArrayId); // Generate buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->mVertexArrayId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh->mIndex.size()/3 * sizeof(byte), &mesh->mIndex, GL_STATIC_DRAW); mMeshBuffer.push_back(meshr); //Dont mind "meshr" its something else containing the Mesh*[/source] Those tutorials do it similarly, but do away with the "pointer" function calls and split each area of vertex data into separate buffers. I think what I'm doing is better, but I could be wrong? Now, for per-frame rendering stuff, I will have either a separate VBO for each mesh, or find a way to batch certain ones together, keeping them independent for transformation. This is what I have gathered as what seemed to be well (in my function called each frame): [source lang="cpp"] Mesh* mesh = mMeshBuffer[i]->GetMesh(); glBindBuffer(GL_ARRAY_BUFFER, mesh->mVertexId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mMeshBuffer[i]->GetMesh()->mVertexArrayId); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glUseProgram(mesh->mShader.id); glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), OFFSET(12)); glNormalPointer(GL_FLOAT, sizeof(Vertex), OFFSET(20)); glColorPointer(4, GL_FLOAT, sizeof(Vertex), OFFSET(32)); glVertexPointer(3, GL_FLOAT, sizeof(Vertex), OFFSET(0)); glDrawElements(GL_TRIANGLES, mesh->mVertices.size(), GL_INT, OFFSET(0)); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);[/source] While those tuts do it differently. Many sources that i've seen, in fact, have different methods here for rendering their buffered vertex data. Like, sending the data to the shader with glVertexAttribPointer and again, not using glXXXXPointer. Mind you, I haven't finished the series yet, and the code of them is fairly static (understandably), so it's long and harder for me to understand. I'm here to ask which of any seems to be the best (yet fairly manageable in easiness) method for rendering a mesh (whose vertices wont change) with a dynamic transform (I assume glRotatef, glTranslatef, and glScalef work okay; or are those as obsolete as straight drawing (function call for each vertex)? If so, shedding light on matrix manipulation with GL'd be nice), texture (simple for now), normals, and, possibly, a shader (I'm not completely sure I know what a shader entails (and it's advantages over using C++ for certain things) when applying it to a mesh) in a VBO. Also, any useful information/tips about related things would help. Thanks. EDIT: Also, glBufferData vs glBufferData (as NULL/nullptr) with glBufferSubData? Game Engine Basis Choices taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingI realize its hard. I think reworking something existing to be how I want it may be more annoying than building my own. That's what I was trying to get opinions about: which would be harder to work into how I want and still have good graphics features and performance. Game Engine Basis Choices taylorsnead replied to taylorsnead's topic in General and Gameplay ProgrammingEveryone in that thread said that Unity Pro is required, which costs $1500. I'm looking for something free.
https://www.gamedev.net/profile/200530-taylorsnead/?tab=topics
CC-MAIN-2018-05
refinedweb
3,118
54.32
This page is intended to help the beginner get a handle on scipy and be productive with it as fast as possible. Contents What are scipy, numpy, matplotlib ? Python is a general purpose programming language. It is interpreted and dynamically typed and is very suited for interactive work and quick prototyping, while being powerful enough to write large applications in. Numpy is a language extension that defines the numerical array and matrix type and basic operations on them. Scipy is another language extension that uses numpy to do advanced math, signal processing, optimization, statistics and much more. Matplotlib is a language extension to facilitate plotting. What are they useful for ? Scipy and friends can be used for a variety of tasks: - First of all, they are great for performing calculation relying heavily on mathematical and numerical operations. They can work natively with matrices, perform operations on them, find eigenvectors, compute integrals, solve differential equations. Using ipython makes interactive work easy. Data processing, exploration of numerical models, trying out operations on the fly allows to go quickly from an idea to a result (see the article on ipython). The matplotlib module produces high quality plots. With it you can turn your data or your models into figures for presentations or articles. No need to do the numerical work in one program, save the data, and plot it with another program. Python has many advanced modules to build interactive applications (for instance TraitsUI or wxPython). Using scipy with these is the quickest way to build a scientific application. How to work with scipy Python is a language, it comes with several user interfaces. There is no single program that you can start and that gives an integrated user experience. Instead of that there are dozens of way to work with python. The most common is to use the advanced interactive python shell ipython to enter commands and run scripts. Scripts can be written with any text editor, for instance SPE, PyScripter, or even notepad, emacs, or vi. Neither scipy nor numpy provide, by default, plotting functions. They are just numerical tools. The recommended plotting package is matplotlib. Under windows all these tools are provided by the enthon python distribution (), for more instruction on installing these see the Installing SciPy section of this site. Learning to use scipy The quick way to get working with scipy is probably this tutorial focused on interactive data analysis. To learn more about the python language, the python tutorial will make you familiar with the python syntax and objects. You can download this tutorial from . Dave Kuhlman's course on numpy and scipy is another good introduction: The Documentation and Cookbook sections of this site provide more material for further learning. An Example Session Interactive work Let's look at the Fourier transform of a square window. To do this we are going to use ipython, an interactive python shell. As we want to display our results with interactive plots, we will start ipython with the "-pylab" switch, which enables the interactive use of matplotlib. $ ipython -pylab Python 2.5.1 (r251:54863, May 2 2007, 16:27:44) Type "copyright", "credits" or "license" for more information. IPython 0.7.3 --)'. Ipython offers a great many convenience features, such as tab-completion of python functions and a good help system. In [1]: %logstart Activating auto-logging. Current session state plus future input saved. Filename : ipython_log.py Mode : rotate Output logging : False Raw input log : False Timestamping : False State : active This activates logging of the session to a file. The format of the log file allows it to be simply executed as a python script at a later date, or edited into a program. Ipython also keeps track of all inputs and outputs (and makes them accessible in the lists called In and Out), so that you can start the logging retroactively. In [2]: from scipy import * Since numpy and scipy are not built into python, you must explicitly tell python to load their features. Scipy provides numpy so it is not necessary to import it when importing scipy. Now to the actual math: In [3]: a = zeros(1000) In [4]: a[:100]=1 The first line simply makes an array of 1000 zeros, as you might expect; numpy defaults to making these zeros double-precision floating-point numbers, but if I had wanted single-precision or complex numbers, I could have specified an extra argument to zeros. The second line sets the first hundred entries to 1. I next want to take the Fourier transform of this array. Scipy provides a fft function to do that: In [5]: b = fft(a) In order to see what b looks like, I'll use the matplotlib library. If you started ipython with the "-pylab" you do not need to import matplotlib. Elsewhere you can import it with: "from pylab import *", but you will not have interactive functionality (the plots displays as you create them). In [6]: plot(abs(b)) Out[6]: [<matplotlib.lines.Line2D instance at 0xb7b9144c>] In [7]: show() This brings up a window showing the graph of b. The show command on input "[7]" is not necessary if you started ipython with the "-pylab" switch. I notice that it would look nicer if I shifted b around to put zero frequency in the center. I can do this by concatenating the second half of b with the first half, but I don't quite remember the syntax for concatenate: In [8]: concatenate? Type: builtin_function_or_method Base Class: <type 'builtin_function_or_method'> String Form: <built-in function concatenate> Namespace: Interactive Docstring: concatenate((a1, a2, ...), axis=0) Join arrays together. The tuple of sequences (a1, a2, ...) are joined along the given axis (default is the first one) into a single numpy array. Example: >>> concatenate( ([0,1,2], [5,6,7]) ) array([0, 1, 2, 5, 6, 7]) In [9]: f=arange(-500,500,1) In [10]: grid(True) In [11]: plot(f,abs(concatenate((b[500:],b[:500])))) Out[11]: [<matplotlib.lines.Line2D instance at 0xb360ca4c>] In [12]: show() This brings up the graph I wanted. I can also pan and zoom, using a set of interactive controls, and generate postscript output for inclusion in publications (If you want to learn more about plotting, you are advised to read the matplotlib tutorial). Running a script When you are repeating the same work over and over, it can be useful to save the commands in a file and run it as a script in ipython. You can quit the current ipython session using "ctrl-D" and edit the file ipython_log.py. When you want to execute the instructions in this file you can open a new ipython session an enter the command "%run -i ipython_log.py". It can also be handy to try out a few commands in ipython, while editing a script file. This allows to try the script line by line on some simple cases before saving it and running it. Some notes about importing The following is not so important for you if you are just about to start with scipy & friends and you shouldn't worry about it. But it's good to keep it in mind when you start to develop some larger applications. For interactive work (in ipython) and for smaller scripts it's ok to use from scipy import *. This has the advantage of having all functionallity in the current namespace ready to go. However, for larger programs/packages it is advised to import only the functions or modules that you really need. Lets consider the case where you (for whatever reason) want to compare numpy's and scipy's fft functions. In your script you would then write 1 from numpy.fft import fft # import from module numpy.fft 2 from scipy import fft as scipy_fft # import scipy's fft implementation and rename it; equivalent: from scipy.fftpack import fft The advantage is that you can, when looking at your code, see explicitly what you are importing, which results in clear and readable code. Additionally, this is often faster than importing everything with import *, especially if you import from a rather large package like scipy. However, if you use many different numpy functions, the import statement would get very long if you import everything explicitly. But instead of using import * you can import the whole package. 1 from numpy import * # bad 2 from numpy import fft, abs, concatenate, sin, pi, dot, amin, amax, asarray, cov, diag, zeros, empty, exp, eye, kaiser # very long 3 import numpy # good 4 # use numpy.fft.fft() on array 'a' 5 b = numpy.fft.fft(a) This is ok since usually import numpy is quite fast. Scipy, on the other hand, is rather big (has many subpackages). Therefore, from scipy import * can be slow on the first import (all subsequent import statements will be executed faster because no re-import is actually done). That's why the importing of subpackages (like scipy.fftpack) is disabled by default if you say import scipy, which then is as fast as import numpy. If you want to use, say scipy.fftpack, you have to import it explicitly (which is a good idea anyway). If you want to load all scipy subpackges at once, you will have to do import scipy; scipy.pkgload(). For interactive sessions with Ipython, you can invoke it with the scipy profile (ipython -p scipy), which loads all of scipy for you. For a general overview of package structuring and "pythonic" importing conventions, take a look at this part of the Python tutorial.
http://scipy.org/Getting_Started
crawl-001
refinedweb
1,593
62.98
A bucket is a container for objects stored in OSS. Every object is contained in a bucket. This topic describes how to delete a bucket. For the complete code used to create a bucket, visit GitHub. Note - Before you delete a bucket, you must delete all objects in the bucket, LiveChannel objects, and fragments generated by multipart uploads. For more information about deleting a LiveChannel object, see LiveChannel. - To delete the parts generated by multipart upload, call ListMultipartUploads to list all the parts, and then call AbortMultipartUpload to delete these parts. The following code provides an example on how to delete a bucket: using Aliyun.OSS; // Initialize an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret); // Delete the bucket. public void DeleteBucket(string bucketName) { try { client.DeleteBucket(bucketName); Console.WriteLine("Delete bucket succeeded"); } catch (Exception ex) { Console.WriteLine("Delete bucket failed. {0}", ex.Message); } } For more information about how to delete a bucket, seeDeleteBucket.
https://www.alibabacloud.com/help/doc-detail/148513.htm
CC-MAIN-2020-34
refinedweb
155
52.46
Easy Eye an easy eye calculator, includes large black font on green background. The human eye is peaked for yellow/green and various ergonomic studies have shown that black font on green background is one of the easiest to read. My small notepad has a linked script and icon for easy eye calculator, posted on the windows desktop of small screen, 22 by 12 cm. One advantage of the easy eye calculator is that the calculations are posted to a console window as a sort of paper tape. The easy eye calculations can be cut and paste, saved to a word processor. The easy eye calculator is a compilation of several eval calculators on the TCL wiki.Improvements: The math operator notation from "namespace path {::tcl::mathop ::tcl::mathfunc}" is available on the green screen. Once the math expression is typed from the keyboard into the green window, the mouse pointer can be set down in the green calculator window and the expression altered. For example, [* 2. 5.0 ] can be altered to [* 2. 5.7777] on the keyboard. I have been unable to screen grab or screen copy the results in the green window, maybe somebody can show how to achieve this. I understand that the TCL console is compiled in a different interpreter or thread than the TCL application, but I would like to forward complex math expressions from the console to the green window. Possibly, entering one symbol like > (right arrow) or ^ (hat) to transfer and expression to the green window. For example, type "> [* 2. 5.7777 ]" or > 2./5. on the keyboard and transfer expression to the green screen. Also, type erase on console and clear green screen. console, > 1/9 transfer entries to green screen Testcase 2 console, e> erase green screen Testcase 3 console, q> quits program Testcase 4 console, > (2*3)+(3*3) transfer entries to green screen Screenshots Section figure 1. References: - Ask Dr. Math, 03/15/2001, material left on roll. - console eval - A little calculator - tclsh as a powerful calculator - - , 1924 - expr - Importing expr functions - RPN - Parsing Polish notation - Category Package - Importing expr functions, part 2 - Call Procedure Like Fortran Example - namespace - package - - tcl::mathop - tcl::mathfunc - Namespace resolution of Variables & Procedures - [1] - A little calculator - A minimal console Appendix Code edit appendix TCL programs and scripts # pretty print from autoindent and ased editor # easy eye calculator, large black type on green # written on Windows XP on eTCL # working under TCL version 8.5.6 and eTCL 1.0.1 # gold on TCL WIKI , 2may2014 package require Tk package provide calculatorliner 1.0 namespace path {::tcl::mathop ::tcl::mathfunc} namespace eval liner { console show proc initdisplay {} { pack [entry .e -textvar e -width 50 ] bind .e <Return> {puts $e;catch {expr[string map {/ *1./} $e]} res; set e $res;puts $res} ;# RS & FR } } proc linershell {} { namespace import liner::* liner::initdisplay .e configure -bg palegreen .e configure -fg black .e configure -font {helvetica 50 bold} .e configure -highlightcolor tan -relief raised -border 30 focus .e wm title . "Easy Eye Calculator" proc pi {} { expr acos(-1) } proc > {args} { global e set e $args} proc e> {args} { global e set e ""} proc q> {args} { exit} } bind Label <1> {focus %W} bind Label <FocusIn> { %W configure -background SystemHighlight -foreground SystemHighlightText } bind Label <FocusOut> { %W configure -background SystemButtonFace -foreground SystemButtonText } bind Label <Control-c> { clipboard clear clipboard append [%W cget -text] } bind Label <Control-p> { #clipboard clear clipboard append [%W cget -text] } bind Label <Control-q> { #clipboard exit clipboard append [%W exit] } console show console eval {.console config -bg palegreen} console eval {.console config -font {fixed 20 bold}} console eval {wm geometry . 40x20} linershell gold This page is copyrighted under the TCL/TK license terms, this license Please place any comments here, Thanks.
http://wiki.tcl.tk/39927
CC-MAIN-2016-44
refinedweb
627
55.13
> 29a_fu.zip > 29A-7.006 How to break the rules with the class libraries roy g biv / 29A), and world's first viruses that can convert any data files to infectable objects (Pretext). Author of various retrovirus articles (eg see Vlad #7 for the strings that make your code invisible to TBScan). Went to sleep for a number of years. This is my first virus for .NET. It is the world's first 32/64-bit parasitic EPO .NET virus. :) Object-oriented language programming At the first look, object-oriented languages in the .NET framework (C#, C++, JScript, and Visual Basic) seem to be very strict. There are no pointers in JScript and Visual Basic, and they are limited in C# and C++. Type conversion is also restricted. BitConverter class Imagine that we have an array of bytes (because only a byte array is allowed for the buffer when accessing files in the .NET framework). We have read some bytes from the file and now we want to check for the 'MZ' signature (assuming little-endian machine). In C, we could use: if (*((WORD *) &array[0]) == 0x5a4d) Can we do that in JScript or Visual Basic? No. Can we do that in C++? Yes, but only for unmanaged arrays, which cannot be used with the class libraries. Can we do it in C#? No (really yes, but it requires "Unsafe coding", which causes other problems). We can form the word from the array like this: if (((array[1] << 8) + array[0]) == 0x5a4d) //C#, C++, JScript if (((array(1) * &h100) + array(0)) = &h5a4d) then 'Visual Basic but that requires lots of bytes of code each time to do that. Fortunately, the class libraries contain a class that exposes methods for exactly this kind of data access. The class is called BitConverter, and the method we can use here is called ToInt16(). It takes two parameters: the array and the offset. So now our code can be replaced by: if (BitConverter.ToInt16(array, 0) == 0x5a4d) //C#, JScript if (BitConverter::ToInt16(array, 0) == 0x5a4d) //C++ if (BitConverter.ToInt16(array, 0) = &h5a4d) then 'Visual Basic Nice. The class exposes other methods, too, such as ToInt32() and ToInt64(), and also versions for unsigned numbers (ToUInt16(), etc). Marshal class Now we want to write large values into a byte array. In C, we could use *((DWORD *) &array[0]) = dword; In C#, C++, and JScript, we can store a dword in the array like this: array[0] = (Byte) (dword); array[1] = (Byte) (dword >> 8); array[2] = (Byte) (dword >> 0x10); array[3] = (Byte) (dword >> 0x18); In Visual Basic, we can store a dword in the array like this: array(0) = dword mod &h100 array(1) = (dword \ &h100) mod &h100 array(2) = (dword \ &h10000) mod &h100 array(3) = (dword \ &h1000000) mod &h100 but that requires too many instructions and too many bytes of code. The better way is to use the Marshal class. It allows us to copy data between managed data types (.NET base types) and unmanaged data types (eg process memory). It can also copy from one managed type to another managed type, but this use is not documented. The method that we can use here is called WriteInt32(). It takes three parameters: the array, the offset in the array, and the value. So now our code can be replaced by: Marshal.WriteInt32(array, 0, dword); //C#, JScript Marshal::WriteInt32(array, 0, dword); //C++ Marshal.WriteInt32(array, 0, dword) 'Visual Basic Much better. Accessing process memory is easy, too. The Process class exists for that purpose. Let's get our module handle: IntPtr ourbase = Process.GetCurrentProcess().MainModule.BaseAddress; //C# IntPtr ourbase = Process::GetCurrentProcess()->get_MainModule()->get_BaseAddress(); //C++ var ourbase : IntPtr = Process.GetCurrentProcess().MainModule.BaseAddress //JScript dim ourbase as IntPtr : Process.GetCurrentProcess().MainModule.BaseAddress 'Visual Basic Great! But what's an IntPtr? Marshal class again The IntPtr type is a special managed type whose size is platform-specific. That means that it is 32 bits large on a 32-bit platform, and 64-bits large on a 64-bit platform. The Marshal methods require an IntPtr as the object to use for reading and writing unmanaged memory. IntPtrs do not support operators such as + and - (they are like void * in C and C++), but since the Marshal methods require an offset, this is usually okay. For example, we can read the lfanew field without trouble: Int32 lfanew = Marshal.ReadInt32(ourbase, 0x3c); //C# Int32 lfanew = Marshal::ReadInt32(ourbase, 0x3c); //C++ var lfanew : Int32 = Marshal.ReadInt32(ourbase, 0x3c) //JScript dim lfanew as Int32 : Marshal.ReadInt32(ourbase, &h3c) 'Visual Basic and then read bytes in the PE header: Int32 tlsrva = Marshal.ReadInt32(ourbase, lfanew + 0xc0); //C# Int32 tlsrva = Marshal::ReadInt32(ourbase, lfanew + 0xc0); //C++ var tlsrva : Int32 = Marshal.ReadInt32(ourbase, lfanew + 0xc0) //JScript dim tlsrva as Int32 : tlsrva = Marshal.ReadInt32(ourbase, lfanew + &hc0) 'Visual Basic But what if we want to copy any number of bytes? There is a Copy() method, and it takes four parameters: the source array, the destination array, the offset in destination array, and the number of bytes to copy. It does not support an offset in the source array, so we need to find a way to apply the + operator to a IntPtr. Fortunately, the Marshal class exposes a method called ReadIntPtr(), which can convert a Int32 to a IntPtr, but this usage is also not documented. To make our pointer, we convert our old IntPtr into a Int32 by using the ToInt32() method, then add the value that we need, then pass the result to the ReadIntPtr() method, using an offset of 0: IntPtr tlsva = Marshal.ReadIntPtr(ourbase.ToInt32() + tlsdata, 0); //C# IntPtr tlsva = Marshal::ReadIntPtr(__box(ourbase.ToInt32() + tlsdata), 0); //C++ var tlsva : IntPtr = Marshal.ReadIntPtr(ourbase.ToInt32() + tlsdata, 0) //JScript dim tlsva as IntPtr : tlsva = Marshal.ReadIntPtr(ourbase.ToInt32() + tlsdata, 0) 'Visual Basic For 64-bit platforms, there is a ToInt64() method, and the ReadIntPtr() method can also convert an Int64 to an IntPtr. Notice the use of __box for C++. This is required to convert a value into a managed object, which can then be passed to the class libraries. Now we can use the Copy() method to copy bytes from the process memory to our array. Let's copy 0x29a bytes ;) to offset 6: Marshal.Copy(tlsva, array, 6, 0x29a); //C#, JScript Marshal::Copy(tlsva, array, 6, 0x29a); //C++ Marshal.Copy(tlsva, array, 6, &h29a); 'Visual Basic TLS and MSIL I thought to make an interesting W32/MSIL hybrid by using TLS to write the MSIL RVA in the PE header at runtime, but when the MSIL code is run, it fails the StrongName signature verification. Then I tried storing a hard-coded fake RVA in the file, and setting it correctly at runtime, but the MSIL code won't run in that case. Finally, I stored the correct RVA and size in the file, but if TLS code runs on exit, then one of the MSIL dlls waits infinitely for an object that never signals and the application won't terminate. So don't use TLS in MSIL files unless you can solve one of these problems. ;) GetProcAddress() .NET files import functions in a way that is simlar to Windows files. There are AssemblyRefs which are the DLL names, and MemberRefs which are the function names (there are also TypeRefs, and they hold the class names, but they have no equivalent). Let us imagine that we want to display our image base, using only standard library functions (mscorlib). The image base is the BaseAddress property of the ProcessModule class. The ProcessModule class is returned by the MainModule property of the Process class. The Process class is in the System.Diagnostics namespace. The System.Diagnostics namespace is exported by system.dll. Since system.dll is not a standard library, we need to find how to load system.dll and get access to its methods, but without using any function from system.dll to do that. We also have to rely on the GetType() method, instead of casting the result, because casts use references to the dll that exports the class. The .NET equivalent of LoadLibrary() requires the full path of the file to load, if the file is not in the current directory (this is similar to LoadLibrary()). System.dll is in the .NET system directory (which is not the same as the Windows system directory), so we need to find the .NET system directory. We can get the system directory from the full path of mscorlib.dll (equivalent to getting the Windows system directory from the module filename of kernel32.dll). I don't know about any .NET equivalent of GetSystemDirectory(). Here is the code in C#: Type t = typeof(System.Object); //get handle to mscorlib.dll Assembly a = t.Assembly; //get its assembly String s = a.CodeBase; //get full path of mscorlib.dll Here is the code in C++: Type *t = __typeof(System::Object); //get handle to mscorlib.dll Assembly *a = t->Assembly; //get its assembly String *s = a->CodeBase; //get full path of mscorlib.dll Here is the code in JScript: var t : Type = System.Object.GetType() //get handle to mscorlib.dll var a : Assembly = t.Assembly //get its assembly var s : String = a.CodeBase //get full path of mscorlib.dll Here is the code in Visual Basic: dim o as new Object 'create an instance of System.Object dim t as Type : t = o.GetType() 'get handle to mscorlib.dll dim a as [Assembly] : a = t.Assembly 'get its assembly dim s as String : s = a.CodeBase 'get full path of mscorlib.dll Now that we have the full path of mscorlib.dll, we have the .NET system directory. We simply replace "mscorlib.dll" with "system.dll", then load the system.dll. This is the .NET equivalent of LoadLibrary(). Here is the code in C#: s = s.Replace("mscorlib.dll", "system.dll"); //get full path of system.dll a = Assembly.LoadFrom(s); //load assembly from file Here is the code in C++: s = s->Replace("mscorlib.dll", "system.dll"); //get full path of system.dll a = Assembly::LoadFrom(s); //load assembly from file Here is the code in JScript: s = s.Replace("mscorlib.dll", "system.dll") //get full path of system.dll a = Assembly.LoadFrom(s) //load assembly from file Here is the code in Visual Basic: s = s.Replace("mscorlib.dll", "system.dll") 'get full path of system.dll a = [Assembly].LoadFrom(s) 'load assembly from file An assembly is the .NET equivalent of a module handle. Using an assembly, we can get the address of any method, by using the GetType() method and the GetMethod() method. This is the .NET equivalent of GetProcAddress(). Here is the code in C#: t = a.GetType("System.Diagnostics.Process"); //get class (Process) MethodInfo m = t.GetMethod("GetCurrentProcess"); //get method interface Here is the code in C++: t = a->GetType("System.Diagnostics.Process"); //get class (Process) MethodInfo *m = t->GetMethod("GetCurrentProcess"); //get method interface Here is the code in JScript: t = a.GetType("System.Diagnostics.Process") //get class (Process) var m : MethodInfo = t.GetMethod("GetCurrentProcess") //get method interface Here is the code in Visual Basic: t = a.GetType("System.Diagnostics.Process") 'get class (Process) dim m as MethodInfo : m = t.GetMethod("GetCurrentProcess") 'get method interface Now we can call our method. Here is the code in C#: Object o = m.Invoke(null, null); //call GetCurrentProcess() Here is the code in C++: Object *o = m->Invoke(0, 0); //call GetCurrentProcess() Here is the code in JScript: var o : Object = m.Invoke(null, null) //call GetCurrentProcess() Here is the code in Visual Basic: o = m.Invoke(nothing, nothing) 'call GetCurrentProcess() Okay, so now we know how to call a method dynamically. Here is the rest of the code in C#: t = o.GetType(); //get class (Process) PropertyInfo p = C++: t = o->GetType(); //get class (Process) PropertyInfo *p = t->GetProperty("MainModule"); //get property interface o = p->GetValue(o, 0); //get MainModule value t = o->GetType(); //get class (ProcessModule) p = t->GetProperty("BaseAddress"); //get property interface o = p->GetValue(o, 0); //get BaseAddress value Here is the rest of the code in JScript: t = o.GetType() //get class (Process) var p : PropertyInfo = Visual Basic: t = o.GetType() 'get class (Process) dim p as PropertyInfo : p = t.GetProperty("MainModule") 'get property interface o = p.GetValue(o, nothing) 'get MainModule value t = o.GetType() 'get class (ProcessModule) p = t.GetProperty("BaseAddress") 'get property interface o = p.GetValue(o, nothing) 'get BaseAddress value So much code for such a simple thing. Anyway... Let's print the value in C#: Int32 i = ((IntPtr) o).ToInt32(); //convert to Int32 Console.WriteLine("{0:x}", i); //display it in hex Let's print the value in C++: Int32 i = dynamic_cast (o)->ToInt32(); //convert to Int32 Console.WriteLine("{0:x}", __box(i)); //display it in hex Let's print the value in JScript: var i : Int32 = o.ToInt32() //convert to Int32 Console.WriteLine("{0:x}", i) //display it in hex Let's print the value in Visual Basic: dim i as Int32 : i = DirectCast(o, IntPtr).ToInt32() 'convert to Int32 Console.WriteLine("{0:x}", i) 'display it in hex This code also requires the #US stream, because it contains strings. It is possible to build strings dynamically to avoid creating the stream, but that requires still more code. However, if you need to access external functions, then this is how it is done. Building strings dynamically In the object-oriented world, type conversion usually happens transparently. This means that a Byte value can be converted to a Char simply by storing the Byte value in the Char variable. We can make strings by storing Bytes in a Char array. We can write multiple Bytes at a time with the Marshal class methods, such as WriteInt32() and WriteInt64(). Here is an example of that: Char[] ourstr = new Char[8]; Marshal.WriteInt64(ourstr, 0, 0x4139322f626772); //C# Char ourstr __gc[] = new Char[8]; Marshal::WriteInt64(ourstr, 0, 0x4139322f626772); //C++ var ourstr : Char[] = new Char[8] : Marshal.WriteInt64(ourstr, 0, 0x4139322f626772) //JScript dim ourstr(8) as Char : Marshal.WriteInt64(ourstr, 0, &h4139322f626772) 'Visual Basic Warning: the JScript .NET Compiler version 7.00.9502 (.NET v1.0) 7.10.2292 (.NET v1.1 final beta) and 7.10.3052 (.NET v1.1) has a bug with 64-bit numbers, so the last byte is either lost or damaged (becomes 0x4139322f626774 in the example). I have not found any method to convert multiple Bytes to a character string, without an array. Greets to friendly people (A-Z): Active - Benny - Obleak - Prototype - Ratter - Ronin - RT Fishel - The Gingerbread Man - Ultras - Vecna - VirusBuster - Whitehead rgb/29A mar 2003 iam_rgb@hotmail.com
http://read.pudn.com/downloads60/sourcecode/asm/208767/Articles/29A-7.006__.htm
crawl-002
refinedweb
2,440
67.35
pthread_sigmask() Examine and change blocked signals Synopsis: #include <signal.h> int pthread_sigmask( int how, const sigset_t* set, sigset_t* oset ); Since: BlackBerry 10.0.0. In order to set the signal-blocked mask for a process with a different real or effective user ID, your process must have the PROCMGR_AID_SIGNAL ability enabled. For more information, see procmgr_ability(). You can't block the SIGKILL and SIGSTOP signals. Returns: - EOK - Success. - EINVAL - Invalid how parameter. - EPERM - The calling process doesn't have the required permission; see procmgr_ability(). Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/p/pthread_sigmask.html
CC-MAIN-2019-35
refinedweb
106
54.08
The subject of this week's column is how to manage your appointments using a simple reminder service, the calendar tool.. The calendar package comes with several calendar files, stored in /usr/share/calendar, containing dates for many different occasions: To have calendar output dates from one of these files, put the following in your calendar file: #include <filename> where filename is the name of the calendar file. For example, to output both US holidays and famous births and deaths when you run calendar, put these lines somewhere in your calendar file: #include <calendar.usholiday> #include <calendar.birthday> And, of course, you can. If you run the bash shell, you can put calendar in your .bashrc file to output the day's reminders every time you log in or start a new shell. If you keep your calendar file in a directory other than your home directory, make sure that calendar is called from that directory. For example, if your calendar file is in your ~/doc/etc directory, you'd put the following in your .bashrc file: cd ~/doc/etc; calendar; cd Next week: Contact manager tools under Linux. Michael Stutz was one of the first reporters to cover Linux and the free software movement in the mainstream press. Read more Living Linux columns.
http://archive.oreilly.com/lpt/a/233
CC-MAIN-2015-18
refinedweb
214
62.58
I'm a program beginner. I am using the GPS module to measure latitude and longitude, but at first I was outputting it with a print statement, but this time I want to output latitude and longitude to the log file, and when I tried to run this error A sentence came out. I would like to know why such an error message appears. Applicable source codeApplicable source code TypeError: log () missing 1 required positional argument: 'msg' import serial import micropyGPS import threading import time import logging #Set log output name logger = logging.getLogger ('GPSTest') # logger.setLevel (10) # fh = logging.FileHandler ('GPS.log') logger.addHandler (fh) gps = micropyGPS.MicropyGPS (9, 'dd') # Create a MicroGPS object. # Arguments are time zone time difference and output format def rungps (): # read GPS module and update GPS object s = serial.Serial ('/ dev/serial0', 9600, timeout = 10) s.readline () # discard the first line because halfway data can be read while True: sentence = s.readline (). decode ('utf-8') # Read GPS data and convert it to a string if sentence [0]! = '$': # throw away unless it starts with '$' continue for x in sentence: # Parse the read string and add/update data to the GPS object gps.update (x) gpsthread = threading.Thread (target = rungps, args = ()) # Create a thread to execute the above function gpsthread.daemon = True gpsthread.start () # start thread while True: if gps.clean_sentences>1: # output when some data is collected #h = gps.timestamp [0] if gps.timestamp [0]<24 else gps.timestamp [0]-24 #print ('% 2d:% 02d:% 04.1f'% (h, gps.timestamp [1], gps.timestamp [2])) latlon = (gps.latitude [0], gps.longitude [0]) logger.log (latlon) #rint ('Sea level:% f'% gps.altitude) #rint (gps.satellites_used) #rint ('Satellite Number: (Elevation, Azimuth, Signal to Noise Ratio)') for k, v in gps.satellite_data.items (): print ('% d:% s'% (k, v)) print ('') time.sleep (3.0) Since I wanted only latitude and longitude, I commented out the other output.Supplemental information (FW/tool version etc.) Please provide more information here. - Answer # 1 - Answer # 2 logger.log (latlon) What kind of argument is this log function? And what type does this latlon variable have? Related articles - [python] graphviz output format error - python - about the error log output method - python: an error occurs that the type is different in the output using dict key values - python - i want to solve the problem that i get the error typeerror: xxxxxxxx takes no arguments - python - [pytorch] i want to get the output of the middle layer of a complicated model - python 3x - the output result of the numerical value obtained by web scraping becomes 0 - python - an error occurs in the if statement program that compares the size of numbers - python - sklearn, svm error - about image output of python - extract from python dat data and output to csv - python - error in image binarization using cv2adaptivethreshold function - python - in raspberry pi, the error occurs only in the case of the automatic start program using systemd - python - the py file cannot be executed in the task scheduler 0x2 error - python - categorical_crossentoropy error does not resolve - python - how to resolve attribute error - readcsv error in python - python - i want to display an image with pysimplegui, but an error occurs - python - error when scraping with selenium and firefox - python - typeerror when calculating the array of images called by imageopen () - python - i get an error when connecting to a voice channel with discordpy Trends logis called by log (level, msg, * args, ** kwargs), and the log level is specified as an integer. Since it is logger.setLevel (10), it is output only when a value greater than 10is specified. Level is CRITICAL> ERROR> WARNING> INFO> DEBUGSo It will be said that.
https://www.tutorialfor.com/questions-150803.htm
CC-MAIN-2021-10
refinedweb
608
57.06
Feature #7849closed Symbol#to_str Description Even though a Symbol is not technically an honest-to-goodness String, from the standpoint of simple practicality it would help to have Symbol#to_str defined. There are times when we want an argument to accept a String or a Symbol, but don't really want it to accept any type of object under the sun that responds to #to_s --which is just about anything. This is especially the case when writing DSLs. Having Symbol#to_str is the nice solution to this. Defining Symbol#to_str may be an exception to the rule, but it's one worth making. Updated by Student (Nathan Zook) over 8 years ago Bad idea. to_str should only be defined on things that really are Strings, and Symbol are most definitely not Strings. I agree that Symbol is unusually close to String. If, for your needs, you were to define to_st on String & on Symbol, you could have the utility you desire. Updated by trans (Thomas Sawyer) over 8 years ago If, for your needs, you were to define to_st on String & on Symbol, you could have the utility you desire. Yes, I thought about that. But concluded it was most likely unnecessary complexity when #to_str would work fine. You say "Bad idea". But show me why it is bad idea other then "them's the rules". I tried to think of a problem case, and the only one I can think of is using foo.respond_to?(:to_str) to identify Stringy things and very specifically not meaning to include Symbols. It's possible, but it's a fairly narrow proposition. Not the least reason being that one should never use respond_to? if one does not need to b/c it is a fragile approach. But more significantly, what is more likely to be used? This narrow usecase or Symbol#to_str? Clearly the later by far. And the former is easily solved with && !Symbol === foo. Updated by charliesome (Charlie Somerville) over 8 years ago Symbols are not Strings. I'm afraid this would only serve to blur the line even more. Rubyists need to stop using Symbols where they actually want a String, and vice versa. Strong -1 from me. Updated by drbrain (Eric Hodel) over 8 years ago - Status changed from Open to Rejected You cannot gsub, enumerate characters in or alter encoding of a Symbol, so it is not a string representation. Updated by trans (Thomas Sawyer) over 8 years ago You cannot gsub, enumerate characters in or alter encoding of a Symbol, so it is not a string representation. That the official spec on the definition of a Stringy-thing? That's the "problem" with #to_str, #to_ary, etc. isn't it? There is no absolute interface that dictates their proper use. As long the method returns the expected type then its purely a question of practicality. And I submit that Symobol#to_str is about a practical as it gets.. I think you rejected this issue far too prematurely. Do you guys even know the purpose of dialog? Updated by trans (Thomas Sawyer) over 8 years ago =begin charliesome (Charlie Somerville) Actually, that's exactly what my proposal attempts to address. You don't always have a choice in what type of object you receive, but you want it to become a string. Consider a DSL like Rake's. One could use: task :foo do ... Or task 'foo' do ... Either one is acceptable, and I think it would be overreaching to make people not be able to use a symbol here. On the other hand do we want any object to be acceptable? B/c just about every object responds to #to_s. To avoid this, you would end up with something like: (WARNING! Fugly code ahead.) def task(name) name = (Symbol === name ? name.to_s : name.to_str) ... end There has to be a clearer solution than that. P.S. Just for fun of it I tried this on rake and discovered the Jim decided not to care what get's passed to task. Try this in your Rakefile: desc "OMG!" task Object.new do puts "OMG is right!" end A Duck-typing true beleiver!!! Yea, looks like a bug to me. If the user really needs it they can call #to_s. =end Updated by drbrain (Eric Hodel) over 8 years ago The purpose of to_str, to_int, to_ary and to_sym are to convert string, integer, array and symbol representations to objects of that class. For example: The rope data structure (which supports insertion, deletion and random access) can be used to implement a representation of a ruby string so it would be a good candidate for to_str. A linked-list implementation could be a good candidate for to_ary A roman numeral implementation that does not descend from Numeric represents an integer and would be a good candidate for to_int A string can be used as an identifier (as in rake) so it has to_sym. A symbol, being an identifier alone is not anything like a String. Updated by trans (Thomas Sawyer) over 8 years ago Symbol's not anything like a Proc either, but we have Symbol#to_proc. Put that in your pipe and smoke it ;-) Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/7849
CC-MAIN-2021-25
refinedweb
869
74.29
Add a memory reporter counting Content Parents and the number of IPC messages they have outstanding . RESOLVED FIXED in Firefox 25, Firefox OS v1.1hd Status () People (Reporter: justin.lebar+bug, Assigned: justin.lebar+bug) Tracking Firefox Tracking Flags (blocking-b2g:leo+, firefox23 wontfix, firefox24 wontfix, firefox25 fixed, b2g18 fixed, b2g18-v1.0.0 wontfix, b2g18-v1.0.1 wontfix, b2g-v1.1hd fixed) Details (Whiteboard: [MemShrink][LeoVB+]) Attachments (5 attachments, 2 obsolete attachments) Patch in a moment. Created attachment 774971 [details] [diff] [review] Part 1: Add Unsound_IsClosed() and Unsound_NumQueuedMessages() to AsyncChannel. Created attachment 774973 [details] [diff] [review] Part 2: Add ContentParent::GetAllEvenIfDead(). To do this, we got rid of the explicit removal of a ContentParent from sContentParents in MarkAsDead(). Instead, we rely on LinkedListElement's destructor to remove the ContentParent from sContentParents. Thus, a ContentParent stays in sContentParents until it's destructed. ContentParent::GetAll() checks whether the ContentParent is still alive, so its behavior is unchanged. Attachment #774973 - Flags: review?(benjamin) Created attachment 774974 [details] [diff] [review] Part 3: Add a memory reporter counting ContentParents and the number of IPC messages they have outstanding. I haven't tried compiling this on on Windows, so sorry in advance for typos there. Created attachment 774978 [details] [diff] [review] Part 3, v2: Add a memory reporter counting ContentParents and the number of IPC messages they have outstanding. Tweaked memory reporter path slightly. Attachment #774971 - Attachment is obsolete: true Attachment #774978 - Flags: review?(n.nethercote) Attachment #774974 - Attachment is obsolete: true The memory reporter looks like: > 0 (100.0%) -- queued-ipc-messages > ├──0 (100.0%) ── content-parent((Preallocated), pid=2156, open channel, 0x44874800, refcnt=14) > ├──0 (100.0%) ── content-parent(Homescreen, pid=2086, open channel, 0x46112800, refcnt=14) > └──0 (100.0%) ── content-parent(Usage, pid=2074, open channel, 0x40416400, refcnt=14) I wanted to include the message size here, instead of just the number, but it was somewhat complicated to achieve in a thread-safe manner. The issue is that I don't want to call malloc_usable_size on every Message when it gets enqueued (sorry, premature optimization). But I also don't want to stick a lock around the Channel object, which means that we can't iterate over the Channel's queue from the main thread. This patch is conservative in terms of its perf impact, which is good if we want to take it on branches (we probably do). Comment on attachment 774971 [details] [diff] [review] Part 1: Add Unsound_IsClosed() and Unsound_NumQueuedMessages() to AsyncChannel. Review of attachment 774971 [details] [diff] [review]: ----------------------------------------------------------------- Looks good, a few things though: (The comments in the posix files apply to win as well) ::: ipc/chromium/src/chrome/common/ipc_channel.h @@ +103,5 @@ > + // Unsound_IsClosed() and Unsound_NumQueuedMessages() are safe to call from > + // any thread, but the value returned may be out of date, because we don't > + // use any synchronization when reading or writing it. > + bool Unsound_IsClosed(); > + uint32_t Unsound_NumQueuedMessages(); Nit: Can you mark these as 'const'? ::: ipc/chromium/src/chrome/common/ipc_channel_posix.cc @@ +292,5 @@ > closed_ = false; > #if defined(OS_MACOSX) > last_pending_fd_id_ = 0; > #endif > + output_queue_length_ = 0; This will certainly trigger valgrind/Asan warnings, so we should file a followup to annotate them as known-race. I'm a bit concerned that this will occasionally do really bogus things (like if an optimizer tries to use this location for temporary calculations or something), but at worst we'll just get a flukey memory report... ::: ipc/chromium/src/chrome/common/ipc_channel_posix.h @@ +151,5 @@ > // A generation ID for RECEIVED_FD messages. > uint32_t last_pending_fd_id_; > #endif > > + size_t output_queue_length_; Nit: This should have some kind of comment too, and maybe be named "unsound" also. ::: ipc/glue/AsyncChannel.cpp @@ +279,5 @@ > + > +uint32_t > +AsyncChannel::ThreadLink::Unsound_NumQueuedMessages() > +{ > + return 0; Maybe just comment here that we don't currently care about thread channels but that we may implement this someday? @@ +694,5 @@ > +bool > +AsyncChannel::Unsound_IsClosed() > +{ > + if (!mLink) { > + return false; Is this right? If we don't have a link shouldn't that count as closed? Attachment #774971 - Flags: review+ (In reply to Justin Lebar [:jlebar] from comment #7) > The issue is that I don't want to call malloc_usable_size on every Message > when it gets enqueued (sorry, premature optimization). We can always use the capacity_ member, right? > We can always use the capacity_ member, right? It's true, we could. The trick is ensuring that the capacity doesn't change. We've had a lot of problems with counter-based memory reporters where the value you add in isn't the same as the value you subtract out, so I didn't want to risk it. (Note that we have the same problem with a counter-based malloc_usable_size approach.) Comment on attachment 774978 [details] [diff] [review] Part 3, v2: Add a memory reporter counting ContentParents and the number of IPC messages they have outstanding. Review of attachment 774978 [details] [diff] [review]: ----------------------------------------------------------------- ::: dom/ipc/ContentParent.cpp @@ +254,5 @@ > + "The number of unset IPC messages held in this ContentParent's " > + "channel. Usually we'd expect this to be zero, or close to it; a " > + "large value here might indicate that we're leaking messages. " > + "Similarly, a ContentParent object for a process that's no longer " > + "running could indicate that we're leaking ContentParents."); Omit the "Usually we'd expect this to be zero, or close to it;" ? @@ +335,5 @@ > return; > } > > + nsRefPtr<ContentParentMemoryReporter> mr = new ContentParentMemoryReporter(); > + NS_RegisterMemoryMultiReporter(mr); I was really confused here, because I thought ContentParent::StartUp() was run for each new ContentParent. But now I see it's a static method run once -- "Start up the content-process machinery. This might include scheduling pre-launch tasks." Attachment #774978 - Flags: review?(n.nethercote) → review+ > Omit the "Usually we'd expect this to be zero, or close to it;" ? Yeah, that's redundant with the next part. Created attachment 775127 [details] [diff] [review] Part 4: Don't crash if we call ContentParent::Pid() after the process is dead. I wasn't seeing this null-crash before; I think it was just an issue of killing the child processes at the right time. Attachment #775127 - Flags: review?(khuey) Comment on attachment 775127 [details] [diff] [review] Part 4: Don't crash if we call ContentParent::Pid() after the process is dead. This looks good to me! Attachment #775127 - Flags: review?(khuey) → review+ Created attachment 775145 [details] [diff] [review] Part 1: Don't leak BrowserElementParent due to an event listener on the window which contains it. This doesn't fix the leak, but I think it's a prerequisite. Comment on attachment 775145 [details] [diff] [review] Part 1: Don't leak BrowserElementParent due to an event listener on the window which contains it. Sorry, wrong bug. Attachment #775145 - Attachment is obsolete: true Sorry for the try: -a pushes here, but I figure nobody is using the cycles on the weekend. So this burns xpcshell because (apparently) sContentParents is not empty at shutdown any longer (because we now remove ContentParents from this list only when they're destructed), and we have an assertion in LinkedList's destructor that checks that the list is empty. It also burns Windows for reasons I'm not sure of yet. Assignee: nobody → justin.lebar+bug Whiteboard: [MemShrink] khuey thinks that the windows orange might have been infra weirdness. Let's find out... I need this in order to diagnose bug 893012 and verify that the changes we make there actually fix things. blocking-b2g: --- → leo+ Created attachment 777369 [details] [diff] [review] Part 1.5: Make sContentParents a StaticAutoPtr. This eliminates a static constructor, which is good. It also avoids a problem at shutdown: If we leak a ContentParent and we destroy sContentParents atexit, then sContentParents will assert that it's not empty and cause test failures. Attachment #777369 - Flags: review?(khuey) This needs a separate set of patches for b2g18. I can uplift tomorrow. Whiteboard: [MemShrink] → [MemShrink][jlebar will uplift] remote: remote: remote: remote: remote: I guess this still needs to be uplifted to b2g18-hd. status-b2g18: --- → fixed Status: NEW → RESOLVED Last Resolved: 5 years ago Resolution: --- → FIXED Target Milestone: --- → mozilla25 Whiteboard: [MemShrink][jlebar will uplift] → [MemShrink] (In reply to Justin Lebar [:jlebar] from comment #25) > I guess this still needs to be uplifted to b2g18-hd. b2g18 is merged to v1.1hd regularly, so no worries on that front :-) fixed Whiteboard: [MemShrink] → [MemShrink][LeoVB+]
https://bugzilla.mozilla.org/show_bug.cgi?id=893242
CC-MAIN-2018-39
refinedweb
1,376
57.06
So I have a question about the keyword this. I made a simple test program to test it, and it seems like it doesn't matter whether I use the this keyword in the display(). I tried running with and without it and get the same result, so my question is what is the advantage of using the this keyword? Game.cs namespace ClassPract { public class Game { public static void Main() { Player player = new Player("Jack", 23); player.display(); } } } Player.cs using System; namespace ClassPract { public class Player { String name; Byte age; public Player (String t_name, Byte t_age) { name = t_name; age = t_age; } public String getName() { return name; } public Byte getAge() { return age; } public void display() { Console.WriteLine("name:\tage:\n{0}\t{1}", this.getName(), this.getAge()); } } }
http://www.gamedev.net/topic/641755-this-keyword-question/
CC-MAIN-2016-40
refinedweb
127
57
I'm really confused with this! I have 2 classes, Club and Membership. In Membership I have the method, getMonth(), and in Club I have joinedMonth() which takes the parameter, 'month' - so a user enters a month and then I want it to return the Membership's which joined in that specific month. I am trying to call the getMonth() method from class Club, so that I can then go on to compare the integers of the months. But, when I try to call the method, I just get the mentioned "non-static method getMonth() cannot be referenced from a static context". Basically, what is this and how can I resolve it? Thank you in advance! Club: public class Club { private ArrayList<Membership> members; private int month; /** * Constructor for objects of class Club */ public Club() { Membership member = new Membership("John", 04, 2010); } /** * Add a new member to the club's list of members. * @param member The member object to be added. */ public void join(Membership member) { members.add(member); } /** * @return The number of members (Membership objects) in * the club. */ public int numberOfMembers() { return members.size(); } /** * Determine the number of members who joined in the given month * @param month The month we are interested in. * @return The number of members */ public int joinedMonth(int month){ Membership.getMonth(); } } Membership: public class Membership { // The name of the member. private String name; // The month in which the membership was taken out. public int month; // The year in which the membership was taken out. private int year; /** * Constructor for objects of class Membership. * @param name The name of the member. * @param month The month in which they joined. (1 ... 12) * @param year The year in which they joined. */ public Membership(String name, int month, int year) throws IllegalArgumentException { Membership member = new Membership("Josh", 5, 2011); if(month < 1 || month > 12) { throw new IllegalArgumentException( "Month " + month + " out of range. Must be in the range 1 ... 12"); } this.name = name; this.month = month; this.year = year; } /** * @return The member's name. */ public String getName() { return name; } /** * @return The month in which the member joined. * A value in the range 1 ... 12 */ public int getMonth() { return month; } /** * @return The year in which the member joined. */ public int getYear() { return year; } /** * @return A string representation of this membership. */ public String toString() { return "Name: " + name + " joined in month " + month + " of " + year; } }
https://www.daniweb.com/programming/software-development/threads/426975/non-static-method-cannot-be-referenced-from-a-static-context
CC-MAIN-2019-43
refinedweb
391
76.22
I let the program run for a few loops then press the switch. The lights change indicating the loop is terminating. it then just hangs for a bit, terminates my repl session on my laptop, continues to hang eventually the lights switch off, but my file probably will be corrupted. Here's a minimium example For this bug to happen it appears i need all the events Code: Select all import pyb import os pressed = False def switch_cb(): global pressed pressed = True def timer_cb(timer): pyb.LED(1).toggle() def main(): pyb.LED(2).on() os.mount(pyb.SDCard(), '/sd') os.chdir('/sd') try: with open("boot_file.txt","r") as f: info=f.readline() except OSError: info=None if "boot_file.txt" in os.listdir(): os.remove("boot_file.txt") blue=pyb.LED(4) blue.off() yellow=pyb.LED(3) yellow.on() print("") with open("data_file.txt","a") as f: while not pressed: f.write("hello world.\n") print(".",end="") for _ in range(60): if pressed: break pyb.delay(1000) yellow.toggle() blue.toggle() print("") blue.off() yellow.off() with open("boot_file.txt", "w") as f: f.write("saved state for next time\n") os.umount('/sd') pyb.LED(2).off() if __name__ == "__main__": switch = pyb.Switch() switch.callback(switch_cb) timer = pyb.Timer(14, freq=3) timer.callback(timer_cb) pyb.delay(5000) timer.callback(None) main() 1) a previously used timer 2) a boot file which is deleted on boot and re written on exit 3) writing of data in a sleepy loop This is a bug and i haven't done some thing wrong? update: if i re start repl whilst there are LEDs still on I get the message unable to open `/dev/ttyACM0` if i wait until they extinguish the repl session is totally un responsive except to pressing CTRL+D (soft reboot). This just causes the pyboard to flash the red and green lights (error?), no message printed.
https://forum.micropython.org/viewtopic.php?t=5232&p=29950
CC-MAIN-2018-39
refinedweb
321
69.38
Interviews Index This series of interviews spotlights Java Champions, individuals who have received special recognition from Java developers across industry, academia, Java User Groups (JUGs), and the larger community. Bio:. Java.sun.com (JSC): What are the best shortcuts to eliminate guesswork in identifying performance bottlenecks? Pepperdine: There are no all-purpose shortcuts. You need to be methodical if you want to find a "go fast" button in any particular situation. That's why I introduced the box with Dr. Heinz Kabutz, as a guide to explain how I approach tuning engagements. Much of my work involves analyzing systems in an effort to solve critical performance problems. After working on a number of systems, I began to notice a trend. The development teams that I assisted all had developers who were all quite capable of understanding the underlying issue when it was presented to them, but they lacked a methodology that could help them identify the problem. Often, in programming as in life, we make educated guesses that are correct. But sometimes we guess wrong, depending on the quality of the information that we base our guess on. Among developers, there's a behavior that is more damaging than guessing. Because we're trained to look at code, when something goes wrong, we look at code. And no matter how good our code is, we can always find something wrong or ugly that's begging to be fixed. Finding ugly code will throw even the best developers off track -- because the code is ugly, they will guess that it's the source of the problem. So developers often fix things that have little or no impact on overall performance. I've seen teams literally waste months rewriting ugly code that had no impact on performance. I'm not saying it's wrong to look into the code. Typically, that's exactly what we'll have to do. But we should delay looking at the code until we have a solid measurement or clue as to exactly which part of our application is responsible for the problem. It's amazing how, when developers are armed with a good measurement, they suddenly start looking past the ugly bits. I've attempted to summarize these observations and experiences in two instruments: the mantra "Measure, don't guess" (PDF) and the box. "Measure, don't guess" means don't do anything that hasn't been justified with a solid measurement that leads you directly to the problem. Unfortunately, getting a solid measurement isn't always so easy. Because of this, people work from hunches and assumptions, trying to find the smoking gun. This is where the box can help. The box provides a guide for investigating problems. Feedback from those using it has been very positive. The box is a reminder that a system is much more than software. There is hardware, which includes the operating system. On top of that, we have a VM for managed systems and then our Java application. The top layer in any system are end users, or people, as the layer is labeled in the box. Each layer is important to the overall performance of the system. If you change anything in any layer, you will change the performance profile. If you don't account for all of the layers, you run the risk of hiding performance bottlenecks or creating artificial ones. This misstep alone often results in teams wasting a lot of time. JSC: You wrote this in a 2006 Java Specialists' Newsletter article: "I have found that violating design principles or writing overly complex code is often the stumbling block to achieving good performance." Sun's Brian Goetz, in a similar vein, recommends that developers should write "dumb code," by which he means straightforward, clean code that follows the most obvious object-oriented principles, in order to get the best compiler optimization. He argues that clever, hacked-up, bit-banging code will get poorer results. Your thoughts? Pepperdine:: .... Iterator iter = customers.iterator(); while (iter.hasNext()) { Customer c = (Customer)iter.next(); doStuff( c); } ....). doStuff(). get: public class Customers { Hashmap customers = new Hashmap(); public void putCustomer( Customer customer) { allCustomers.put( customer.getId(), customer); } public Customer getCustomer( String id) { allCustomers.get( id); } public Customers getCustomers( String pattern) { return doSomeStufftoGetACollectionOfCustomer( pattern); }. Hashmap Customers. JSC: What advice do you have regarding Java technology performance tips? Pepperdine: A while ago, I added to my presentations a slide that says, "Everything I'm about to tell you will be wrong." I say this because, as time marches on, tips grow stale and things need to be reassessed. Even scarier, some tips are just plain wrong to begin with. Think of it this way: The prescription (drug) that your friend is taking may result in ill health if you were to take it. Same goes with performance tips. Here's an example: A while back, I was asked to review a paper on what you could do in your code to help the garbage collector. The big tip in the article was that one. myObject = null JSC: What are your greatest Java technology "pain points," and how do you cope with them? Pepperdine: When I began working with Java programming after working a lot with Smalltalk, I was struck by how much more work I had to do because the Java language was strongly typed. I still don't like the fact that the language designers decided to directly expose primitive types. In Smalltalk, primitives were managed as immediate directs, which in effect says the value of the "object" is held in the pointer. It seems to me that this decision tightly couples implementation, the language, with representation. The Java language has two separate syntaxes that don't mix. This in turn motivated autoboxing, a solution to the syntax problem that I consider to be yet another code smell. There is one pain point we can be thankful for: The Java language and platform lowered the bar on distributed programming. It allows average developers to create systems that would have taken a rock-star team of C/C++ developers to create in the past. Still, there are certain realities that no language or platform can paper over. This makes the Java EE and Spring and now Grid frameworks both a blessing and a curse, as they encourage developers to swim with the sharks. This can be fun unless you are swimming with one that decides to attack. Java EE, Spring, and Grid can take a bite out of you in quite different ways that are related to the same fundamentals. Spring, JEE, and grids all have to deal with networks, caching read multiple copies of the same thing that everyone expects to be constantly consistent, locking up shared resources. All of these issues still need to be dealt with, no matter which of these architectural styles you decide to use. It is remarkable what Java has enabled people to do, but it still can't save them from needing to understand and know how to deal with the fundamentals. JSC: What are the major misconceptions you encounter in performance tuning? Pepperdine: I can think of a few interesting situations where conventional wisdom fails. For example, I walked onto a client site at the beginning of a one-week engagement and was immediately invited into the CEO's office. The CEO wanted to get a sense of what I planned to do. He offered me a desk and complete access to the source. He was surprised when I said that I most likely wouldn't be looking at the code. You can imagine how surprised he looked, and of course, he immediately asked what I planned to do. This is misconception number one -- the assumption that I, or any consultant for that matter, can drop onto a work site for a week and start looking at code. First, I'm not smart enough to read through an application's code base and find performance bottlenecks, no matter how much time you give me. And with only a week to work with, there are just too many details to absorb. Second point, the box tells us that performance problems exhibit themselves in a live, fully functional system, so it only makes sense to look for them in a live, fully functional system. That said, I did eventually dive into the code, but by that time, I was completely focused on a very narrow aspect of the code. The misconception is quite obvious -- as developers, we are paid to look at, write, and manipulate code. Why would we ever do anything else? Here's another example. In my performance tuning course, I use an exercise that began as a lesson on how to use a profiler. Jack Shirazi and I expected it to take about 30 minutes to complete. The first time we presented the course, we were stunned that no one had identified the primary bottleneck after 30 minutes, yet everyone in the class was happily coding away. An entire group of people who had just been told how to profile, when faced with a problem and a deadline, abandoned all reason and just started hacking at the code. We have presented the course countless times, and each time, developers continued to ignore profiling and just jump into the code. Jack and I scratched our heads for quite some time trying to figure out what was going on. I finally got a clue when I taught the course to a group that included a tester. The tester had very little experience coding in Java. Yet he was the first person to complete the exercise within 30 minutes. Since then, we've had a number of testers in the course, and overwhelmingly, it has been the testers who have been able to solve the problem in the requisite time span. They started by profiling and pretty much ignored the code. The conclusion seems obvious. JSC: How do you approach problems in database interactions and memory management? Pepperdine: Database and memory problems make up the vast majority of the performance issues that I face. Most of the database problems can be traced back to overutilization or poor structure. That includes too many table joins or lack of indexes -- simple things like that. Most database administrators (DBAs) are well equipped to recognize and squish these types of problems. I like working with DBAs because they are well aware of the importance of acting on a direct measurement. The bigger problem is overutilization of the database by the application. If the team has been "dumb" enough -- and I say that in a very complimentary way -- to use the JPA and/or a mapping tool such as Hibernate or TopLink, then there's a chance to inject caching into the application. At the very least, code interacting with the database will most likely be fairly well structured. Sadly, I've run into a number of applications that I have deemed to be cache resistant. What I mean by cache resistant is that there's no effective way that caching can be injected into the application. This can happen for several reasons. First, and less common nowadays with people using EJB, Spring, Juice, and so on, is the scattering of JDBC (Java Database Connectivity) logic throughout the application. To find and change all that logic is, to put it mildly, a major hassle. Second, I've seen this happen when applications use the database as an IPC channel or worse, use it as a distributed locking mechanism. Third involves putting key business logic into the database, and a fourth is when you have denormalized data flows into the database. I'm not antidatabase. Databases are and will continue to be important pieces of technology. As much as database vendors may disagree with me, it is my opinion they've been abused. This wasn't a problem as long as clock speeds kept pace. But that hasn't been happening for the past couple of years. Having every thread of execution somehow end up in a database is just not going to work anymore unless you set the database up as a data grid. Which means, why not just code the application in SQL? I say this because we all know that users are demanding more and more performance, for systems to work harder, and do more faster. Sun, Intel, AMD, and others have continued to oblige by moving to multicore CPUs. All of a sudden, parallelism is much more important than it has been in the past, and now the abuses of the technology are coming home to roost. I predict that we will roll back on how databases are used. I think they will be repurposed to secure corporate data and do less pure transactional work. As cheap and as plentiful as memory is, I don't see memory databases as an option for most applications as long as the amount of data being kept expands faster than we are creating memory. Of course, this prediction is like throwing a punch at a boxer and not expecting him to duck. DB vendors are ducking. But for now.... So getting back to diagnosis, the first step in recognizing overutilization is to count the number of interactions between the application and the database. That count should be tempered against the amount of work that you're doing. There are a number of tools out there that can give you this measurement. Glassbox and JaMon are a couple of open-source offerings. Most of the commercial vendors offer this capability. The quick fix is to add caching, as it's much easier to do this than eliminate the excessive calls to the database. Here's a takeaway: The cheapest call you can make is the one you didn't make. The other trick is to bulk up on the database interactions. Bulking up is a common optimization whenever you have to cross an expensive barrier. I lived in a building that had a large grocery store on the ground floor. While I could always quickly run down and get fresh food, it was more effective to get more less often and store extra in the fridge or cupboard The same principle holds for databases or with connecting to any process that involves use of a network or other high-energy barrier. JSC: How do you go about solving memory problems? Pepperdine: Memory leaks are easiest to solve, and the best tool to use is the generations feature found in the NetBeans profiler. You can also use VisualVM, as it contains the same stuff. Another problem is object loitering, and again, the NetBeans generations feature may be helpful in finding these cases. In the past, I've always let the system rest so I can see what times out. Now with generations, you can immediately see what may be causing you grief. A third problem is high rates of object churn. I find that simplifying the site's feature in the hprof profiler works wonders. You can find the equivalent information in the NetBeans profiler. Kudos to the NetBeans profiling team. They have altered the face of memory profiling. Prior to the generations feature in the profiler, finding leaks used to be quite tricky. Now it is mechanical. One should be able to find most memory problems within minutes using these new tools. If you're facing high rates of object churn, that will translate into very inefficient garbage-collection (GC) numbers. Sometimes the problem is simply that the JVM* doesn't have enough heap space. Monitoring GC activity will give you a hint that a general heap-sizing exercise could solve your problem. HPJMeter is a free tool that will read Sun. Right now, it's pretty limited in functionality, but I expect that will change very shortly. The VisualVM team is very interested in integrating gchisto. I think it's a great fit. JSC: Tell us about the Java Performance Tuning site. Pepperdine: Jack Shirazi started the site after he wrote his very successful book, Java Performance Tuning, published by O'Reilly. The book is the result of our experiences working together. In a cafe, we worked out a plan of action literally on the back of a napkin. That plan became an integral part of Jack's book. Jack is a lot more disciplined than I am. After he wrote the book, Tim (O'Reilly) encouraged him to start the web site, and shortly afterwards, I started contributing to the site. The site is a comprehensive set of everything related to Java performance. The tips section offers a selection of all the performance tuning tips that appear on the Web. There's not enough time to vet the tips, so some may be questionable, but the sum total of knowledge on the site can't be matched. JSC: What role does stress reduction play when you're attempting to correct an application that is performing poorly? Do you have any tips for helping people calm down and become more functional? Pepperdine: Great question -- we mustn't forget that although we are working with machines, we ourselves are not machines. Emotions, feelings, stress, everything that makes us human also has a huge impact on how we perform. A product company I worked for frequently sent me to their more difficult customers. I assumed it was some sort of punishment for something I'd done. I asked the sales guy what was up with that. He said, "Hey, I send you to noisy customers, and when you leave, they're no longer noisy." What I'd discovered very early on is that the customers were often frustrated. They had tight deadlines, aggressive plans, and intense pressure to deliver -- and no matter what they did, things just didn't seem to be working. To make things worse, they "knew" the problem wasn't their fault. I let them rant and rave and in the process vent their frustration. What happened is they ended up explaining exactly what was wrong with the system. So it both allowed them to vent and I could parrot back what they told me in the form of a diagnosis. They got to release all of their stress, and I ended up looking brilliant. HTTPSession I quickly learned that the more frustrated the customer, the more brilliant I was going to appear to be, which may sound a bit egotistical, but honestly, most of the teams I was helping were cleverer than I could ever hope to be. The only advantage I had was that I'd learned to turn frustration and stress into something useful. Stress prevents us from learning. The first thing I look for in an SOS engagement is a pressure-relief valve, some hack or trick to reduce the level of stress in the room. In one case, I put in a cron job that ran every 15 minutes, looking for any database transaction that had run for more than some threshold period of time. If it found one, it would kill that session. This is an ugly hack. The user whose transaction was killed certainly wasn't happy. But the hack stabilized the system enough so that most of the users who had customers in their faces got work done. It also took pressure off the developers. Every time the system went south, which was quite often, the phones would start -- and just think of the rat in the cage being buzzed at random times. You could imagine what a relief it was to get the phones to stop ringing. You could see the stress drain out of the room and the brains turn back on. It set up an environment where we could have a meaningful discussion about a permanent fix. I've used lots of release valves to calm stressed-out developers: I've rolled VMs through clusters, neutered the HTTPSession object, used GC to slow down certain parts of the application to improve overall throughput, tuned memory to some very insane configuration so that the application would run for a working day, and on and on. HTTPSession object This is triage, and my only goal is to keep the patient alive to give developers time to start fixing what is broken. _______ * As used on this web site, the terms "Java Virtual Machine" and "JVM" mean a virtual machine for the Java platform. Kirk Pepperdine's Blog Java Performance Tuning The Box: A Shortcut to Finding Performance Bottlenecks Ant Developer's Handbook Java Champions Project Java Champion Dr. Heinz Kabutz Java Champion Cay Horstmann Java Champion Adam Bien The Java Champions self-select their members. However, the Java community can nominate candidates in accordance with the Five Guiding Principles.
http://java.sun.com/developer/technicalArticles/Interviews/community/pepperdine_qa.html
crawl-002
refinedweb
3,466
63.29
@xinxin.li.seattle In the random initialization Lesson 3 discussion that’s exactly where i am lost!!! i couldn’t find the random initialization in the code (tried search “rand”“random”). Would you be so kind to point me to that line of code? [] Whenever you define a layer of the model it is initialized with weights, each type of layer has a default way to initialize its weights, you can change it by: it is in those initializations where the randomness is introduced Aha!! I looked at Jeremy’s code, and I couldn’t find the explicit initialization as in ‘VGG-style’ CNN (attached below). Does that mean it’s initialized with a default distribution? If so, what is the default? uniform? normal? def get_model(): model = Sequential([ Lambda(norm_input, input_shape=(1,28,28)), Convolution2D(32,3,3, activation=‘relu’), Convolution2D(32,3,3, activation=‘relu’), MaxPooling2D(), Convolution2D(64,3,3, activation=‘relu’), Convolution2D(64,3,3, activation=‘relu’), MaxPooling2D(), Flatten(), Dense(512, activation=‘relu’), Dense(10, activation=‘softmax’) ]) model.compile(Adam(), loss=‘categorical_crossentropy’, metrics=[‘accuracy’]) return model Never mind, found my own answer. “?? Convolution2D” gives me the following: Init signature: Convolution2D(self, nb_filter, nb_row, nb_col, init=‘glorot_uniform’, activation=‘linear’, weights=None, border_mode=‘valid’, subsample=(1, 1), dim_ordering=‘default’, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs) I am stuck at the same point. But then get stuck with a problem with vgg16bn The network we are building is just the top of vgg16bn anyway so it seems a logical workaround just to jump to using vggbn. However if I run: from vgg16bn import * vgg = Vgg16BN() I get the follow error. ValueError Traceback (most recent call last) in () 1 from vgg16bn import * ----> 2 vgg = Vgg16BN() 3 #model = vgg.model 4 #from vgg16 import * 5 #vgg = Vgg16() /home/anaconda3/envs/python2/nbs/lesson2/vgg16bn.pyc in init(self, size, include_top) 31 def init(self, size=(224,224), include_top=True): 32 self.FILE_PATH = “/home/anaconda3/envs/python2/nbs/lesson1/data/kaggle/” —> 33 self.create(size, include_top) 34 self.get_classes() 35 /home/anaconda3/envs/python2/nbs/lesson2/vgg16bn.pyc in create(self, size, include_top) 89 90 fname = ‘vgg16_bn.h5’ —> 91 model.load_weights(get_file(fname, self.FILE_PATH+fname, cache_subdir=‘models’)) 92 93 /home/anaconda3/envs/python2/lib/python2.7/site-packages/keras/utils/data_utils.pyc in get_file(fname, origin, untar, md5_hash, cache_subdir) 111 try: 112 urlretrieve(origin, fpath, –> 113 functools.partial(dl_progress, progbar=progbar)) 114 except URLError as e: 115 raise Exception(error_msg.format(origin, e.errno, e.reason)) /home/anaconda3/envs/python2/lib/python2.7/site-packages/keras/utils/data_utils.pyc in urlretrieve(url, filename, reporthook, data) 48 yield chunk 49 —> 50 response = urlopen(url, data) 51 with open(filename, ‘wb’) as fd: 52 for chunk in chunk_read(response, reporthook=reporthook): /home/anaconda3/envs/python2/lib/python2.7/urllib2.pyc in urlopen(url, data, timeout, cafile, capath, cadefault, context) 152 else: 153 opener = _opener –> 154 return opener.open(url, data, timeout) 155 156 def install_opener(opener): /home/anaconda3/envs/python2/lib/python2.7/urllib2.pyc in open(self, fullurl, data, timeout) 419 420 req.timeout = timeout –> 421 protocol = req.get_type() 422 423 # pre-process request /home/anaconda3/envs/python2/lib/python2.7/urllib2.pyc in get_type(self) 281 self.type, self.__r_type = splittype(self.__original) 282 if self.type is None: –> 283 raise ValueError, “unknown url type: %s” % self.__original 284 return self.type 285 ValueError: unknown url type: /home/anaconda3/envs/python2/nbs/lesson1/data/kaggle/vgg16_bn.h5 Things I have checked: -So I have checked the path and the vgg16_bn.h5 file is present at the required location (and in a few other places as well for redundancy). -The path itself is valid. -Replacing vgg16BN with vgg runs normally with the same path. -Changing the path in which I launch the notebook does not change this. Has anyone else had this problem, and if so how did you solve it? Did you modify FILE_PATH yourself? If so, try file:// in the beginning of the path There are five steps to take once you are overfitting. But for two of them it’s not really clear to me how they translate to what Jeremy has been teaching us in the videos. Use architectures that generalize well What kind of architectures generalize well? Reduce architecture complexity Given VGG, how could we reduce its complexity to make it less prone to overfitting? I don’t really know how to answer these two questions. For your 1st question on architecture : Start with a very simple linear model , then for image recognition tasks include convolution layers, max pooling , drop out . Basically get inspired by looking at how other architectures are designed. If the problem is similar to Imagenet , then you can use transfer learning . By fine tuning an existing model. You may decide to choose to train how many layers to train. In practice , training the dense layers works well. For 2nd question on complexity : Model is less complex when you have fewer nodes/layers , the number of parameters to learn is less. The more number of layers and nodes you add , the model has chance to learn or memorize the entire input data , where it does not generalise for unseen data. So reducing the layers or nodes in each layers forces the network not to memorize. Hope it helps. Hey all, Really struggling with some parts of lesson 3. First, in order to load weights from the fine tuned model in lesson 2, I had to pop a layer before adding the Dense(2, activation = ‘softmax’) layer. Does this make sense? otherwise I end up with 17 layers instead of 16. new_model = vgg_ft(2) #create a model with a binary classifier new_model.pop() new_model.add(Dense(2,activation = 'softmax')) Later, when trying to load in weights, I get this error --------------------------------------- TypeErrorTraceback (most recent call last) <ipython-input-244-e9cf85a7e40b> in <module>() ----> 1 fc_model = get_fc_model() <ipython-input-243-24066d99319f> in get_fc_model() 10 ]) 11 ---> 12 for l2,l3 in zip(nmodel.layers, fc_layers): l2.set_weights(wghts(l3)) 13 14 nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) /home/ubuntu/anaconda2/lib/python2.7/site-packages/keras/engine/topology.pyc in set_weights(self, weights) 873 ''' 874 params = self.weights --> 875 if len(params) != len(weights): 876 raise Exception('You called `set_weights(weights)` on layer "' + self.name + 877 '" with a weight list of length ' + str(len(weights)) + TypeError: object of type 'generator' has no len() But when I call type(wghts) it says it’s a function (as it should be), so I can’t figure out what it means by generator… Here’s the rest of my (Jeremy’s) code: def wghts(layer): return (w/2 for w in layer.get_weights()) def get_fc_model(): nmodel = Sequential([ MaxPooling2D(input_shape = conv_layers[-1].output_shape[1:]), Flatten(), Dense(4096, activation = 'relu'), Dropout(p = 0.6), Dense(4096, activation = 'relu'), Dropout(p = 0.6), Dense(2, activation = 'softmax') ]) for l2,l3 in zip(nmodel.layers, fc_layers): l2.set_weights(wghts(l3)) nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) return nmodel fc_model = get_fc_model() I should add that my validation accuracy after this if I comment out for l2, l3... is awful - 50%, down from 85% with a test set I’m using of my own images for a wet vs. dry ID problem HI Elizabeth, Let me first answer your question around the model part. If you take a look at utils.py in the github repo , vgg_ft model returns a model for which the last layer is already removed and a new dense layer with softmax activation function added. So you do not need to perform the pop and adding of a new layer part. Regarding your second question around the weights , you can use the weights saved from the previous task where you could have fine tuned. In the original VGG model , a drop out of 0.5 is used . Which could be overkill for our problem . So jeremy in his class , try to avoid those drop outs . Instead of training the weights from some random values , we take the weights from the previous experiment and half it , as we are not using dropout . If you want to try with Dropout of 0.6 then you may not be able to take advantage of the previous weights. Increasing the dropout may not be a great idea ,since the training accuracy is lesser than validation accuracy. Basically the model is under fitting. Hope it helps. Thanks, Vishnu Subramanian Hmm… I am still not fully understanding the rationale behind halving weights when we want to load the convolutional outputs from Vgg to a new fully-connected model. From my understanding… In the original Vgg16, there are dropout layers set to 0.5 in the fully-connected blocks. That means out of 4096 outputs (from the Dense layer), 2048 weights are temporarily deactivated during training each time dropout is utilized. To deal with having double the # of weights as we remove dropout in our newly constructed model, the notes Wiki mentions: and therefore a valid method of alleviating this imbalance is to simply divide the dense Vgg in half when loading them into our new model How does dividing each weight value by half exactly relate to having half of the weights zero’d out during training with dropout? Why do we do this instead of getting rid of half of the number of weights we’re loading in (since dropout gets rid of 50%), and zeroing out the rest? Is this just a heuristic to initialize the weight closer to where they’re supposed to be before fitting? Hey Vishnu! Thanks for the quick reply. Ignore the p values… was just playing around with those… What’s weird is the TypeError I’m getting in regard to the weights parameter. I can’t figure out why it’s being classified as a generator. Please share your code in gist , so that we can take a look at it. Please denote at what point you are getting the error. Towards the end of the video for lesson 3 @jeremy mentions that there is a strategy that is nowadays used for adding drop out, but I think he mentions he described it earlier. I think I might have missed it or maybe it was shared during Part 1 via some other medium. In general, what does this strategy entail? If I understood correctly, the idea is to start with no dropout and add as little as needed to the point where we are no longer overfitting? If I am reading this right, on the 5 point list that @jeremy shared with us in notebook for lesson 3, adding regularization is #4, so this is something that should be tried as a last resort to some extent? (dropout would be considered a form of regularization?) I’m applying the approach of the mnist notebook to the kaggle leaf classification (just the images, not the features). I notice that when i add batch normalization, it runs a lot slower (about 7 times longer per epoch) while having worse results. What could cause that? Is the dataset too simple? Re large images and foveation. @jeremy (love the course, though I’m following it after the real-time classes.) I liked your comment lecture 3 about how disappointing it is that people just down-sample big images and that something to do with the way eyes work in scanning pictures for relevance is likely to be the right way to go. I have a suspicion that the real trick would be to break images down like foveation, but structured in one or more rooted trees. I’m basing this idea on a new paper by Lin and Tegmark about why these neural networks work so well (). They argue that things in Nature arise from generative processes controlled by only a handful of parameters, which means things that learn the original model can more easily learn the next level of (perhaps physical or evolutionary) generations. I suspect that most large images we look at include natural objects that were generated in multiple steps of a generative model (embryology in living things; geologic and physical processes in non-living objects). If the eye searches for something like rooted trees and then processes the leaves in smaller, related batches,then I would suspect big image understanding might benefit by doing something similar. For anyone else that may have had the same question, I think I found an explanation in the lesson 3 note in the wiki, in which a clarification is made between classical dropout (which is the method of halving the weights demonstrated in the lesson 3 ipynb), and how Keras handles dropout (which renders the rescaling of weights demonstrated in the notebook actually not necessary). With respect to my question of “how does dividing each weight value by half relate to dropout with a probability of 0.5”, the gist of it is that (from lesson 3 notes): if during train time we were teaching our network to predict in the subsequent layer utilizing only 50% of its weights, now that it has all the weights at its disposal the contribution of each weight needs to only be half as big! I must say I’m still not 100% on the exact mechanism of rescaling to compensate for dropout, but I’ll accept this intuitive explanation for now!
http://forums.fast.ai/t/lesson-3-discussion/186?page=5
CC-MAIN-2018-17
refinedweb
2,231
55.64
Quark D2000 doesn't wake up after deep sleepLockdog Jul 31, 2016 3:55 PM I'm trying to wake up quark board after deep sleep, using comparator: #define WAKEUP_COMPARATOR_PIN (3) /*A0*/ int main(void) { qm_rc_t rc;(QM_PIN_ID_3, QM_PMUX_FN_1); qm_pmux_input_en(QM_PIN_ID_3, true); QM_PUTS("Weak Up Interrupt Ready\r\n"); while(1) { QM_PUTS("Go to deep sleep."); soc_deep_sleep(); QM_PUTS("Weak Up"); } } void ac_callback() { QM_PUTS("Interrupt"); QM_SCSS_INT->int_comparators_host_mask |= BIT(WAKEUP_COMPARATOR_PIN); } And interrupt works fine before deep-sleep, but it can't to wake up after. UPD. This example: qmsi/main.c at fd5a6a783df1ab99260302ea25e1efb6208dbd8f · 01org/qmsi · GitHub didn't work too. 1. Re: Quark D2000 doesn't wake up after deep sleepIntel_Alvarado Aug 1, 2016 1:16 PM (in response to Lockdog) Hi, According to the Intel Quark Microcontroller Software Interface document , section 4.13 you can see a notes that says: “Enter into deep sleep mode. All clocks are gated. The only way to return from this is to have an interrupt trigger on the low power comparators.” In the link you posted there’s a comment that says “Comparator pin will fire an interrupt when the input voltage is greater than the reference voltage (0.95V).” I also find a couple of threads with questions related to yours: One of the users also posted that “I've made some measurements and it seems that to wakeup from deep sleep the A5 pin needs to be pulled down.” Make sure to meet all these requirements. -Sergio 2. Re: Quark D2000 doesn't wake up after deep sleepLockdog Aug 1, 2016 1:59 PM (in response to Intel_Alvarado) Hello, Sergio, thanks for the reply. I've used low power comparator as described in document, and provide 3.3V to the input pin which connected to the comparator. Threads, that you provided doesn't resolve my problem at all. Example from Intel Studio doesn't work too. >>"A5 pin needs to be pulled down.” How I can do that? Is there any internal pull down and how I could configure it in this case? Or the only way is to use external pull-down resistor? UPD. I added the pulldown resistor and no any changes. UPD2. "A5 pin needs to be pulled down.” - it need for reducing the power consumption only and doesn't affect on interrupt. 3. Re: Quark D2000 doesn't wake up after deep sleepIntel_Alvarado Aug 2, 2016 1:57 PM (in response to Lockdog) We’ll investigate further and post a reply soon. -Sergio 4. Re: Quark D2000 doesn't wake up after deep sleepIntel_Alvarado Aug 2, 2016 3:09 PM (in response to Intel_Alvarado) According to , pin A5 should be connected to GND. Why is the Intel Studio not working, does it show any error logs or is it not responding? Can you try the power example? Notice the example says: “/* On the Quark Microcontroller D2000 Development Platform this pin is marked as"A5". This pin should be connected to ground before running the example! If not, the irq would be run before going into deep sleep. The callback will turn-of the gpio/comparator irq. This will result in the board not being able to recover from deep sleep.” Follow the suggestions on the thread and let us know your results. -Sergio 5. Re: Quark D2000 doesn't wake up after deep sleepLockdog Aug 2, 2016 4:25 PM (in response to Intel_Alvarado) Hi, thanks for the reply. Power example works as it should if I connect A5 to the GND, before running. But when I'm trying to write my own code interrupt, doesn't work. Also, I'm trying to use soc_sleep and waking up by RTC and it doesn't working too! Please help. My code below: int main(void) { uart_cfg(); QM_PUTS("Magnetometer app started\r"); mag_init(); ac_init(); rtc_init(); while(1) { QM_PUTS("Go to sleep\r"); soc_sleep(); QM_PUTS("Weak Up\r"); } } void bmc150_mag_set_h_threshold(void) { /*ENABLE INTERRUPT*/ write_register(0x12, BMC150_REG_INTERRUPT, 0x47); /*SET THRES ON X*/ write_register(0x12, BMC150_REG_HIGH_THRESHOLD_AXES_SET, 0x37); /*SET THRES VALUE (XDATA/16)*/ write_register(0x12, BMC150_REG_HIGH_THRESHOLD, X_H_THRESHOLD); } void ac_init(void) {(WAKEUP_COMPARATOR_PIN, QM_PMUX_FN_1); qm_pmux_input_en(WAKEUP_COMPARATOR_PIN, true); #ifdef DEBUG0 QM_PUTS("Comparator Ready\r"); #endif } int mag_init(void) { bmc150_init(BMC150_J14_POS_0); bmc150_mag_set_power(BMC150_MAG_POWER_ACTIVE); bmc150_mag_set_preset(BMC150_MAG_PRESET_LOW_POWER); bmc150_mag_set_h_threshold(); #ifdef DEBUG0 QM_PUTS("BMC150 Ready\r"); #endif return 0; } void uart_cfg(void) { qm_uart_config_t cfg; qm_uart_get_config(QM_UART_0, &cfg); cfg.baud_divisor = QM_UART_CFG_BAUD_DL_PACK(0, 104, 3); qm_uart_set_config(QM_UART_0, &cfg); qm_pmux_select(QM_PIN_ID_12, QM_PMUX_FN_2); /* configure UART_A_TXD */ qm_pmux_select(QM_PIN_ID_13, QM_PMUX_FN_2); /* configure UART_A_RXD */ qm_pmux_input_en(QM_PIN_ID_13, true); /* UART_A_RXD is an input */ #ifdef DEBUG0 QM_PUTS("UART Ready\r"); #endif } void rtc_init(void) { qm_rtc_config_t rtc; clk_periph_enable(CLK_PERIPH_RTC_REGISTER | CLK_PERIPH_CLK); rtc.init_val = 0; rtc.alarm_en = true; rtc.alarm_val = ALARM; rtc.callback = bmc150_mag_callback; qm_rtc_set_config(QM_RTC_0, &rtc); qm_irq_request(QM_IRQ_RTC_0, qm_rtc_isr_0); #ifdef DEBUG0 QM_PUTS("RTC Ready\r"); #endif } void bmc150_mag_callback(void) { bmc150_mag_t mag = {0}; bmc150_read_mag(&mag); QM_PRINTF("mag x %d y %d z %d\r\n", mag.x, mag.y, mag.z); qm_rtc_set_alarm(QM_RTC_0, (QM_RTC[QM_RTC_0].rtc_ccvr + ALARM)); } void bmc150_mag_read_reg_int(void) { QM_PRINTF("\r\nINTERRUPT\r\n"); uint8_t raw_mag[1]; read_register(0x12, 0x4A, raw_mag, sizeof(raw_mag)); QM_PRINTF("INT: %d\r\n", raw_mag[0]); } void ac_callback() { bmc150_mag_read_reg_int(); } 6. Re: Quark D2000 doesn't wake up after deep sleepIntel_Alvarado Aug 4, 2016 8:57 AM (in response to Lockdog) Thank you for providing the code. We’ll run some tests and post our reply soon. -Sergio 7. Re: Quark D2000 doesn't wake up after deep sleepLockdog Aug 8, 2016 12:45 PM (in response to Intel_Alvarado) Hello, Sergio Do you have any results? 8. Re: Quark D2000 doesn't wake up after deep sleepIntel_Alvarado Aug 9, 2016 10:30 AM (in response to Lockdog) We’re still investigating on your case. We’ll post a reply soon. Thank you for your patience. -Sergio 9. Re: Quark D2000 doesn't wake up after deep sleepIntel_Alvarado Aug 9, 2016 11:24 AM (in response to Lockdog) Take a look at this power example . This is the newest example used for deep sleep testing. If you’re writing your own code, make sure to base your code on this example, not in one of the previous examples. Try testing this code first. If this code works using the comparators and the RTC, you can move on and write your own code. I’d suggest you try small parts of the circuit first before attempting to connect the whole circuit. Focus first in waking up in the deep sleep wake up source. Once it is working then you can focus on the RTC wake up source. -Sergio 10. Re: Quark D2000 doesn't wake up after deep sleepLockdog Aug 11, 2016 11:58 AM (in response to Intel_Alvarado) @Intel_Alvarado Example works right. But when I try to implement the deep sleep part in my code it doesn't work. Which part may conflicted with it? 11. Re: Quark D2000 doesn't wake up after deep sleepjdel_ Aug 12, 2016 9:20 AM (in response to Lockdog)2 of 2 people found this helpful Hello Lockdog, Checking your code, you are using a high power comparator as a wake up pin. Please use one of AI[18:6] for wake-up. Refering to section 3.3 of the D2000 datasheet: Intel® Quark™ Microcontroller D2000: Datasheet : Any wake capable analog inputs shall be connected only to any of AI[18:6] and not to AI[5:0]. Your example is using: #define WAKEUP_COMPARATOR_PIN (3) /*A0*/. If you check the example in example/quark_d2000/main.c, the example is using: #define WAKEUP_COMPARATOR_PIN (6) /*A5*/ I hope this solves your issue. - Julien 12. Re: Quark D2000 doesn't wake up after deep sleepLockdog Aug 15, 2016 2:32 AM (in response to jdel_) Hi, Julien, thanks for your note, it helped me to moving forward I have found mistake in my code: when interrupt happens it call the function which try to read data by i2c, but deep sleep routine still didn't recover gpio registers and quark hangs up. Second point is that we need to configuring analog comparator every time before deep-sleep.
https://communities.intel.com/thread/104945
CC-MAIN-2018-47
refinedweb
1,327
63.09
Class RWWString, also used in representing various alphabets, is similar to RWCString except it works with wide characters. These are much easier to manipulate than multibyte characters because they are all the same size: the size of wchar_t.<!> The Essential Tools Module makes it easy to convert back and forth between multibyte and wide character strings. Here's an example of how to do it, built on the Sun example in the previous section: #include <rw/cstring.h> #include <rw/wstring.h> #include <assert.h> int main() { RWCString Sun("\306\374\315\313\306\374"); RWWString wSun(Sun, RWWString::multiByte); // MBCS to wide string RWCString check = wSun.toMultiByte(); assert(Sun==check); // OK return 0; } Basically, you convert from a multibyte string to a wide string by using the special RWWString constructor: RWWString(const char*, multiByte_);<!> The parameter multiByte_ is an enum with a single possible value, multiByte, as shown in the example. The multiByte argument ensures that this relatively expensive conversion is not done inadvertently. The conversion from a wide character string back to a multibyte string, using the function toMultiByte(), is similarly expensive.<!> If you know that your RWCString consists entirely of ASCII characters, you can greatly reduce the cost of the conversion in both directions. This is because the conversion involves a simple manipulation of high-order bits: #include <rw/cstring.h> #include <rw/wstring.h> #include <assert.h> int main() { RWCString EnglishSun("Sunday"); // Ascii string assert(EnglishSun.isAscii()); // OK // Now convert from Ascii to wide characters: RWWString wEnglishSun(EnglishSun, RWWString::ascii); assert(wEnglishSun.isAscii()); // OK RWCString check = wEnglishSun.toAscii(); assert(check==EnglishSun); // OK return 0; } Note how the member functions RWCString::isAscii() and RWWString::isAscii() are used to ensure that the strings consist entirely of ASCII characters. The RWWString constructor: RWWString(const char*, ascii_);<!> is used to convert from ASCII to wide characters. The parameter ascii_ is an enum with a single possible value, ascii. The member function RWWString::toAscii() is used to convert back. Rogue Wave and SourcePro are registered trademarks of Quovadx, Inc. in the United States and other countries. All other trademarks are the property of their respective owners. Contact Rogue Wave about documentation or support issues.
http://www.xvt.com/sites/default/files/docs/Pwr%2B%2B_Reference/rw/docs/html/toolsug/4-10.html
CC-MAIN-2017-51
refinedweb
363
50.84
Coupled Spring Mass ODE System¶ Introduction¶ In this tutorial Modulus is used to solve a system of coupled ordinary differential equations. Since the APIs used for this problem have already been covered in a previous tutorial, only the problem description is discussed without going into the details of the code. Note This tutorial assumes that you have completed tutorial Lid Driven Cavity Background and have familiarized yourself with the basics of the Modulus APIs. Also, we recommend you to refer to tutorial 1D Wave Equation for information on defining new differential equations, and solving time dependent problems in Modulus. Problem Description¶ In this tutorial, a simple spring mass system as shown in Fig. 45 is solved. The systems shows three masses attached to each other by four springs. The springs slide along a friction-less horizontal surface. The masses are assumed to be point masses and the springs are mass-less. The problem is solved so that the masses (\(m's\)) and the spring constants (\(k's\)) are constants, but they can later be parameterized if you intend to solve the parameterized problem (Tutorial Parameterized 3D Heat Sink). The model’s equations are given as below: Where, \(x_1(t), x_2(t), \text{and } x_3(t)\) denote the mass positions along the horizontal surface measured from their equilibrium position, plus right and minus left. As shown in the figure, first and the last spring are fixed to the walls. For this tutorial, assume the following conditions: Fig. 45 Three masses connected by four springs on a friction-less surface¶ Case Setup¶ The case setup for this problem is very similar to the setup for the tutorial 1D Wave Equation. Define the differential equations in spring_mass_ode.py and then define the domain and the solver in spring_mass_solver.py. Note The python scripts for this problem can be found at examples/ode_spring_mass/. Defining the Equations¶ The equations of the system (132) can be coded using the sympy notation similar to tutorial 1D Wave Equation. from sympy import Symbol, Function, Number from modulus.pdes import PDES class SpringMass(PDES): name = "SpringMass" def __init__(self, k=(2, 1, 1, 2), m=(1, 1, 1)): self.k = k self.m = m k1 = k[0] k2 = k[1] k3 = k[2] k4 = k[3] m1 = m[0] m2 = m[1] m3 = m[2] t = Symbol("t") input_variables = {"t": t} x1 = Function("x1")(*input_variables) x2 = Function("x2")(*input_variables) x3 = Function("x3")(*input_variables) if type(k1) is str: k1 = Function(k1)(*input_variables) elif type(k1) in [float, int]: k1 = Number(k1) if type(k2) is str: k2 = Function(k2)(*input_variables) elif type(k2) in [float, int]: k2 = Number(k2) if type(k3) is str: k3 = Function(k3)(*input_variables) elif type(k3) in [float, int]: k3 = Number(k3) if type(k4) is str: k4 = Function(k4)(*input_variables) elif type(k4) in [float, int]: k4 = Number(k4) if type(m1) is str: m1 = Function(m1)(*input_variables) elif type(m1) in [float, int]: m1 = Number(m1) if type(m2) is str: m2 = Function(m2)(*input_variables) elif type(m2) in [float, int]: m2 = Number(m2) if type(m3) is str: m3 = Function(m3)(*input_variables) elif type(m3) in [float, int]: m3 = Number(m3) self.equations = {} self.equations["ode_x1"] = m1 * (x1.diff(t)).diff(t) + k1 * x1 - k2 * (x2 - x1) self.equations["ode_x2"] = ( m2 * (x2.diff(t)).diff(t) + k2 * (x2 - x1) - k3 * (x3 - x2) ) self.equations["ode_x3"] = m3 * (x3.diff(t)).diff(t) + k3 * (x3 - x2) + k4 * x3 Here, each parameter \((k's \text{ and } m's)\) is written as a function and substitute it as a number if it’s constant. This allows you to parameterize any of this constants by passing them as a string. Solving the ODEs: Creating Geometry, defining ICs and making the Neural Network Solver¶ Once you have the ODEs defined, you can easily form the constraints needed for optimization as seen in earlier tutorials. This example, uses Point1D geometry to create the point mass. You also have to define the time range of the solution and create symbol for time (\(t\)) to define the initial condition, etc. in the train domain. This code shows the geometry definition for this problem. Note that this tutorial does not use the x-coordinate (\(x\)) information of the point, it is only used to sample a point in space. The point is assigned different values for variable (\(t\)) only (initial conditions and ODEs over the time-range). The code to generate the nodes and relevant constraints is below: import numpy as np from sympy import Symbol, Eq import modulus from modulus.hydra import to_yaml, instantiate_arch from modulus.hydra.config import ModulusConfig from modulus.continuous.solvers.solver import Solver from modulus.continuous.domain.domain import Domain from modulus.geometry.csg.csg_1d import Point1D from modulus.continuous.constraints.constraint import ( PointwiseBoundaryConstraint, PointwiseBoundaryConstraint, ) from modulus.continuous.validator.validator import PointwiseValidator from modulus.key import Key from modulus.node import Node from spring_mass_ode import SpringMass @modulus.main(config_path="conf", config_name="config") def run(cfg: ModulusConfig) -> None: print(to_yaml(cfg)) # make list of nodes to unroll graph on sm = SpringMass(k=(2, 1, 1, 2), m=(1, 1, 1)) sm_net = instantiate_arch( input_keys=[Key("t")], output_keys=[Key("x1"), Key("x2"), Key("x3")], cfg=cfg.arch.fully_connected, ) nodes = sm.make_nodes() + [sm_net.make_node(name="spring_mass_network", jit=cfg.jit)] # add constraints to solver # make geometry geo = Point1D(0) t_max = 10.0 t_symbol = Symbol("t") x = Symbol("x") time_range = {t_symbol: (0, t_max)} # make domain domain = Domain() # initial conditions IC = PointwiseBoundaryConstraint( nodes=nodes, geometry=geo, outvar={"x1": 1.0, "x2": 0, "x3": 0, "x1__t": 0, "x2__t": 0, "x3__t": 0}, batch_size=cfg.batch_size.IC, lambda_weighting={ "x1": 1.0, "x2": 1.0, "x3": 1.0, "x1__t": 1.0, "x2__t": 1.0, "x3__t": 1.0, }, param_ranges={t_symbol: 0}, ) domain.add_constraint(IC, name="IC") # solve over given time period interior = PointwiseBoundaryConstraint( nodes=nodes, geometry=geo, outvar={"ode_x1": 0.0, "ode_x2": 0.0, "ode_x3": 0.0}, batch_size=cfg.batch_size.interior, param_ranges=time_range, ) domain.add_constraint(interior, "interior") Next define the validation data for this problem. The solution of this problem can be obtained analytically and the expression can be coded into dictionaries of numpy arrays for \(x_1, x_2, \text{and } x_3\). This part of the code is similar to the tutorial 1D Wave Equation. # add validation data deltaT = 0.001 t = np.arange(0, t_max, deltaT) t = np.expand_dims(t, axis=-1) invar_numpy = {"t": t} outvar_numpy = { "x1": (1 / 6) * np.cos(t) + (1 / 2) * np.cos(np.sqrt(3) * t) + (1 / 3) * np.cos(2 * t), "x2": (2 / 6) * np.cos(t) + (0 / 2) * np.cos(np.sqrt(3) * t) - (1 / 3) * np.cos(2 * t), "x3": (1 / 6) * np.cos(t) - (1 / 2) * np.cos(np.sqrt(3) * t) + (1 / 3) * np.cos(2 * t), } validator = PointwiseValidator(invar_numpy, outvar_numpy, nodes, batch_size=1024) domain.add_validator(validator) Now that you have the definitions for the various constraints and domains complete, you can form the solver and run the problem. The code to do the same can be found below: slv = Solver(cfg, domain) # start solver slv.solve() if __name__ == "__main__": run() Once the python file is setup, you can solve the problem by executing the solver script spring_mass_solver.py as seen in other tutorials. Results and Post-processing¶ The results for the Modulus simulation are compared against the analytical validation data. You can see that the solution converges to the analytical result very quickly. The plots can be created using the .npz files that are created in the validator/ directory in the network checkpoint. Fig. 46 Comparison of Modulus results with an analytical solution.¶
https://docs.nvidia.com/deeplearning/modulus/text/foundational/ode_spring_mass.html
CC-MAIN-2022-27
refinedweb
1,255
50.84
Python Development This page will be devoted to matters relating to python development in general for the FreeOrion project, including the general boost::python interface. A separate page is devoted to details specifically regarding the AI Python API. Other topics relating more specifically to the AI will be covered at AI_Development, and topics relating more specifically to universe creation will be covered at Universe_Creation. A good understanding of the Free_Orion_Content_Script_(FOCS) will also likely be very helpful since the use of python in FreeOrion closely relates to scripted content. Contents Python version Supported python version is 2.7 Code style C++ API use camelCase style Python code should be written using general python style according to PEP8 also usefull to read google recommendations Extend C+ API in python In some cases it is more easy and effective to extend interface of c++ objects from python. For example string representation of object. This code located in file default\AI\freeorion_debug\extend_free_orion_AI_interface.py PS. Add __repr__ and __str__ methods to objects as soon as you need it. AI state in save file, and preserving backwards compatibility The AIState is stored as an encoded string in save game files (currently via the pickle module). The attributes of the AIState must therefore be compatible with the encoding method, which currently generally means that they must be native python data types, not objects such as UniverseObject instances or C++ enum values brought over from the C++ side via boost. If desiring to store a reference to a UniverseObject store its object id instead; for enum values store their int conversion value. Adding or removing AIState attributes can break save compatibility. If you're not entirely sure how to handle it one option is to not fully remove them, leave them with comment to remove, to make breaks less frequent. When adding attributes or changing their names, compatibility can be broken because some of the new code will try to use attributes that the saved object won't have. To deal with this, a custom __setstate__ method can be specified, which will be called during the unpickling process and which can add default values for the newly added attributes. For example, if a new attribute is added to the AIstate class, restoring the AIstate from a previous save file would fail unless additional steps are taken to deal with the conflict. The following __setstate__ method can be added to (or adjusted in) the AIstate class to provide default values for the new attribute(s); it is automatically called during the unpickling process. In this example the new attributes are all dictionaries. Keep in mind, this method is just used for unpickling saved games; default values still need to be provided in __init__ to handle new games: def __setstate__(self, state_dict): self.__dict__.update(state_dict) # update attributes for dict_attrib in ['qualifyingColonyBaseTargets', 'qualifyingOutpostBaseTargets', 'qualifyingTroopBaseTargets', 'planet_status', 'diplomatic_logs']: if dict_attrib not in state_dict: self.__dict__[dict_attrib] = {} Debugging Internal Debug Mode To be accessible this must be enabled by an AI config option: allow_debug_chat=1 For convenience, there is a premade config file that can be used invoking freeorion from the command line with the following option: --ai-config .\default\python\AI\ai_debug_config.ini Then, to access chat commands you need to choose send all (default behavior) or select first AI Send help to chat window. You will got instruction how to work with it. start <id> will start debug mode with selected id stop will finish debug mode To run start you need that this AI was selected (don't select any AI and all will work fine) Most used variables already imported to scope with short name (e:empire, u: universe, ai: aiState) Chat window does not support multiline input. Use semicolon as line separator Use short user name. In examples I use ($) as short name for user. This chat works like python shell. You can assign variables, print result and do almost all you want. $ x = 1 $ x 1 $ print x + 3 4 $ e.playerName 'AI_3' See more possibilities: Tips and tricks External For windows remove Python27.* from installed game folder to use system python(don't forget to install it) PyDev To open console: If you want to use the interactive console in the context of a breakpoint, a different approach would be selecting a stack frame (in the debug view) > right-clicking it > pydev > Debug Console (or you can also in the debug view create a new console view connected to the debug session for the same effect). winpdb Tips and tricks Reload module - enter debug mode $ start 2 - import module to current scope $ import ProductionAI - change module - reload module $ reload(ProductionAI) - end turn and enjoy result Note: Reload module that store some state will ruin the game (FreeOrionAI) Execute file $ execfile('file_path') path can be absolute or relative to current working dir $ import os $ print os.getcwd() Python editor It is your choice how to edit python code. Here are some suggestions: - PyCharm community edition - Eclipse based. A good IDE will help you to make fewer mistakes, and keyboard shortcuts and other IDE features can greatly speedup your development. If you are unfamiliar with using an IDE then two key features to be sure to learn are how to quickly navigate to an item's declaration (preferably with a shortcut key), and how to use its code completion feature. Deploying code Best way to deploy your code to game is to specify resource-dir and stringtable-filename in persistent_config file. - navigate to game folder with Config.xml - create persistent_config.xml - add next text and replace repository_path to your path <?xml version="1.0"?> <XMLDoc> <resource-dir>repository_path/freeorion/default</resource-dir> <stringtable-filename>repository_pathfreeorion/default/stringtables/en.txt</stringtable-filename> </XMLDoc> - Q: This page can be better / has typo / ... - A: Welcome to forum, lets do it better. - Q: Which python version used? - A: Windows: python shipped with game(2.7.3) Other system use system python. - Q: Where does print output go? - A: stdout and stderr redirected to logs in the game settings folder. - Q: How do I test new code? - A: start/load a game (changing code during gameplay will not affect a current game; the code is already in memory).
https://freeorion.org/index.php?title=Python_Development&amp;oldid=9082
CC-MAIN-2019-22
refinedweb
1,037
51.99
Web Forms :: Adding List Items To Drop Down Control From Generic List?Feb 6, 2010 I have the following Students class: [Code].... I need the 1 since it's a foreign key in another table. For the life of me, I can't get this to work like this. I have the following Students class: [Code].... I need the 1 since it's a foreign key in another table. For the life of me, I can't get this to work like this. I am getting this error yet I know it to be untrue.This is the code: ddlPartnerOrganisation.DataSource = agency.AgencyGetListOfEYDN(); string temp = ddlPartnerOrganisation.SelectedValue.ToString(); ddlPartnerOrganisation.DataValueField = "AgencyID" ; ddlPartnerOrganisation.DataTextField = "AgencyName" ; ddlPartnerOrganisation.DataBind(); Is it possible to set tab index value for list items of ASP.Net RadioButtonList control.View 1 Replies I have a webpart which contains a dropdownlist in the Webpaart property and its working fine. The code is below. public enum ItemCount { One = 1, Five = 5, Ten = 10 [Code]..... I have a drop down list that has the initials of about 12 of our sales guys.How can I make it so that when they select their initials from the list, the next drop down list only shows their customers.In my database there is a column for customer name and salesman.View 6 Replies I have two lists: List<string> _list1; List<string> _list2; I need add all _list2 different items on _list1... How can I do that using LINQ? I want to develop a web form where I have a list of elements, so I want to drag a single document into an image (ex. trashcan icon, favorites icon, news icon, etc). I read some samples of panel dragging, but this is not what I am looking for. Is there a way to drag and drop the item in a listbox to reorder the sequence?View 8 Replies in one page i have list box on one button click i am showing on popup which is another aspx pagein that page showing one grid with check box now i want that when user select check boxes and click on add button selected items should gets added to list box on page when i click save button on page(not popup) all the records in that list box should gets saved to data base how to do thisView 4 Replies. adding data from more than one columns of a table in drop down list but not concatening them. Like a table having columns Station_1 , Station_2 , Station_3. All these columns having place names. Now I want to list the distinct station/place names from each columns Station_1, Station_2 and Station_3 in my drop down list. How to do this I serched everywhere in but not found the solution.. if i create a html ul. and wanted to dynamically add list items to this list. so i have : <ul id="test" runat="server"> </ul> is there a way i can add list item to this list dynamically in asp.net i am using vb i'm having this issue, in ASP.NET MVC 2 where I'm adding a drop down list on the master page and filling it with data from an abstract master controller. When an option is selected an submit button clicked, it reroutes you to a new page. so lets say the page lives on i'm on: i select option and submit takes me to i select again and now the post tries to go to: because of the action="" i have set on the form tag. MasterPage: <form method="get" action="landingPage/Projects/FramedPage"> <%= Html.DropDownList("navigationList")%> <input id="navSubmitBtn" class="btnBlue" type="submit" value="Take Me There" /> [code]... The problem i am having is that if I am ON that page have a dropdown list inside gridview which has a object data source and I am adding the list items as true, false which stores in the database table as a bit value. Even if i am addin the values 1 and 0 to the drop down list, its throwing the below error'grdDebug' has a SelectedValue which is invalid because it does not exist in the list of items.Parameter name: value My code to add the dropdownlist with list items are as below <asp:TemplateField <ItemTemplate> <asp:DropDownList [code]... Is there an easy way to add image to the drop down list that is build into the report viewer export list?View 1 Replies As the tree said to the lumberjack, "I'm stumped". I've been doing .net for years, and my brain is in vapor lock...Very simple here.. I have a user control which has a dropdown list, and a button on it. The DDL is databound. When the button is clicked, I want to retrieve the value of the dropdownlist. I check to see if the page is a postback and if not, I bind the DDL.I put my user control on my master page.When the button is clicked, the value of the dropdown is not obtainable. The selectedvalue is empty. I figure this has something to do with the order of the page being regenerated.View 2 Replies I have a requirement in my application that, while saving the application, need to get all the value from drop down list and pass it to the view model. But application should not allow the user to select more than one item from drop down list manually, ie, only one value at a time. My view model is like ... public class ListManagement { public IEnumerable<selectListItem> InactiveProduct { get; set; } public string[] InactiveProductSelected { get; set; } public IEnumerable<selectListItem> ActiveProduct { get; set; } } [code]... Looping Through Checkbox List and adding selected items to MS SQL DatabaseI don't want to store it using comma deliminator.I will need to do a search on analyze which users have what music in common.The image above is from a tbl_lookup_music table I created. MusicID, MusicNow how should I build the logicIF we have a user that has a tbl_profile table. And listens to many different types of music. How should We store the data.------------------------------------------------------------------------------------------CREATE TABLE [dbo].[tbl_lookup_music]( [MusicID] [int] IDENTITY(1,1) NOT NULL, [Music] [nvarchar](64) NOT NULL, ---- Type of music. CONSTRAINT [PK_tbl_lookup_music] PRIMARY KEY CLUSTERED ( [MusicID] ASC )WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY----------------------------------------------------------------------------------------------CREATE TABLE [dbo].[tbl_Profile_Music]( [ProfileMusicID] [int] IDENTITY(1,1) NOT NULL, [ProfileID] [int] NOT NULL, [MusicID] [int] NOT NULL,PRIMARY KEY CLUSTERED ( [ProfileMusicID] ASC)WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOHow should I setup this table.View 4 Replies How find out time duration in asp.net using drop down list Control? Result will display in textbox.View 13 Replies I have a list of objects that have values to them. Specifically one of these values if a boolean (isAbnormal) to determine whether or not the value itself is classified by our application logic as "Abnormal" or not. I have composed a list of a mixture of abnormal/not abnormal items. I want and need to remove items from this list that aren't clsasified as being abnormal (in programming logic, isAbnormal will be false) I have tried several ways and can think of some dirty/ugly ways to get it, but there has to be something better: [Code].... I've got a drop down list that I want to populate with items from a SQL Server database, which I did successfully, but I can't figure out how to write an if statement that will clear the drop down list based on a selected index and repopulate it with data from another table. The drop down list is inside an update panel that auto posts back. Basically I want to allow the user to choose an item, but rather than populate another drop down list control, i just want to repopulate the current one with new data.I'm guessing that if I want to get data from more than one table the code below isn't going to work for me. Could I get the data from all the tables at once and store each table data in its own variable until I need to use it? (Each table will have under 10 items, in 5 tables.) Here is the code to get the data from the database:[Code].... I'm designing my own custom control that contains a .NET dropdownlist. What I'm wondering is if it is possible to populate my dropdownlist with listitems placed in a placeholder? For example: <asp:DropDownList <asp:PlaceHolder </asp:DropDownList> This doesn't work because the DropDownList control only allows ListItems as child controls. But, I want to do something similar to this so when the user includes my control on a page, they can do something like this: <mytag:MyControl <ListItemTemplate> <asp:ListItem</asp:ListItem> <asp:ListItem</asp:ListItem> <asp:ListItem</asp:ListItem> </ListItemTemplate> </myTag:MyControl> I know I can do this by dynamically adding the ListItems in the page code behind, but I'd like to avoid that if possible.
http://asp.net.bigresource.com/Web-Forms-Adding-list-items-to-drop-down-control-from-generic-list--2P3t7SgOX.html
CC-MAIN-2018-39
refinedweb
1,529
63.7
Flask supports the common HTTP methods, including GET, PUT, PATCH, DELETE and working with them is extremely simple, allowing us to build URL's and endpoints which only listen for certain HTTP methods. In this part of the "Learning Flask" series, we're going to build a simple application to demonstrate working with the 5 HTTP methods listed above, along with examples of when and how to use them. If you're new to programming or new to working on web, getting to know the HTTP methods and understanding the basics of HTTP is extremely valuable, so I'd suggest reading up on it after you're done here. This guide isn't designed to be an in depth tutorial on HTTP, however it should give you enough information to use them in your Flask applications and hopefully you'll learn something new! HTTP basics The "Hyper text transfer protocol" AKA HTTP is the world wide protocol for how we communicate and send/receive information on the web. It works on a "Request/Response" protocol, where a client makes a request to a web server which then returns a response. For example, when you clicked on this very URL, your browser (The client) made a request to the Pythonise web server, which internally triggered a series of events to return a response, which is the HTML you're reading now. Like I said, this is a very basic introduction to HTTP and we're not going to go into too much detail on it in this guide. For more information, the Wikipedia page is a good place to start. HTTP status codes When something goes well, it's nice to get a pat on the back, likewise when something doesn't go as planned, it helps to know why so you can put it right. Feedback is very important and it's no different on the web! HTTP status codes are used as a feedback system, issued by the server in response to a request from the client to indicate the status of the request. If the request went well, the server returns a status code to the client to indicate that everything is OK, likewise a bad request or error will result in a different code to tell the client that something didn't go as expected. If you've spend any time on the web, you've most likely come across these status codes yourself. Ever clicked on a link and got a 404 NOT FOUND? That's the web servers way of saying "I got your message, but whatever you're looking for, I don't have it". However rather than saying that it simply returns a 404 status code (Which is much more friendly for machines to understand 🤖) HTTP status codes are made up of 3 digits that fall into 5 categories, with each category representing a certain class of code. The first digit is the category and the 5 categories correspond to the following class: 1xx- Informational 2xx- Success 3xx- Redirection 4xx- Client errors 5xx- Server errors The example of the 404 status code falls under the "client error" category, where the client tried to request something that doesn't exist on the server. The last 2 digits of the code don't fall under any kind of class or category, but are used to provide more information and context. Again to use the 404 example, the last 2 digits refer to NOT FOUND, giving more context to the type of client error. A full list of HTTP status codes can be found here at the Wiki. HTTP methods The method is the type of action you want the request to perform and is sent from the client to the server on every request. There are several HTTP methods but we're only going to cover 5 in this article: GET- Used to fetch the specified resource POST- Used to create new data at the specified resource PUT- Used to create new data or replace existing data at the specified resource PATCH- Used to create new data or update/modify existing data at the specified resource DELETE- Used to delele existing data at the specified resource Requesting a URL is an example of a GET request, where your browser makes a request for resources at a specified location (the URL) and the server returns some HTML. GET requests are "safe" as they aren't able to modify state or data on the server. An example use case of a POST request would be creating a new account on a website or application, whereby the resource doesn't already exist. Flask HTTP methods By default, routes created with @app.route(/example) only listen and respond to GET requests and have to be instructed to listen and respond to other methods using the methods keyword & passing it a list of request methods. Let's explore some common use cases for GET requests. GET requests Ubiquitously used in Flask applications, the GET method is used to return data at a specified resource/location. Returning text Possible one of the most simple routes you can write in a flask app simply returns a string: @app.route("/get-text") def get_text(): return "some text" Rendering templates A very common use case for a GET request is to return some HTML: from flask import render template @app.route("/") def index(): return render_template("index.html") Handlinq query strings No different from either of the 2 previous examples, with the addition of handling a query string in the URL and returning a formatted string to the client: from flask import request @app.route("/qs") def qs(): if request.args: req = request.args return " ".join(f"{k}: {v} " for k, v in req.items()) return "No query" Requesting /qs?name=john&language=python returns the string name: john language: python. Fetching resources Again, not really any different from the previous examples, just in this case fetching and returning a resource as a JSON string. We've also created a mock database called stock: from flask import make_response, jsonify stock = { "fruit": { "apple": 30, "banana": 45, "cherry": 1000 } } @app.route("/stock") def get_stock(): res = make_response(jsonify(stock), 200) return res Extending the previous example with some URL variables, ding a lookup and returning a JSON response (Note the use of the 404 if the collection or member is not found): @app.route("/stock/<collection>") def get_collection(collection): """ Returns a collection from stock """ if collection in stock: res = make_response(jsonify(stock[collection]), 200) return res res = res = make_response(jsonify({"error": "Not found"}), 404) return res @app.route("/stock/<collection>/<member>") def get_member(collection, member): """ Returns the qty of the collection member """ if collection in stock: member = stock[collection].get(member) if member: res = make_response(jsonify(member), 200) return res res = make_response(jsonify({"error": "Not found"}), 404) return res res = res = make_response(jsonify({"error": "Not found"}), 404) return res In summary, use GET requests when you just need to return resources to the client and NOT make any changes to the state/data of your application. GET and POST In many cases such as rendering forms, you'll need a route to handle more than just GET requests. Making any request other than GET to a route without the methods argument and a list of methods will result in a 405 METHOD NOT ALLOWED HTTP status code, as methods must be declared for the route to respond to. Adding multiple request methods to a route is done with the following: @app.route("/example", methods=["METHOD_A", "METHOD_B"]) # GET POST PUT PATCH DELETE etc.. The route will now listen and respond to both methods provided which means we have to put in some control flow to handle each type of request. Fortunately this is made easy using the request object, in particular the request.method attribute which returns the method for the current request. This verbose and silly example illustrates the logic, assuming we want to listen for GET and POST requests: @app.route("/log-in", methods=["GET", "POST"]) def log_in(): if request.method == "POST": # Attempt the login & do something else elif request.method == "GET": return render_template("log_in.html") As Flask routes default to GET requests, we can remove the elif statement and let Flask return the template: @app.route("/log-in", methods=["GET", "POST"]) def log_in(): if request.method == "POST": # Only if the request method is POST # attempt the login & do something else # Otherwise default to this return render_template("log_in.html") A working example can be seen below where we're rendering a template which a user can then use to add a new collection to our stock database: @app.route("/add-collection", methods=["GET", "POST"]) def add_collection(): """ Renders a template if request method is GET. Creates a collection if request method is POST and if collection doesn't exist """ if request.method == "POST": req = request.form collection = req.get("collection") member = req.get("member") qty = req.get("qty") if collection in stock: message = "Collection already exists" return render_template("add_collection.html", stock=stock, message=message) stock[collection] = {member: qty} message = "Collection created" return render_template("add_collection.html", stock=stock, message=message) return render_template("add_collection.html", stock=stock) POST requests Flask routes listen for GET requests by default, so we must implicitly instruct them to listen for anything other than GET. In the example below, we've passed methods=["POST"] to the @app.route() decorator, meaning this route will ONLY respond to POST requests: @app.route("/stock/<collection>", methods=["POST"]) def create_collection(collection): """ Creates a new collection if it doesn't exist """ req = request.get_json() if collection in stock: res = make_response(jsonify({"error": "Collection already exists"}), 400) return res stock.update({collection: req}) res = make_response(jsonify({"message": "Collection created"}), 201) return res We're checking to see if the collection variable (passed in via the URL) is in our stock database and if not, create it, otherwise return a 400 BAD REQUEST to indicate the resource already exists. POST requests should be used to create NEW resources (New users, devices, posts, articles, datasets etc..) Again, if you tried to access this resource from the browser, you'd be greeted with a 405 METHOD NOT ALLOWED status as we've not provided GET as one of the available request methods to listen for. PUT requests PUT requests are similar to POST requests but serve a very different purpose. As we explained earlier, PUT should be used to create or replace a resource, meaning if it doesn't exist - create it, however if it does exist, replace it. @app.route("/stock/<collection>", methods=["PUT"]) def put_collection(collection): """ Replaces or creates a collection """ req = request.get_json() if collection in stock: stock[collection] = req res = make_response(jsonify({"message": "Collection replaced"}), 200) return res stock[collection] = req res = make_response(jsonify({"message": "Collection created"}), 201) return res Since PUT requests shouldn't care about the existing data or resource, we've decided to go ahead and create the resource with no regard for any existing data. The only dirrerence in the logic is the HTTP status code. If the collection DIDN'T exist, we're returning a 201 CREATED status. Whereas if the collection DID exist, we're returning a 200 OK to indicate that the collection has been replaced. It's probably bad design to replace an entire collection using the PUTrequest, but for demonstrational purposes it'll do. A better solution would be to use PUTto replace or create a value for one of the members in the collection. PATCH requests We're using a PATCH request to update OR create a resource in our stock database: @app.route("/stock/<collection>", methods=["PATCH"]) def patch_collection(collection): """ Updates or creates a collection """ req = request.get_json() if collection in stock: for k, v in req.items(): stock[collection][k] = v res = make_response(jsonify({"message": "Collection updated"}), 200) return res stock[collection] = req res = make_response(jsonify({"message": "Collection created"}), 201) return res Rather than replace the collection entirely, we're iterating over the keys and values in the request body and updating the values in the collection, only creating new members if they don't exist. And just like in PUT, we're returning a 200 if the collection was updated and a 201 if the collection was created. Let's cover the last request method in this article, DELETE. Delete requests Just like it says on the tin, DELETE requests should be used to delete a resource. As per the rest of the examples, we provide methods=["DELETE"] in the @app.route() decorator, meaning this route will only listen for that specific method. In the 2 examples below, you'll see we're deleting a collection and deleting individual members from a collection with 2 separate routes: @app.route("/stock/<collection>", methods=["DELETE"]) def delete_collection(collection): """ If the collection exists, delete it """ if collection in stock: del stock[collection] res = make_response(jsonify({}), 204) return res res = make_response(jsonify({"error": "Collection not found"}), 404) return res @app.route("/stock/<collection>/<member>", methods=["DELETE"]) def delete_member(collection, member): """ If the collection exists and the member exists, delete it """ if collection in stock: if member in stock[collection]: del stock[collection][member] res = make_response(jsonify({}), 204) return res res = make_response(jsonify({"error": "Member not found"}), 404) return res res = make_response(jsonify({"error": "Collection not found"}), 404) return res On deletion, we're returning a 204 NO CONTENT status code to indicate a successful transaction and we have no content to return. If the resource isn't found, I/e the collection or member doesn't exist, we're returning a 404 NOT FOUND. Wrapping up The code snippets shown here were designed to demonstrate how to work with some of the common request methods in Flask, rather than be examples of how to write a REST API, so take the examples with a pinch of salt. restfulapi.net is a great place to learn more about API design and using the various request methods, along with the 2 Wikipedia links below. I hope you learned something new!
https://pythonise.com/series/learning-flask/flask-http-methods
CC-MAIN-2021-17
refinedweb
2,337
50.16
Passing Data to Components Vue Test Utils provides several ways to set data and props on a component, to allow you to fully test the component's behavior in different scenarios. In this section, we explore the data and props mounting options, as well as VueWrapper.setProps() to dynamically update the props a component receives. The Password Component We will demonstrate the above features by building a <Password> component. This component verifies a password meets certain criteria, such as length and complexity. We will start with the following and add features, as well as tests to make sure the features are working correctly: const Password = { template: ` <div> <input v- </div> `, data() { return { password: '' } } } The first requirement we will add is a minimum length. Using props to set a minimum length We want to reuse this component in all our projects, each of which may have different requirements. For this reason, we will make the minLength a prop which we pass to We will show an error if password is less than minLength. We can do this by creating an error computed property, and conditionally rendering it using v-if: const Password = { template: ` <div> <input v- <div v-{{ error }}</div> </div> `, props: { minLength: { type: Number } }, computed: { error() { if (this.password.length < this.minLength) { return `Password must be at least ${this.minLength} characters.` } return } } } To test this, we need to set the minLength, as well as a password that is less than that number. We can do this using the data and props mounting options. Finally, we will assert the correct error message is rendered: test('renders an error if length is too short', () => { const wrapper = mount(Password, { props: { minLength: 10 }, data() { return { password: 'short' } } }) expect(wrapper.html()).toContain('Password must be at least 10 characters') }) Writing a test for a maxLength rule is left as an exercise for the reader! Another way to write this would be using setValue to update the input with a password that is too short. You can learn more in Forms. Using setProps Sometimes you may need to write a test for a side effect of a prop changing. This simple <Show> component renders a greeting if the show prop is true. <template> <div v-{{ greeting }}</div> </template> <script> export default { props: { show: { type: Boolean, default: true } }, data() { return { greeting: 'Hello' } } } </script> To test this fully, we might want to verify that greeting is rendered by default. We are able to update the show prop using setProps(), which causes greeting to be hidden: import { mount } from '@vue/test-utils' import Show from './Show.vue' test('renders a greeting when show is true', async () => { const wrapper = mount(Show) expect(wrapper.html()).toContain('Hello') await wrapper.setProps({ show: false }) expect(wrapper.html()).not.toContain('Hello') }) We also use the await keyword when calling setProps(), to ensure that the DOM has been updated before the assertions run. Conclusion - use the propsand datamounting options to pre-set the state of a component. - Use setProps()to update a prop during a test. - Use the awaitkeyword before setProps()to ensure the Vue will update the DOM before the test continues. - Directly interacting with your component can give you greater coverage. Consider using setValueor triggerin combination with datato ensure everything works correctly.
https://test-utils.vuejs.org/guide/essentials/passing-data
CC-MAIN-2022-40
refinedweb
539
53.71
We are about to switch to a new forum software. Until then we have removed the registration on this forum. Hi, I was wondering if anyone here can help me getting my head around PVectors. I am creating a visualization of points on Earth. For this I am creating an arrayList of PVectors, which get their data from a csv (Longitude, Latitute). My problem is the csv has over 88 000 lines and slows down the program when drawn in void draw() Therefore I wanted to initialize the PVectors in void createLocationPoints()) and only display them in draw with another funciton... For instance with giving the points a stroke weight. Can someone explain how I can display the function LocationVectors.add(new PVector(x, y, z)); in this example? I was thinking of something similar like Daniel Schiffmans simple particle example from the documentation but I can't quite get my head around it. Please be gentle, I am quite new to processing. Thanks a lot! import peasy.*; PeasyCam cam; //Radius Earth float radius = 6371000/50000; //global scale //Tables Table dataTable; Table locationTable; //Data lists FloatList AffordabilityIndex; FloatList LongituteAI; FloatList LatituteAI; FloatList AltituteAI; //Locations Lists FloatList settlementPoint; FloatList Longitute; FloatList Latitute; FloatList Altitute; float x; float y; float z; PVector LocationVector; //PShape points; ArrayList<PVector> LocationVectors; void setup() { size(800, 800, P3D); smooth(); dataTable = loadTable("dataTable.csv", "header"); locationTable = loadTable("locationTable.csv", "header"); LocationVectors = new ArrayList<PVector>(); cam = new PeasyCam(this, 4000); cam.setMinimumDistance(250); //0 cam.setMaximumDistance(500); //8000 ////LOCATIONS ////create location lists Longitute = new FloatList(); Latitute = new FloatList(); Altitute = new FloatList(); //Read and store CSV for (int i = 0; i < locationTable.getRowCount(); i++) { TableRow rowLocationTable = locationTable.getRow(i); Longitute.append(rowLocationTable.getFloat("Longitute")); Latitute.append(rowLocationTable.getFloat("Latitute")); Altitute.append(rowLocationTable.getFloat("Altitute")); } //DATA //create data lists AffordabilityIndex = new FloatList(); LongituteAI = new FloatList(); LatituteAI = new FloatList(); //Read and store CSV for (int i = 0; i < dataTable.getRowCount(); i++) { TableRow rowDataTable = dataTable.getRow(i); AffordabilityIndex.append(rowDataTable.getFloat("Affordability Index")*1); LongituteAI.append(rowDataTable.getFloat("Longitute")); LatituteAI.append(rowDataTable.getFloat("Latitute")); //println(Longitute, Latitute, AffordabilityIndex); } createLocationPoints(); } void draw() { background(255); shape(points); displayLocationPoints(); //DRAW DATA AltituteAI = AffordabilityIndex; strokeWeight(4); stroke(0); beginShape(POINTS); for (int i = 0; i < LongituteAI.size(); i++) { //Convert to Cartesian Coordinates //float a = pow( 1, 3); // Sets 'a' to 1*1*1 = 1 float f = 0; // flatening float lambda = atan(pow((1 - f), 2) * tan(radians(LatituteAI.get(i)))); // lambda float y = radius * cos(lambda) * cos(radians(LongituteAI.get(i))) + AltituteAI.get(i) * cos(radians(LatituteAI.get(i))) * cos(radians(LongituteAI.get(i))); //swaped x&y float x = radius * cos(lambda) * sin(radians(LongituteAI.get(i))) + AltituteAI.get(i) * cos(radians(LatituteAI.get(i))) * sin(radians(LongituteAI.get(i))); float z = radius * sin(lambda) + AltituteAI.get(i) * sin(radians(LatituteAI.get(i))); vertex(x, y, z); } endShape(); noStroke(); sphere(radius*0.98); } void createLocationPoints(){ //DRAW ALL LOCATIONS //strokeWeight(1); //stroke(0); //beginShape(POINTS); //points = createShape(); //points.beginShape(); for (int i = 0; i < Longitute.size(); i++) { //Convert to Cartesian Coordinates //float a = pow( 1, 3); // Sets 'a' to 1*1*1 = 1 float f = 0; // flatening float lambda = atan(pow((1 - f), 2) * tan(radians(Latitute.get(i)))); // lambda float y = radius * cos(lambda) * cos(radians(Longitute.get(i))) + Altitute.get(i) * cos(radians(Latitute.get(i))) * cos(radians(Longitute.get(i))); //swaped x&y float x = radius * cos(lambda) * sin(radians(Longitute.get(i))) + Altitute.get(i) * cos(radians(Latitute.get(i))) * sin(radians(Longitute.get(i))); float z = radius * sin(lambda) + Altitute.get(i) * sin(radians(Latitute.get(i))); vertex(x, y, z); LocationVector = new PVector(x, y, z); LocationVectors.add(new PVector(x, y, z)); } //endShape(); //points.endShape(); println(LocationVectors); } void displayLocationPoints(){ strokeWeight(10); stroke(0); } Answers you can do the "flattening" in setup() after the reading and store the results, which will save you a bunch of calculations in draw() and if the data doesn't change then you can create a PShape holding it all and just display that in draw(). java naming standards have all variables starting with a lower case letter, so latitudeAI is preferred. (classes start with a Capital) also if all the values are connected then make a class and have an ArrayList of that class. there are FAQs for this: thanks a lot. I should really work on my naming system. The draw() data doesn't change but it has a camera rotating around, so the display of the point array should be updating. I tried it with a class and a PShape, but it doesn't give me any visual. Can createPShape() even do a collection of points/vertices? Here's the code with a class and cleaned up (the previous had two data sets simultaneously). I am calling the drawPoints() function of the class in setup() and the display function in draw() DataPoints should be outside the for loop that starts on line 82, only the vertex call should be inside. Plus it needs to be DataPoints.vertex() (This is untested - I don't have the data) This is fine. With a pshape you define the data once. It is uploaded to the graphics card, once. Any camera changes are done by the graphics card in hardware and are lightning fast. The thing you avoid is calculations using the CPU and the data transfer. Thanks for the ideas. I tried some different versions in the last days and to be honest I am starting to feel a bit hopeless about it. Try1: Class: With PShape modified as you suggested. I think what the problem is that createShape() doesn't really do point clouds. The documentation says it is for geometries such as rectangles or custom shapes made from points etc. – Try2: A Function called in setup() with PShape Group created from an array of PShapes: it looks like this: It seems to work, the array has the right number of indices but with the grouping everything went blank. I suppose PShape group is not made for 88000 points. Try3: an ArrayList of PVectors. It is actually the same as drawing all points in draw() because it still has to loop through all the points in each frame to display them. The only idea that I still have is using the file ParticleSystePShape from the official examples and try to recreate it for my case. After all this program is creating a bizillion rectangles every frame. But to be honest I am lacking the brains to understand the example. I guess I would need help to even understand it. does this work? (my 2009-vintage video card (Nvidia 130M) does 450,000 with very little cpu but .5M kills it) but this, from 2011 and using Processing 1.5.1 and the GlGraphics library says i got 90,000 5 pointed stars (so 900,000 lines) before it started failing. Thanks a lot! That's a really good example. Apparently my old Macbook Air can only go up to 100 000 after this it gives me weird glitches – 300 000 kill it. Your example actually helped me figuring out what I did wrong. I needed to create an array of xyz coordinates and, when createShape() is called, only loop through the array to create the points. Apparently it didn't like the fact that I did the spherical coordinate conversion in the same loop. It is working now and the PShape method actually saves a lot of CPU in my case... totally worth it :) Thanks so much for your help! Here's a screenshot of the WIP since you could never run it without the data: Screen Shot 2016-05-29 at 19.30.26 That's the code that worked: in setup(): in draw(): that shouldn't matter, really. also, rL[i] isn't used outside the loop by the look of things so you don't need an array to store this value. in short, this should work (untested) Some more extra advises: :-B floatas much as you can. radians(longitudes.get(i))over & over, why not float lon = DEG_TO_RAD * longitudes.get(i);? float[]arrays btW. longitudes = new FloatList();, better w/ longitudes = new float[locationTable.getRowCount()];;) An even better idea: longitudes[], latitudes[], altitudes[] form 1 trio. Why not get all those 3 together as 1 PVector[] as x, y & z fields? *-:) And another alternative version where longitudes, latitudes & altitudes are already stored in PVector[] pre-converted to radians() plus pre-calculated w/ cos() + sin(): B-) If the Table or the PVector[] containers are not needed elsewhere within your sketch, why keep them around, given you'd only want the generated PShape? :-? In this latest example, there's a customized createShape() which returns a PShape according to the Table file + some other attributes: :> 8-X :D Thanks GoToLoop, I cleaned my naming. Always appreciate some advice on naming conventions, as I am a bit of a noob. I tried your last version and it works perfectly fine. I just wonder if it brings any advantage on the CPU usage? I am not sure if it works for my final code because color and dataTable are set in setup(). As a next step I will have to lerp from one dataset to another and map it to the altitude. i guess in that case I have to call the createShape() under draw()? Or can the createShape function be influenced by draw, so that color and altitude can be modified? Thanks guys for your help!
https://forum.processing.org/two/discussion/16830/arraylist-of-pvectors-setup-and-display
CC-MAIN-2019-47
refinedweb
1,579
56.66
import and export functions are available free china vpn download both through the GUI or through direct command line options. Secured import and export functions To allow IT Managers to deploy VPN Configurations securely, ). Free china vpn download this article describes how to change an IP free china vpn download address of a dynamically assigned IP address (those assigned via the DHCP )). jangan gunakan formulir ini untuk melaporkan bug atau meminta fitur pengaya baru; laporan ini akan dikirim kepada Mozilla, silakan laporkan masalah ini kepada Mozilla menggunakan formulir berikut. Hoxx VPN Proxy Dapatkan free china vpn download Ekstensi ini droid vpn orange tunisie untuk Firefox (id)) Jika Anda pikir pengaya ini melanggar kebijakan pengaya Mozilla atau memiliki masalah keamanan atau privasi, bukan pengembang pengaya ini. Selain melindungi identitas pengguna dan menyediakan sambungan internet yang aman, ExpressVPN juga diiklankan sebagai sarana untuk mendapatkan sekitar sensor internet, serta pembatasan geografis yang ditempatkan di situs web dan konten media streaming. Menonton konten yang Anda inginkan dari negara manapun di bumi, pada kecepatan yang. External Groovy scripts can be integrated simply by placing them in the scripts subdirectory of the Freeplane homedir. Such scripts can be used like any other built-in function of Freeplane. After some preparation we'll create the first script. Hi I am trying to set-up my home pc as a vpn server, so i can RDC to it from my laptop when ever i need to where there is a net connection. I have opted in for BT fon, so hopefully, soon, I can have nearly 24/7 access to anything from home if im not there. Free china vpn download EU: which is named, to create a Window Firewall rule, to do so navigate to the free china vpn download Control Panel and select Windows Firewall. You first need to open up the advanced Firewall interface, windows Firewall with Advanced Security. In the Windows Firewall window, appropriately enough, twitter is another forum like Reddit you can use to attain neutral reviews about VPN services that support free china vpn download steam. VPN for Steam Twitter. A. turning it into free china vpn download a lightweight, low-power VPN server. You could even install other server software on it and use it as a multi-purpose server. You could take a Raspberry Pi and install OpenVPN server software, a free china vpn download VPN (or virtual private network)) is a way of extending a private network a companys intranet, for example over a public network,navigate to: User ConfigurationPoliciesAdministrative TemplatesWindows ComponentsInternet Explorer Enable "Disable changing proxy settings" This will prevent free china vpn download individual users from setting their own proxy server settings. 2. You can add exceptions and have local intranet addresses bypass the proxy also.No quiero hacer este video tan largo solo queda recalcar que la idea fue tomada delr Union Binera y pues sin ms les dejo la vpn premium. Dieses Online-Lexikon von Wolfgang Bergt definiert mehr als 5.300 miteinander verlinkte Informatik-Begriffe how to use hot vpn for android rund um Computer und Internet. access social media, bypass censorship free china vpn download when travelling or living abroad: Use our VPN service to change your virtual location when visiting or living in a country where the internet is censored. Gaming sites and more. News sources,this time is inclusive of any time spent in proxy negotiation. This time will include when the browser is waiting for an free china vpn download already established connection to become available for re-use, time the request spent waiting before it could be sent. Additionally, Free china vpn download searching the GitHub pages I came free china vpn download across a posted fix.jIO 4G Data Plans JIo data free china vpn download plans might be cheaper but none of its 4G data plans have been officially released by the company as of July 2016.iP VPN (Cisco (800 series)) ADSL (D-Link (DSL-2640U ( free china vpn download D-Link 16 )) 6,vPN Pro - Free VPN proxy, connect as a hare to unblock sites, fastest - Connect free china vpn download successfully as a hare with high VPN speed. WiFi hotspot secure and protect privacy.cookie. 'nul this- _url url; s curl_init curl_setopt(s,CURLOPT _URL,) txt public function setReferer(referer)) this- _referer referer; public function setCookiFileLocation(path)) this- _cookieFileLocation path; public function setPost (postFields)) this- _post true; this- _postFields free china vpn download postFields; public function setUserAgent(userAgent)) this- _useragent userAgent; public function createCurl(url 'nul if(url!) dosto is trick me mai aapko jo Tarika bataunga uske liye aapko Sirf thoda sa dimag aur ek Android app ki jarurat padegi. Is free china vpn download trick me aap daily 2GB.sSL VPN Bookmarks via the SonicWall Virtual Office This article details free china vpn download how to setup the SSL VPN Feature for NetExtender and Mobile Connect Users, both of which are software based solutions.dont worry, you can still access the Live feature. French Taiwan: Traditional Chinese Turkey: Turkish United Arab Emirates: International English free china vpn download United Kingdom: International English United States: English Is your country not listed above? Slovakia: English South Africa: International English Spain: Spanish Sweden: Swedish Switzerland: German, the Netherlands, australia, so thats weird.) Plus you can also connect through an iptables proxy IP address out of the United free china vpn download Kingdom, canada, germany, france, singapore or Hong Kong. (Virginia is a state,) not a city, there are programs that can overcome this restriction, these programs are known as proxifiers and free china vpn download enable non-SOCKS aware internet application to use SOCKS proxies. But you will have to install additional third party software to make SOCKS more run independently.VPN : VPN (Virtual Private Network - ) - , . . the R8500 has the ability to broadcast three distinct network names, free china vpn download devices with 44 antennas). With three radios, the X8 optimizes WiFi performance across your network by using Smart Connect to strategically assign every device to the fastest WiFi possible. But with Smart Connect, w3.org/TR/xhtml1/DTD/xhtml1-transitional. "-/W3C/DTD XHTML 1.0 Transitional/EN" geoproxy google chrome "http www. Residential tenancies authority (RTA)) forms Queensland Civil and Administrative Tribunal (QCAT )) forms Useful templates free china vpn download Financial records Pool safety forms Other forms. Dtd" Forms and documents Property occupations forms Agents financial administration forms.
http://malopolskadays.eu/organizatorzy/free-china-vpn-download.html
CC-MAIN-2019-09
refinedweb
1,064
50.26
#include <SPI.h>#include <Ethernet.h>// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network.// gateway and subnet are optional:byte mac[] = { 0xA1, 0xA2, 0xD3, 0xC3, 0xF1, 0x2A };IPAddress ip(192, 168, 1, 118);IPAddress gateway(192, 168, 1, 1);IPAddress subnet(255, 255, 255, 0);// telnet defaults to port 23EthernetServer server(23);boolean gotAMessage = false; // whether or not you got a message from the client yetvoid setup() { // Open serial communications and wait for port to open: Serial.begin(9600); // loop() { // wait for a new client: EthernetClient client = server.available(); // when the client sends the first byte, say hello: if (client) { if (!gotAMessage) { Serial.println("We have a new client"); client.println("Hello, client!"); gotAMessage = true; } // read the bytes incoming from the client: char thisChar = client.read(); // echo the bytes back to the client: server.write(thisChar); // echo the bytes to the server as well: Serial.print(thisChar); }} The arduino never gets past the setup code, I have enclosed a screenshot of the output That screenshot is of your ipconfig on your PC. Ethernet.begin(mac); Guys I need an answer on my question about the mac adress. I read that newer board such as mine has a hard wired mac adress. Is there a way to set a new one or read it out somehow? Can I still use the ethernet shield or can I get a hammer and smash my board which costed me €35,- to $h!T?? Download all files and replace the "\libraries\Ethernet\src" folder in your Arduino IDE. This will update the "utility" folder also under "\libraries\Ethernet\src". In the W5100.h file(\libraries\Ethernet\utility\w5100.h), uncomment the device(shield) you want to use. By default, "WIZ550io_WITH_MACADDRESS" is commented and if you uncommnet it, you can use the MAC address stored in the WIZ550io. #if defined(WIZ550io_WITH_MACADDRESS) // Use assigned MAC address of WIZ550io;#elsebyte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};#endif Failed to configure Ethernet using DHCP server is at 0.0.0.0 I am also unable to find the ethernet shield in the network devices on my PC.
http://forum.arduino.cc/index.php?topic=135140.0;prev_next=prev
CC-MAIN-2017-39
refinedweb
362
64.51
What's new with Scripting for the Java platform? By sundararajan on Nov 12, 2007 Sorry about the looo..ng hibernation! Now, it is time for updates on the Scripting project. Three new jsr-223 compliant script engines: Happy scripting! - Yoko Harada updated JRuby script engine with JRuby 1.0.2 and added few other fixes in engine code. - I've pre-built binaries of the project (uploaded the .zip and .tar.gz files) - JavaFX Script interpreter had jsr-223 support. Now, the JavaFX Script compiler has jsr-223 support -- you may want to checkout JavaFX Script compiler project. The following code works as expected: import javax.script.\*; public class Test { public static void main(String[] args) throws Exception { ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine e = m.getEngineByName("javafx"); e.eval("<<java.lang>>.System.out.println(\\"hello\\");"); } } - Xavier Clerc sent a link to the jsr-223 script engine for the Object Caml language. Thanks! - Alexandre Bergel sent a link to the jsr-223 script engine for the Smalltalk language. Thanks!
https://blogs.oracle.com/sundararajan/entry/what_s_new_with_scripting
CC-MAIN-2014-15
refinedweb
169
68.57
MongoDB Description and Overview. NERSC provides a set of MongoDB nodes for users that wish to use MongoDB with their scientific applications. How to Use MongoDB The MongoDB command line client is available at NERSC on Cori, and Edison, and can be used to directly connect to mongodb via the command line. There are also language specific client drivers. Requesting a Mongo Database Users can request a MongoDB database for their project using this form. Here are some considerations for when to use MongoDB as your scientific datastore. MongoDB is suitable for use cases where - Your data model and schema are evolving rapidly - You need a simple query interface to access the data i.e. you would like to interact with JSON objects directly - Your data is mostly non-relational - i.e. you data exists in self contained objects with minimal cross linking between objects The MongoDB setup at NERSC may not be ideal in cases where - You need to do high volume transactional data writes. We can handle bulk loads and a small volume of writes at a time, but our current setup is not optimized for heavy write volumes - Your data model is heavily relational (lots of JOINs across data tables). Use the mongodb client If you wish to directly access MongoDB via the command line, you can use the Mongo JavaScript shell. On a NERSC system, type the following commands to use Mongo: % module load mongodb % mongo mongodb01.nersc.gov/yourdb -u dbuser -p MongoDB shell version: 2.6.4 Replace yourdb and dbuser with the name of the mongodb database and user provided to you by NERSC. You may need to replace mongodb01 with mongodb03 if you are going to the development host. Use pymongo Mongo DB can also be invoked directly from within your code using the language specific client API. Here we show you how to use the pymongo client for Anaconda Python % module load python To access MongoDB through your python code #!/usr/bin/env python import pymongo p = pymongo.... Documentation Extensive on-line documentation is available. For questions about MongoDB at NERSC, please contact consult@nersc.gov. Availability
http://www.nersc.gov/users/data-analytics/data-management/databases/mongodb/
CC-MAIN-2018-13
refinedweb
356
54.02
See also: IRC log <m4nu> rob: Hi Rob Sanderson, co-chair for Web Annotations WG... Ben Young is a co-chair. <m4nu> Rob: Academically, I've always been interested in annotations, allows people to give feedback on annotations. <m4nu> David: Hi, David Burns - co-editor for web ??? specification - user emulation in the browser, wanted to see what this was about. <m4nu> John: Hi John Jansen from Microsoft, working on Webdriver spec, mapping test suite to spec, leveraging annotations to map words in a paragraph to spec - interested in where it's going. <m4nu> Malena: Hi Malena - working on automatic annotation on fashion data - image recognition on Semantic Web. <m4nu> Amy: Hi just joined <m4nu> Sarven: Joined web annotations recently, at MIT - <m4nu> Alex: Hi Alex Milowski - worked on annotations and scientific data - anything web/annotations pique my interested. <m4nu> ???: Wanted to see what's going on here. <m4nu> Philippe: ? Hi , from Paris - research infield, would like to extension of annotatin to semantic <m4nu> Kazui: Kazui Sako - wanted to learn more about web annotations - personal data store, manage it, control it, etc, working on it. <m4nu> Takari: Takari from ??? <m4nu> Ben: Hi Benjamin Young with Hypothesis and co-editor of data model. <m4nu> Rob: Just wanted to do a brief walktrhough - five to ten minutes . Let's keep questions until the end, put yourself on queue. <m4nu> Rob: Why people care about annotations - user comments on pages - don't read the comments, but want to solve that problem, want to tag posts, make review of products, academic paper, describe content that's not easily accessible for screen readers <m4nu> Rob: Transcription of video, audio, replying in a threaded mode could be an annotation on an annotation, copyediting - instead of having editor wars, anyone might be able to propose a change by making an annotation. <m4nu> Rob: System for annotating and moderating - those have been indirections on content, moving your own annotations between systems. Moving annotations from Kindle to another ereader. <m4nu> Rob: Doesn't need to go to anyone outside your circle. We have a long list of use cases <m4nu> Rob: We lay out a set of sorts of things you'd want to do. <m4nu> Rob: A brief history of annotations on the Web. This was in Mosaic in 1993 - annotations. Running a server where annotations would be stored, would cause legal and operational problems. <danbri> see also <m4nu> Rob: Even since very beginning of Web, notation of users annotating the Web - both read and write has been part of the vision and part of technical reality. Now that we have superior capabilities, time is right again to try it. <m4nu> Rob: In 2001, there was an Annotea protocol <m4nu> Rob: In 2009, Google created Sidewiki, but stopped in 2011 <danbri> Announcing www-annotation@w3.org and www-collaboration@w3.org (1996) <m4nu> Rob: In 2011, the Open Annotation Community Group was created - OAC was focused more on humanities. <bigbluehat> also, those email lists are public, so *please* join in the conversation <m4nu> Rob: In 2014 the Web Annotation Working Group was chartered. <m4nu> Rob: You have someone that creates a page, then someone else annotates that web page. <m4nu> Rob: We have a serialization using JSON-LD to write that annotation down, write that down to persistent storage mechanism. <danbri> see also e.g. 1998 debates around Netscape "what's related" functionality — (Netscape fetched RDF annotations from its related link service for each page you viewed) <m4nu> Rob: We also have an anchoring mechanism to talk about a bit of the page. <m4nu> Rob: If you have a small range of text, fragments don't help you. Commenting on regions of images rather than ranges of text. <m4nu> Rob: The annotations may need to be read by the person or other people as well, new user might want to comment on the annotation. <m4nu> Rob: They may have their own store. Final step, as far as protocol goes, for notification, for all annotations, it would be useful to have a system that aggregates them. Publish that there were annotations about image - tells publisher, maybe render them as a part of the display. <m4nu> Rob: That's the architectural vision that you're making good progress towards - we have two WDs, data model <m4nu> Rob: We are trying to simplify implementations, our focus is on looking at JSON and JSON-LD for ease of development, so that devs can look at document, rather than having to worry about lots of RDF stuff, even though its RDF underneath. <m4nu> Rob: Focus has been on CRUD - use hypermedia APIs to do that, also discovery, fortunate enough to have TimBL to join our meetings over last couple of days - if you can't discover annotations and where you create them, one to one mapping of client and server - that's one area that we're trying to solve w/ Web Architecture. <m4nu> Rob: Ongoing implementation - we don't want new query languages - we're looking at what the minimal filtering requirements are that might have millions of annotations, internationalization <m4nu> Rob: On client-side, we're looking for 'find text API' - context - we need to work on finding text. <m4nu> Rob: We are trying to make it simpler, and make it more internationalized. <m4nu> JohnJansen: Is there deep linking in the specs? A URI to point to an anchor? <m4nu> Rob: There has been discussion around find text API and to see if that could be used in the fragment - you wouldn't want to put the entire text of a chapter into a URI - so there are technical issues - around fragments and URIs <m4nu> Rob: Technically, fragments are defined by media type - lots of requirements and discussion, we may not deliver anything in that space. We do have people asking for exactly that. <JohnJansen> :-) <m4nu> Rob: This stuff is pretty simple (shows example) <kevinmarks> how small a fragment is not useful? <m4nu> Rob: There are technical details that we could go through. <kevinmarks> across the entire web a ten word phrase is pretty good at uniqueness <m4nu> Rob: if you want to comment on our specs, you can annotate them - we're dogfooding. <kevinmarks> within a document how small a phrase do you need? <m4nu> Rob: To try and dogfood, we enabled annotation on the working drafts. <m4nu> Rob: There are specs on TR space and on Github. <m4nu> ???: What about the use of this stuff for ePub standard? <m4nu> Rob: Working with markus on epub - been implemented in a few reading systems, timing is always problematic. <kevinmarks> yep <kevinmarks> if someone has done work on uniqueness length I'd love to hear about it <m4nu> Rob: There are a few changes from the CG spec that are not backwards compatible - for example, to embed text body - use EARL but it was never sent to CR> <csarven> BartvanLeeuwen: There is <JohnJansen> +1 to kevinmarks <m4nu> Rob: There are a few changes that would have to be made, but relatively minor. <m4nu> Rob: Several of us are also a part of digital publishing WG - we share a staff contact. <m4nu> Rob: There is ongoing conversations between communities. <m4nu> ???: All annotations are human produced? <m4nu> Rob: At the moment, the majority of the use cases assume human produces them, in scientific area - a lot of work being done in NLP. <m4nu> Rob: UIMA annotates text and uses CG spec to produce those annotations, all machine produced. We've done our best to allow for those use cases without modifying the model either way. if there are issues, we dont' want to make them unusable. <m4nu> Helena: Machines have special knowledge - the knowledge that they have is of a different quality. <m4nu> Rob: One thing we don't have in there yet is the confidence of the implementation - only 50% confident (a machine might say that) <m4nu> Rob: Since focus has been on annotating web resources, we haven't put it into the model - since it's JSON-LD, we can add those features later w/o breaking the model. We had a meeting w/ I18N folks, NLP interchange format on Monday, they're interested in assisting to see if NIF can use annotation model. <m4nu> Rob: Confidence is one of the requirements. <m4nu> Helena: I'm part of multi-modal interaction WG - we have EMA - supports annotation use cases also - have supported recommendation already - in discovery w/ another approach using semantic web also. <Zakim> kevinmarks, you wanted to ask if there has been work done on uniqueness length <kevinmarks> I'm not physically present, so if someone can read that out… <m4nu> manu: PLACEKEEPR <m4nu> Rob: There has been some work done on uniqueness <m4nu> Rob: 32 characters was good enough for some very high percentage... 64 characters was almost 100% accurate - experiment was wikipedia corpus, randomly select region of text, then see if you got back to the right block of text - so that test was done in english. <m4nu> Benjamin: If you are only sending the thing you want highlighted, in those scenarios, we provide prefix and suffix, which help w/ reanchoring. In Hypothesis, we have robust anchoring to provide edit space away from text. <Zakim> m4nu, you wanted to ask where are you in your timeline? <kevinmarks> I suspect human generated ones would be word rather than character focused <m4nu> manu: PLACEKEEPER2 <m4nu> Rob: We have a two year charter, we're pretty much halfway through - we're confident that we'll get the model and protocol and at least a stripped down of find text down to CR by middle of next year. <kevinmarks> is the 64/32 for unique across whole wikipedia corpus or within a page? <m4nu> Rob: Then it's a question of how long CR takes - if we have to handle an extension - that would likely be granted. <m4nu> Rob: We would hope that the next year will create enough momentum around things that we're not going to take to CR to get more use cases and requirements to know what to fulfill them, then sketch out pre-FPWD material. <m4nu> Rob: We don't want there to be a gap <m4nu> Rob: We're certainly thinking about it - people wanting to participate over next year would help w/ continuation of group. <m4nu> Bart: How would this work w/ real-world objects? <m4nu> Rob: If there is a URL to the object, you can talk about it - it's RDF, so all you need is a URI for the object. <m4nu> Bart: If you take a real-world object, would augmented reality see the annotations. <m4nu> Benjamin: Data model is RDF-based, you could put in geolocation - specific resource is more fine-grained, a component of a thing - highlight - form of selectors, prefix quote suffix, data position inside data file, text position, those are the ones that run into I18N problems. With a different set of selectors you could do a geolocation type thing. <m4nu> Bart: It's been a while since I read the spec, should work. <m4nu> Rob: Yes <m4nu> Benjamin: Yeah, should work. <m4nu> Rob: Catarina's project after she left Flickr - HistoryPin? wants to annotate items in the real world. <Zakim> kevinmarks, you wanted to ask if the uniqueness was within a page or through whole corpus. <m4nu> Benjamin: Other use case that came up - digitally storing annotations in physical books - page number, use digital selector, text position to anchor inside book - closer shot at anchoring - we had most of what they needed. <m4nu> Kevin: Was it the entire wikipedia corpus or per page? <m4nu> Rob: it was on a per-page basis - so if you use a fragid on a page, what's the likelyhood that you mis-link. <m4nu> Rob: You need to see how long it takes for the anchoring to become obsolete... don't remember if anchoring was through time. <Zakim> m4nu, you wanted to ask about credentials and digital signatures. <m4nu> Manu: What about digital signatures, what about credentials, where does that fit into your timeline? <m4nu> Rob: Very trivial agents that can be associated with annotation, target could be another organizations, however, w/o credentials or signatures you could trivially spoof information - publish annotations that claim you're the author of body - reputation models, that's an issue. <m4nu> Rob: This is really important to get right - if you want to spam someone, million followers, a million followers get spammed w/ extraneous content - we know it's going to be important - we want to make sure it'll be possible in future, we don't have time to do that right now, but it's certainly on radar to work on actively - would want to get started - could be another tick mark on ledger <m4nu> to seeking a second charter <Zakim> alexmilowski, you wanted to ask What is the status of the other items on the charter or have they been rolled up into the existing WD documents? <m4nu> Alex: Are these things rolled into other things, are there things that still need to be done - six areas of work - serialization, data model, protocol, client-side APIs that use protocol. <m4nu> Rob: Data model for specification, model + vocab + serializations - protocol stands alone, but doesnt have stuff for notification or search <m4nu> Rob: We can't solve search in this iteration - client-side API, robust anchoring - great if you have experience requirements interest - find text API will start to be addressed for robust anchoring. <m4nu> Rob: However, we do not yet have a client-side, make it easy to create/manipulate annotations in a browser - there was a pre-WD spec written up by Nick Stenning, but we haven't been able to take that forwards w/ enough momentum, one of the issues in the WG - lack of input from WebApps side. We've been trying to work with WebApps - find text, trying to make sure we don't spec something that <m4nu> doesn't work w/ other APIs. <m4nu> Rob: Call for help in that space - collaboration. <Zakim> m4nu, you wanted to ask abou t@id and @type <m4nu> Rob: If our answers are not complete, please ask. <m4nu> Benjamin: There are a lot of JSON databases that use ID and Type in a different way - annotator already uses UUID, for those developers, they would have to change the context than putting square brackets - so namespace is a new thing - sorry about brackets - lower pain point, change all IDs to URLs. We felt this could co-exist next to existing JSON - could be thrown away. <m4nu> Benjamin: Leaving them around it problematic - but less so than ... <m4nu> Benjamin: Spec - context is optional - could express JSON in this shape, or you could upgrade it - you could add a link header. <scribe> scribenick: rhiaro_ m4nu: the best option seems to be to get rid of all the @ signs to make it ieasier for js developers ... alias @id to id and @type to type ... are you working with legacy data that has id and type? bigbluehat: we're working with annotations systems all over the web, and we're trying to get them to upgrade ... this was the easiest way. So we're not destroying keys they already depend on ... It's still an open question ... It was put in and taken back out ... We could consider undoing that m4nu: how much of your user base are you going to destory by introducing this weird @ stuff into this data ... do you want to get more adoption at the risk o fmaking the data uglier forever? bigbluehat: I come from CouchDB land which has thes e ugly underscore prefix things ... people have just got used to these ... as being not their stuff ... evertyhing else can be there stuff ... that's not great either ... we don't want to pollute someone elses keyspace at all ... Some amount of developers, mongo and couch, are okay with the shape of their json changing if I use that database, I now have these keys I don't like ... But the @ one is a little awkward because it requires 4 more characters, underscore does not m4nu: we use mongo and couch and have aliased everything and it worked fine bigbluehat: I just mentioned those as they are doing awkward ids m4nu: just because they are doesn't mean you do ... THe @ signs were put in there so legacy json data could easily be ported to json-ld ... I understand you have legacy data, I understand you don't want to alienate those devs or make them rewrite applications, that's valid ... but if you could change it and they could agree the change to their data and their apps, and have a nicer format that looks just like json, that would be best azaroth: one other issue that came up in the discussion was we want to use things like activitystreams for having eg. a collection of annotations ... if at al lpossible we don't want to create another collectoin spec ... as2 uses @id and @type ... we were concerned that if we did aliasing and they don't and we wanted to use them together that would cause problems m4nu: right, that would be a problem ... when we first did the @id thing we hoped that would never happen, but now it is ... and in schema.org tantek: we can fix it m4nu: alias it danbri: just the @ sign? m4nu: alias any json-ld keyword that starts with an @ sign ... to not have an @ sign bigbluehat: as1 has id but it is a uri ... so no problem there ... and means the same thing ... and used objectType earlier, so no cost to change ... For most of the formats an id and type shift is probably the most marginal change that they'd have to make ... Other things are harder ... Thank you. I didn't know about json-ld, could you put that in the spec <tantek> m4nu: m4nu: we're trying to put together a best practices thing about that tantek: could you file an issue against as2? m4nu: okay azaroth: after 5, q is empty! <m4nu> scribe: m4nu <tantek> <danbri> m4nu, got an example of proper @context mapping syntax for @type -> type etc? <danbri> i.e. for Tantek: Most of those annotations are post-types that they're annotating - if you want to look at more examples, is that compatible w/ your model - as input to social web work - best examples in the model - here are people posting replies/reviews. Mostly JSON-focused. Benjamin: take found JSON, wordpress comments that are not JSON - upgrade those into the model ... Schema.org has JSON shapes that match or don't match - what you're doing, what you're not doing. Dan: No way world will adopt single mechanism for annotations - there are too many different ways to do it. Benjamin: This annotation, if you want 3 different types - knock yourself out. xidorn: One more annotation use case - not aware of - why east asian video sites - Danmaku - text host where video is created, text will move with the video in some direction - in-video comment, probably another use case. Benjamin: We don't have that written up as use case - fragment selector - media fragment on time-based positioning - this video and this 10 second mark. ... Any fragment-based selector ontology - 10 that you dereference - make it an RFC - reference non-RFC specs. - here's value hash, media time <tantek> bigbluehat, hopefully you can mention as well! Benjamin: If XPointer had become something, it would've worked. <tantek> fragmentions is essentially a modern HTML-based replacement for XPointer ranges Rob: The list of things is not affected - these are examples. Most of them can be used in URIs. From 30 seconds to 60 seconds of this video, fragment according to fragment, media fragment <danbri> m4nu, ok i found :) <Zakim> m4nu, you wanted to ask about type coercion in JSON-LD. Manu: Why do you have so many @id? Rob: We had a long discussion about this - let's take it to hallway discussion.
http://www.w3.org/2015/10/28-annotation-minutes.html
CC-MAIN-2020-16
refinedweb
3,346
67.79
import "github.com/golang/go/src/net/http/internal" Package internal contains HTTP internals shared by net/http and net/http/httputil. LocalhostCert is a PEM-encoded TLS cert with SAN IPs "127.0.0.1" and "[::1]", expiring at Jan 29 16:00:00 2084 GMT. generated from src/crypto/tls: go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h LocalhostKey is the private key for localhostCert. but does not send the final CRLF that appears after trailers; trailers and the last CRLF must be written separately... Package internal imports 6 packages (graph). Updated 2019-06-30. Refresh now. Tools for package owners.
https://godoc.org/github.com/golang/go/src/net/http/internal
CC-MAIN-2019-51
refinedweb
121
52.97
Hello, I hope you are having a great time. Could you please help me about the following problem? Because the range of the target values is completely different and oscillates between 0 to 6000, the target should be normalized to train the model. For example : t_mean = torch.mean(target) t_std = torch.std(target) t_normal = (target - t_mean)/t_std How can I denormalize theprediction if the loss function depends on the first and second derivatives of the output of the NN w.r.t the input: def P_loss(x,y): first_derivative = torch.autograd.grad(y, x, grad_outputs, create_graph=True, retain_graph=True)[0] second_derivative = torch.autograd.grad(first_derivative, x, grad_outputs, create_graph=True, retain_graph=True)[0] eq = 4*first_derivative[:,1] - second_derivative[:,0] loss = torch.mean(eq**2) return loss I think pred = model(input) pred = pred * t_std + t_mean does not work correctly.
https://discuss.pytorch.org/t/un-normalizing-the-prediction-with-different-loss-function/110404/4
CC-MAIN-2022-33
refinedweb
138
51.85
Search Criteria Package Details: xapps-git 1.2.2.r0.gd957699-2 Dependencies (7) - libgnomekbd - git (git-git) (make) - gobject-introspection (gobject-introspection-git) (make) - meson (meson-git) (make) - python-gobject (python-gobject-git) (make) - python2-gobject (python2-gobject-git) (make) - vala (vala-git, vala0.26) (make) Required by (13) - cinnamon-git (requires xapps) - cinnamon-screensaver-git (requires xapps) - cinnamon-session-git (requires xapps) - cinnamon-slim (requires xapps) - mintlocale (requires xapps) - mintstick (requires xapps) - mintstick-git (requires xapps) - nemo-git (requires xapps) - timeshift (requires xapps) - xed-git (requires xapps) - xplayer (requires xapps) - xplayer-git (requires xapps) - xreader-git Latest Comments eschwartz commented on 2018-04-19 18:13 "working", yes. "good", no. I've taken this opportunity to adopt the package and base it off of my [community] package. Things you missed: pygobject-devel is wrong and not needed at all, it does need to be able to import giunder both python and python2 (which means python{,2}-gobject). The pkgver is wonky. Some scripts require python in depends, unless you remove them which I have done because they are useless and require e.g. Debian-specific renames of the gist utility. meson should use the "plain" releasetype in order to fully respect makepkg.conf oberon2007 commented on 2018-04-16 21:58 I made a working PKGBUILD here: oberon2007 commented on 2018-04-16 21:22 PKGBUILD needs update! /tmp/yaourt-tmp-user/aur-xapps-git/./PKGBUILD: line 27: ./autogen.sh: No such file or directory xapps is using meson build now. willemw commented on 2017-10-13 07:42 @kernelmd: It needed some more changes. Updated PKGBUILD file: kernelmd commented on 2017-10-13 06:33 willemw, unfortunately I can't test it atm, as I don't have arch installed. The error should be fixed by installing gtk-doc package. Please try it and reply here with the results, so that I could update the package. willemw commented on 2017-10-13 06:20 ./autogen.sh: line 28: gtkdocize: command not found ==> ERROR: A failure occurred in build(). PKGBUILD of xapps has: makedepends=('gnome-common' 'gobject-introspection') kernelmd commented on 2016-11-06 10:04 oberon2007, thank you for feedback. I have just updated the package. oberon2007 commented on 2016-11-03 10:44 depends=('libgnomekbd') needs to be added. Thank you for the x-apps packages! :)
https://aur.archlinux.org/packages/xapps-git/
CC-MAIN-2019-18
refinedweb
390
57.06
Did you try out creative excuse #432 on your boss this week? Were you tempted to? Hopefully, you didn't have to. Part 1 of this series helped you understand how to work with Microsoft® Excel® spreadsheets in Java™ technology (see the link to "Read, recycle, and reuse: Reporting made easy with Excel, XML, and Java technologies, Part 1" in Resources). Simply download Apache POI and set up to use it, and soon enough, walking through an Excel spreadsheet is almost as easy as walking through a park. And almost as green. But reading Excel files is only a start. This installment shows you how to use Apache POI and the XML Object Model (XOM) to store an Excel file in XML objects. Then, you can recycle those objects to write an entirely new Excel spreadsheet and XML file. The sample application The sample application contains an Excel spreadsheet called Employee_List.xls from the fictional Planet Power corporation. The Big Boss has convinced Planet Power's top employees to donate 1% of their salaries to his favorite cause: the Genetically Engineered Enormous Wild Hamster Interplanetary Sanctuary (GEE WHIS). The sample application calculates the amount and creates an XML report to rush to the sanctuary. Meanwhile, the application writes an Excel spreadsheet for the Big Boss. To follow the examples in this article, download the samples and extract the files to C:\Planet Power. Then, start Eclipse. Employees2 Eclipse project To import the Employees2 Eclipse project containing the sample application, perform these steps: - In Eclipse, right-click in the Package Explorer, and then click Import. - Expand General, and then select Existing Projects into Workspace. Click Next (Figure 1). Figure 1. Bring an existing project into the workspace - Click Browse beside Select root directory, and then navigate to C:\Planet Power\Employees2. - Select the Employees2 folder, click OK, and then click Finish (Figure 2). Figure 2. Finish importing a project into Eclipse The Employees2 folder should appear in the Package Explorer pane. Note: For this project, use the file ExcelXML.java in the Employees2 project under src\default_package. Getting started In Part 1 of this series, your first step is to import Apache POI along with exception and file-handling classes (see Resources for the link to Part 1). In addition, you'll need to add some XML API classes along with classes for working with numbers, as in Listing 1. Listing 1. Importing classes (ExcelXML.java) // File and exception handling imports import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; // Apache POI imports import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFHyperlink;FDataFormatter; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; // XOM imports import nu.xom.Document; import nu.xom.Elements; import nu.xom.Element; import nu.xom.Attribute; import nu.xom.Serializer; // Imports for later calculations import java.text.NumberFormat; After importing the classes,you're ready to begin programming inside main(). Handling files The code in Listing 2 represents an exception-handling structure for file ( IOException) and number conversion ( ParseException) errors. Listing 2. Set up exception handling (ExcelXML.java) public class ExcelXML { public static void main(String[] args) { try { // Put file and number handling code here. // End try } catch (IOException e) { System.out.println("File Input/Output Exception!"); } catch (ParseException e) { System.out.println("Number Parse Exception!"); } // End main method } // End class block } Now you can begin to work with XOM. XOM, Document, and XML objects XOM simplifies working with XML by parsing it into objects that represent an XML document's pieces. The class that represents an entire XML document is nu.xom.Document. From the Document, you can add or access other pieces. Some classes for working with XML include: nu.xom.Builder nu.xom.Document nu.xom.Elements nu.xom.Element nu.xom.Serializer The main pieces of XML are called elements. An element consists of a pair of tags and the content in between. Here's one example of an element from a sample file called weather_service.xml. <dawn>07:00</dawn> The words dawn and their brackets ( <>) and slash ( /) are called tags. The 07:00 is the content. Elements can contain other elements, text content, or both. A containing element is called a parent, and the elements inside are called child elements or children. In XOM, elements are represented by nu.xom.Element objects. A set of elements is a nu.xom.Elements object. The root of all good To find elements, use the one element every well-formed XML document is guaranteed to have: the root element. The root acts as a container for every other element. If a document doesn't have a root, it's not proper XML. To find the root, use getRootElement() on the Document object. Getting just one element opens strategies for exploring the document. Want to work with the root's children? Get a list of all child elements or child elements with a specific name using variations of Element.getChildElements(). Want a single element? Get only the first child element with a specific name from Element.getFirstChildElement(). Does this seem familiar? Iterating through an XML document to find children of children is similar to iterating through an Excel worksheet. In the previous article, you saw how Apache POI's getStringCellValue() method retrieved a string value from an Excel HSSFCell. Similarly, XOM uses Element.getValue() to get string content from an XML element. However, unlike working with cells, working with XOM Elements does not require testing the data types. XML is all text. Excel-XML mashup and XML markup When traversing spreadsheets and extracting data, you can store the data in any number of objects: Strings. Arrays. Squirrels. This article uses XML elements. (That way, it's easier on the Squirrels.) It also offers some insight into translating between the two formats. Listing 3 prepares a new HSSFWorkbook and XML Document to store the workbook's information. Listing 3. Prepare a workbook and an XML Document (ExcelXML.java) // First, create a new XML Document object to load the Excel sheet into XML. // To create an XML Document, first create an element to be its root. Element reportRoot = new Element("sheet"); // Create a new XML Document object using the root element Document XMLReport = new Document(reportRoot); // Set up a FileInputStream to represent the Excel spreadsheet FileInputStream excelFIS = new FileInputStream("C:\\Planet Power\\Employee_List.xls"); // Create an Excel Workbook object using the FileInputStream created above HSSFWorkbook excelWB = new HSSFWorkbook(excelFIS); Does something seem backward about Listing 3? The code creates a new Element before it creates a Document. Why? A brand new Document requires one thing: an Element to be its root element. Remember, the Document can't represent a well-formed XML document without having a root element. Therefore, you must pass it a root element when you create it. In contrast, you can create elements that don't belong to a root. You can leave them as free-floating elements or append them to a document root or other elements. However, before you start, you should plan the structure of your XML. XML structure XML describes and formats data, mainly through elements and attributes. Attributes are name-value pairs. The name part of an attribute describes the data the attribute holds. The value of the attribute is its data. Writers of HTML code are familiar with attributes such as: <font size="12">Hello, Planet!</font> The entire listing is an element. The tag is <font>. The attribute is size="12". The name of the attribute is size. Its value is 12. The equal sign ( =) joins the two. Generally, data is stored in elements, while metadata is stored in attributes. So, how should the Employee_List.xls workbook translate to XML? Markup method 1: mimic workbook structure One way to structure the XML is to mimic the physical structure of an Excel workbook. Consider Listing 4. Listing 4. XML structure based on general workbook structure <sheet> <row> <cell> Thumb </cell> <cell> Green </cell> <cell> Growing Plants </cell> <cell> 5:00 AM </cell> <cell> 2:00 PM </cell> <cell> 150,000 </cell> </row> </sheet> With this format, the rows and cells are clear. But what data does each cell hold? Is 5:00 AM the employee's start or end time? What about using the column name as an attribute of the cell? If maintaining the Excel spreadsheet structure is important, that might work. However, in XOM, without learning how to write XPath queries, there is no easy method to extract a collection of elements based on their attribute values. With the column names stored as attributes, extra code is required to locate a collection of all of the elements from a specific column. Because XOM contains a method to find elements by their names, consider using the Excel columns as element names rather than as attributes. Markup method 2: mimic the data structure Instead of basing XML on the presentation of data, consider a structure that describes the data. That's what XML does best, as Listing 5 shows. Listing 5. XML structure based on describing data <EmployeeData> <Employee> > </Employee> </EmployeeData> This approach allows you to use the getChildElements("Salary") method on each Employee element to quickly find the employees' salaries. However, using Excel column names for the element names is risky. Excel columns can use characters that are not valid in XML element names, such as spaces. So, be sure to scrub those characters out of potential element names. To structure the data this way, you must be familiar with the data. It would be difficult to calculate programmatically that a row in the Excel spreadsheet should be called an Employee in the XML. It would also be difficult to calculate a name for the root element ( EmployeeData in the above example). Also, what happens if the structure changes or the Big Boss wants to recycle the code for other spreadsheets? Spreadsheet rows could list types of hamsters rather than employees. You would then have to adjust what the program calls the rows. Markup method 3: Excel XML mashup blend Consider blending the Excel-structured XML with the data-structured markup, as in Listing 6. Listing 6. Blending workbook structure with data-based markup <sheet> <row> > </row> </sheet> If the first row in each Excel spreadsheet contains column names, this blend could be flexible enough to work with several Excel workbooks. Because the data in the document and rows might not be consistent between spreadsheets, you can use the generic sheet and row as element names, and they will still have meaning to programmers reading the code. Note: As with pure data-centric markup, beware of illegal characters weaseling into XML element names. This article uses an XML-Excel blended format to store cell values. But what about tracking other cell information, like data type and formatting? Data type and formatting are metadata. Depending on what metadata must be preserved, you can use attributes like dataFormat and dataType. Coding to convert After deciding how your XML should look, begin storing Excel data in XML elements. Use the same loops to traverse the Excel spreadsheet as in Part 1 of this series (see Resources for the link). Then, add XML. Listing 7 recycles Excel-reading code from the previous article. Listing 7. Start traversing through the Excel spreadsheet (ExcelXML.java) // Traverse the workbook's rows and cells. // Remember, excelWB is the workbook object obtained earlier. // Just use the first sheet in the book to keep the example simple. // Pretend this is an outer loop (looping through sheets). HSSFSheet oneSheet = excelWB.getSheetAt(0); // Now get the number of rows in the sheet int rows = oneSheet.getPhysicalNumberOfRows(); // Middle loop: Loop through rows in the sheet for (int rowNumber = 0; rowNumber < rows; rowNumber++) { HSSFRow oneRow = oneSheet.getRow(rowNumber); // Skip empty (null) rows. if (oneRow == null) { continue; } As you iterate through the spreadsheet's rows, create XML elements to represent the rows, as in Listing 8. Listing 8. Create a row element (ExcelXML.java) // Create an XML element to represent the row. Element rowElement = new Element("row"); Don't attach the rows to the Document yet, in case you have empty rows or null rows. If the row isn't empty after adding cells, you can attach it to the root element at the bottom of the row loop. Next, start the inner loop to read the cells, as in Listing 9. Listing 9. Continue to iterate through the Excel cells (ExcelXML.java) // Get the number of cells in the row int cells = oneRow.getPhysicalNumberOfCells(); // Inner loop: Loop through each cell in the row for (int cellNumber = 0; cellNumber < cells; cellNumber++) { HSSFCell oneCell = oneRow.getCell(cellNumber); // If the cell is blank, the cell object is null, so don't // try to use it. It will cause errors. // Use continue to skip it and just keep going. if (oneCell == null) { continue; } Once you're inside the inner loop, create an XML element to represent the cell, using the appropriate column name as the element name. In Listing 10, because element names can't be empty, each name defaults to header. After the first row, calculate a new name based on the data stored in the first row elements, which contain the Excel spreadsheet column names. Listing 10. Create elements for the cells using the column names as element names (ExcelXML.java) // Set up a string to use just "header" as the element name // to store the column header cells themselves. String elementName="header"; // Figure out the column position of the Excel cell. int cellColumnNumber = oneCell.getColumnIndex(); // If on the first Excel row, don't change the element name from "header," // because the first row is headers. Before changing the element name, // test to make sure you're past the first row, which is the zero row. if (rowNumber > 0) // Set the elementName variable equal to the column name elementName=reportRoot.getFirstChildElement("row").getChild(cellColumnNumber).getValue(); // Remove weird characters and spaces from elementName, // as they're not allowed in element names. elementName = elementName.replaceAll("[\\P{ASCII}]",""); elementName = elementName.replaceAll(" ", ""); // Create an XML element to represent the cell, using // the calculated elementName Element cellElement = new Element(elementName); A lot happens in Listing 10. In the long line in the middle beneath the comment, // Set the elementName variable equal to the column name, elementName is set equal to something. Reading the end of the line, you can see it's set to the text value inside an element using getValue(). Which element's value does it use? Inside the reportRoot, inside the first row element ( reportRoot.getFirstChildElement("row")), the code locates a child element by its index number using getChild(cellColumnNumber). You have already stored the first row of the spreadsheet in the first row element, so the values of the row's child elements are the column names in the spreadsheet. The index number is the same as the current cell's column number in the spreadsheet. So the value set for the elementName is the corresponding column name from the first row of heading elements. Next, the code scrubs the elementName string of illegal characters likely to exist in spreadsheets. First, the replaceAll() method of String replaces all non-ASCII characters with empty strings. Then, it replaces all spaces. Both lines use regular expressions. For information on regular expressions, see Resources. Finally, the last line of Listing 10 creates the element using the proper column name. Appending attributes and elements Just like elements, you can create attributes independently, and they can remain free-floating until you append them to an element using its addAttribute() method. Create an attribute, and then populate it with cell metadata using a getter method such as getDataFormatString() from the Apache POI's HSSFCell object, as in Listing 11. Listing 11. Add Attributes (ExcelXML.java) // Create an attribute to hold the cell's format. // May be repeated for any other formatting item of interest. String attributeValue = oneCell.getCellStyle().getDataFormatString(); Attribute dataFormatAttribute = new Attribute("dataFormat", attributeValue); // Add the attribute to the cell element cellElement.addAttribute(dataFormatAttribute); Now, the element exists and has an attribute. To get data for the element, remember to test the data type of each HSSFCell, so you know which getter method to use. Because you're testing for the data type anyway, you can also create an attribute that stores the cell's data type information. Adding data to the element and appending the element as a child of the row is straightforward when working with string values, as in Listing 12. Listing 12. Add Attributes, append the cell text to the element, and append the element into the row (ExcelXML.java) switch (oneCell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: // If the cell value is string, create an attribute // for the cellElement to state the data type is a string Attribute strTypeAttribute = new Attribute("dataType", "String"); cellElement.addAttribute(strTypeAttribute); // Append the cell text into the element cellElement.appendChild(oneCell.getStringCellValue()); // Append the cell element into the row rowElement.appendChild(cellElement); break; Repeat the case section for each data type. But numeric data can be tricky. Part 1 of this article series pointed out that extracted Excel data is not the same as spreadsheet data (see the link to Part 1 in Resources). It is raw data. Certain numbers, like dates, look awfully funny as raw data and would not be the correct values if stored without formatting. You'll want to properly format numeric data before it goes into an element. You can use the Apache POI class HSSFDataFormatter and its method formatCellValue() to accomplish this. See Listing 13. Listing 13. Add Attributes, format numeric data, and append the cell element (ExcelXML.java) case HSSFCell.CELL_TYPE_NUMERIC: // If the cell value is a number, create an attribute // for the cellElement to state the data type is numeric Attribute cellAttribute = new Attribute("dataType", "Numeric"); // Add the attribute to the cell cellElement.addAttribute(cellAttribute); // Apply the formatting from the cells to the raw data // to get the right format in the XML. First, create an // HSSFDataFormatter object. HSSFDataFormatter dataFormatter = new HSSFDataFormatter(); // Then use the HSSFDataFormatter to return a formatted string // from the cell rather than a raw numeric value: String cellFormatted = dataFormatter.formatCellValue(oneCell); //Append the formatted data into the element cellElement.appendChild(cellFormatted); // Append the cell element into the row rowElement.appendChild(cellElement); break; Repeat the case section for each possible cell type. Check out the full example in ExcelXML.java. After storing the cell data, close the inner loop. Before closing the middle loop, which represents rows, test whether the row element is empty. If it's not, append it to the root element. Then, close the middle loop, as in Listing 14. Listing 14. Append the row element into the root element (ExcelXML.java) // End inner loop } // Append the row element into the root // if the row isn't empty. if (rowElement.getChildCount() > 0) { reportRoot.appendChild(rowElement); } // End middle loop } Now your Excel file is a complete XML document. Inside the XML When using XML to perform calculations, such as figuring out 1% of salaries, you must convert between strings and numbers. Listing 15 provides an example. Listing 15. Calculate 1% of the salary and store it in a donation element (ExcelXML.java) // To get employees' salaries, iterate through row elements and get a collection of rows Elements rowElements = reportRoot.getChildElements("row"); // For each row element for (int i = 0; i < rowElements.size(); i++) { // Get the salary element, // Calculate 1% of it and store it in a donation element. // Unless it's the first row (0), which needs a header element. if (i==0) { Element donationElement = new Element("header"); donationElement.appendChild("Donation"); Attribute dataType = new Attribute("dataType","String"); donationElement.addAttribute(dataType); Attribute dataFormat = new Attribute("dataFormat","General"); donationElement.addAttribute(dataFormat); // Append the donation element to the row element. rowElements.get(i).appendChild(donationElement); } // If the row is not the first row, put the donation in the element. else { Element donationElement = new Element("Donation"); Attribute dataType = new Attribute("dataType","Numeric"); donationElement.addAttribute(dataType); // The dataFormat of the donation should be the same // number format as salary, which looking at the XML file tells // us is "#,##0". Attribute dataFormat = new Attribute("dataFormat","#,##0"); donationElement.addAttribute(dataFormat); // Get the salary element and its value Element salaryElement = rowElements.get(i).getFirstChildElement("Salary"); String salaryString = salaryElement.getValue(); // Calculate 1% of the salary. Salary is a string // with commas, so it // must be converted for the calculation. // Get a java.text.NumberFormat object for converting string to a double NumberFormat numberFormat = NumberFormat.getInstance(); // Use numberFormat.parse() to convert string to double. // Throws ParseException Number salaryNumber = numberFormat.parse(salaryString); // Use Number.doubleValue() method on salaryNumber to // return a double to use in the calculation. // Perform the calculation to figure out 1%. double donationAmount = salaryNumber.doubleValue()*.01; // Append the value of the donation into the donationElement. // donationAmount is a double and must be converted to a string. donationElement.appendChild(Double.toString(donationAmount)); // Append the donation element to the row element rowElements.get(i).appendChild(donationElement); //End else } // End for loop } Now you have stored an extra Donation element for each row. You have finished building your XML Document object. XOM makes it easy to write your Document object to an XML file. Use nu.xom.Serailizer.write(), as in Listing 16. Listing 16. Writing XML to Excel (ExcelXML.java) // Print out the XML version of the spreadsheet to see it in the console System.out.println(XMLReport.toXML()); // To save the XML into a file for GEE WHIS, start with a FileOutputStream // to represent the file to write, C:\Planet Power\GEE_WHIS.xml. FileOutputStream hamsterFile = new FileOutputStream("C:\\Planet Power\\GEE_WHIS.xml"); // Create a serializer to handle writing the XML Serializer saveTheHamsters = new Serializer(hamsterFile); // Set child element indent level to 5 spaces to make it pretty saveTheHamsters.setIndent(5); // Write the XML to the file C:\Planet Power\GEE_WHIS.xml saveTheHamsters.write(XMLReport); The hamsters will love their new donation report. XML is their native language. Writing back to Excel To write the XML to an Excel spreadsheet, iterate through the XML and set cell values and formatting. Listing 17 sets up and starts looping through rows. Listing 17. Set up to write XML to Excel (ExcelXML.java) // Create a new Excel workbook and iterate through the XML // to fill the cells. // Create an Excel workbook object HSSFWorkbook donationWorkbook = new HSSFWorkbook(); // Next, create a sheet for the workbook. HSSFSheet donationSheet = donationWorkbook.createSheet(); // Iterate through the row elements and then cell elements // Outer loop: There was already an elements collection of all row elements // created earlier. It's called rowElements. // For each row element in rowElements: for (int j = 0; j < rowElements.size(); j++) { // Create a row in the workbook for each row element (j) HSSFRow createdRow = donationSheet.createRow(j); // Get the cell elements from that row element and add them to the workbook. Elements cellElements = rowElements.get(j).getChildElements(); Like looping through rows, looping through cell creation is straightforward. The harder part is formatting the cells. An HSSFCellStyle object represents style options for a cell, like font, border, and numeric formatting (including date and time formats). However, styles are per workbook, not per cell. The HSSFCellStyle object represents a named style existing in the workbook that can be applied to a cell. These styles are groupings of style options, like named styles in Microsoft Office Word. Similarly, an HSSFDataFormat is created per workbook but represents only numeric formatting, like date and time formats. To style a cell, create a new HSSFCellStyle for the workbook, or use an existing HSSFCellStyle. Then, apply it to the cell using HSSFCell.setCellStyle(). To set a numeric format for a cell, set the numeric format of the HSSFCellStyle, not the cell. Then, apply the HSSFCellStyle to the cell. The HSSFDataFormat objects are indexed by number in the workbook. To tell an HSSFCellStyle which HSSFDataFormat to use, you need the index number of the HSSFDataFormat. This is a numeric short, not an HSSFDataFormat object. Fortunately, the HSSFDataFormat object has a method called getFormat(). When passed a string representing a desired format, it returns the index number of the HSSFDataFormat that matches the string. The index is returned as a numeric short. If there is no match, it creates a new HSSFDataFormat and returns its index. You can use that index to apply the formatting to the cell style and apply the cell style to the cell, as in Listing 18. Listing 18. Loop through cell elements and set up proper numeric formatting before inserting data // Middle loop: Loop through the cell elements. for (int k = 0; k < cellElements.size(); k++) { // Create cells and cell styles. Use the row's // createCell (int column) method. // The column index is the same as the cell element index, which is k. HSSFCell createdCell = createdRow.createCell(k); // To set the cell data format, retrieve it from the attribute // where it was stored: the dataFormat attribute. Store it in a string. String dataFormatString = cellElements.get(k).getAttributeValue("dataFormat"); // Create an HSSFCellStyle using the createCellStyle() method of the workbook. HSSFCellStyle currentCellStyle = donationWorkbook.createCellStyle(); // Create an HSSFDataFormat object from the workbook's method HSSFDataFormat currentDataFormat = donationWorkbook.createDataFormat(); // Get the index of the HSSFDataFormat to use. The index of the numeric format // matching the dataFormatString is returned by getFormat(dataFormatString). short dataFormatIndex = currentDataFormat.getFormat(dataFormatString); // Next, use the retrieved index to set the HSSFCellStyle object's DataFormat. currentCellStyle.setDataFormat(dataFormatIndex); // Then apply the HSSFCellStyle to the created cell. createdCell.setCellStyle(currentCellStyle); After setting the cell's style, use setCellValue() to put most data types in the cell. However, numeric data needs special handling. To store numbers as numbers rather than text, convert them to doubles first. Do not convert dates to doubles, or they will be incorrect. Test the data format of numeric data to determine whether it's a date (see Listing 19). Listing 19. Insert cell data, converting to doubles for certain numeric data // Set cell value and types depending on the dataType attribute if (cellElements.get(k).getAttributeValue("dataType")=="String") { createdCell.setCellType(HSSFCell.CELL_TYPE_STRING); createdCell.setCellValue(cellElements.get(k).getValue()); } if (cellElements.get(k).getAttributeValue("dataType")=="Numeric") { createdCell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); // In this spreadsheet, number styles are times, dates, // or salaries. To store as a number and not as text, // salaries should be converted to doubles first. // Dates and times should not be converted to doubles first, // or you'll be inputting the wrong date or time value. // Dates and times can be entered as Java Date objects. if (cellElements.get(k).getAttributeValue("dataFormat").contains("#")) { // If formatting contains a pound sign, it's not a date. // Use a Java NumberFormat to format the numeric type cell as a double, // because like before, the element has commas in it. NumberFormat numberFormat = NumberFormat.getInstance(); Number cellValueNumber = numberFormat.parse(cellElements.get(k).getValue()); createdCell.setCellValue(cellValueNumber.doubleValue()); // Add a hyperlink to the fictional GEE WHIS Web site just // to demonstrate that you can. HSSFHyperlink hyperlink = new HSSFHyperlink(HSSFHyperlink.LINK_URL); hyperlink.setAddress(""); createdCell.setHyperlink(hyperlink); } else { // if it's a date, don't convert to double createdCell.setCellValue(cellElements.get(k).getValue()); } } // Handle formula and error type cells. See ExcelXML.java for the full example. //End middle (cell) for loop } // End outer (row) for loop } Formatting is also necessary for Excel functions that create dates, such as TODAY() and NOW(). See Listing 20. Listing 20. Use Excel functions with proper formatting // Demonstrate functions: // Add the TODAY() and NOW() functions at bottom of the Excel report // to say when the workbook was opened. // Find the last row and increment by two to skip a row int lastRowIndex = donationSheet.getLastRowNum()+2; // Create a row and three cells to hold the information. HSSFRow lastRow = donationSheet.createRow(lastRowIndex); HSSFCell notationCell = lastRow.createCell(0); HSSFCell reportDateCell = lastRow.createCell(1); HSSFCell reportTimeCell = lastRow.createCell(2); // Set a regular string value in one cell notationCell.setCellValue("Time:"); // Setting formula values uses setCellFormula() reportDateCell.setCellFormula("TODAY()"); reportTimeCell.setCellFormula("NOW()"); // Create HSSFCellStyle objects for the date and time cells. // Use the createCellStyle() method of the workbook. HSSFCellStyle dateCellStyle = donationWorkbook.createCellStyle(); HSSFCellStyle timeCellStyle = donationWorkbook.createCellStyle(); // Get a HSSFDataFormat object to set the time and date formats for the cell styles HSSFDataFormat dataFormat = donationWorkbook.createDataFormat(); // Set the cell styles to the right format by using the index numbers of // the desired formats retrieved from the getFormat() function of the HSSFDataFormat. dateCellStyle.setDataFormat(dataFormat.getFormat("m/dd/yy")); timeCellStyle.setDataFormat(dataFormat.getFormat("h:mm AM/PM")); // Set the date and time cells to the appropriate HSSFCellStyles. reportDateCell.setCellStyle(dateCellStyle); reportTimeCell.setCellStyle(timeCellStyle); Finally, after finishing the desired workbook object, write it to a file using the workbook's write() method (Listing 21). Listing 21. Write the Excel workbook to a file // Write out the workbook to a file. First, // you need some sort of OutputStream to represent the file. String filePathString = "C:\\Planet Power\\Employee_Donations.xls"; FileOutputStream donationStream = new FileOutputStream(filePathString); donationWorkbook.write(donationStream); You have now written an Excel spreadsheet calculating donations to GEE WHIS. Conclusion The reports are done. Along with reading Excel and creating XML, Java programmers can now write XML back to Excel files. After understanding the basics of converting between the two formats, you might feel yourself globally warming to the whole idea of reporting. The Big Boss is happy, and you've done your part toward helping Planet Power's environmental superheroes save Genetically Engineered Enormous Wild Hamsters. Everyone's happy. Reporting really can be good for the environment. Download Resources Learn - Read, recycle, and reuse: Reporting made easy with Excel, XML, and Java technologies, Part 1: Read Excel files and write them to new files using Java and XML (Shaene M. Siders, developerWorks, February 2010): Every company faces the challenge of extracting business data. Learn to extract data from Excel and convert it between Excel and XML using Java technology in Part 1 of this series by the author. - JavaDoc documentation for Apache POI: Browse the Apache POI documentation. - XML and Java technologies: Data binding, Part 2: Performance (Dennis Sosnoski, developerWorks, January 2003): Take XML data binding frameworks out for a test drive. - Regular expressions: Learn more about regular expressions using regular expressions in Java and the ASCII POSIX bracket expression used in this article. - The Busy Developers' Guide to HSSF and XSSF Features: Jump start your POI skills with this guide, available on Apache's site. - Get started with XPath (Bertrand Portier, developerWorks, May 2004): Explore XPath and learn about its syntax and semantics, XPath location paths, XPath expressions, XPath functions, and how XPath relates to XSLT in this introductory XPath tutorial. - XPath: Explore XPath with W3Schools. -'s tweets. - developerWorks podcasts: Listen to interesting interviews and discussions for software developers. Get products and technologies - Eclipse Classic: Download Eclipse. This article uses version 3.5.1. - Apache POI: Learn more about and download version 3.6 of the Apache POI, which is the latest stable release. - Complete zip for XOM: Learn more about and download Elliotte Rusty Harold's XML API. - Examine an elegant code snippet: Detect (and remove) Excel rows that are blank (but not null). -.
http://www.ibm.com/developerworks/library/x-jxmlexl2/index.html
CC-MAIN-2014-42
refinedweb
5,177
50.63
JDB - In Eclipse This chapter explains how to use JDB in Eclipse. Before proceeding further, you need to install Eclipse Indigo. Follow the steps given below to install Eclipse Indigo on your system. Step 1: Download and Install Eclipse You can download Eclipse from the following link: Step 2: Create a New Project and a New Class - Create a new Java project by following the options File-> New -> Java project. - Name it as “sampledebug”. - Create a new class by right clicking on the samplebebug project. - Select options ->new -> class - Name it as “Add.java” Add.java public class Add { public int addition( int x, int y) { int z = x + y; return z; } public static void main( String ar[ ] ) { int a = 5, b = 6; Add ob = new Add(); int c = ob.addition(a,b); System.out.println("Add: " + c); } } Step 3: Open the Debug Perspective Follow the instructions given below to open the debug perspective. On the Eclipse IDE, go to Window -> Open perspective -> Debug. Now you get the debug perspective for the program Add.java. You get to see the following window. Sections in Debug Perspective The sections in the Debug perspective are as follows: Coding Section Java code is displayed in this section. It is the code you want to debug, that is, Add.java. Here we can add a breakpoint on a line by double clicking in front of the line. You find the blue bubble with an arrow symbol to point out the breakpoint of that line. See the following screenshot; you can find the selected area with a red circle pointed as “1”. - Double click here. You can set the breakpoint for this line. Breakpoint Section This section defines the list of breakpoints that are set to the program code. Here we can add, delete, find, and manage the breakpoints. The following screenshot shows the breakpoint section. Observe the following options in the given screenshot: Using the check box in the left, we can select or deselect a breakpoint. Here, we use one breakpoint, i.e., Add class-main() method. The single cross icon “X” is used to delete the selected breakpoint. The double cross icon “XX” is used to delete all the breakpoints in your code. The arrow pointer is used to point to the code where the selected breakpoint is applied. The remaining functionalities in the breakpoint section are as follows: Hitcount : It shows how many times the control hits this breakpoint. It is used for recursive logic. Suspend thread : We can suspend the current thread by selecting it. Suspend VM : We can suspend the VM by selecting it. Debug Section This section is used for the process of debugging. It contains options that are used in debugging. Start debugging : Follow the instructions given below to start debugging. Right click on the code -> click Debug as -> click 1 Java application. The process of debugging starts as shown in the following screenshot. It contains some selected options, highlighted using numeric digits. We apply a breakpoint on the Add class main() method. When we start debugging, the controller gets stuck at the first line of the main() method. It is used to Resume the debugging process and skip the current breakpoint. It works similar to the cont command in the JDB command line. It is used to stop the debugging process. It works similar to the step in process in the JDB command line. It is used for moving the control to the next line, i.e., point “1” moves to the next line. It works similar to the step over process in the JDB command line. It is used to see on which line the breakpoint is applied. Follow the given steps and sections to debug your code in eclipse IDE. By default, every IDE contains this debugging process.
https://www.tutorialspoint.com/jdb/jdb_in_eclipse.htm
CC-MAIN-2017-34
refinedweb
634
75.81
[libxml]: Can't find nodes using XPath, namespaces mess Discussion in 'Ruby' started by Stanislaw Wozni Problems with libxml, XML::LibXML and PerlIan Gregory, Jul 23, 2003, in forum: XML - Replies: - 1 - Views: - 602 - cp - Jul 25, 2003 C++ libraries: Xerces, libxml/libxml++ or perhaps Arabica?Olav, Jun 21, 2004, in forum: XML - Replies: - 3 - Views: - 4,619 Xpath and axis navigation using libxmlAlfie Noakes, Nov 11, 2008, in forum: XML - Replies: - 4 - Views: - 847 - Alfie Noakes - Nov 11, 2008 Dealing with xpath using libxmlVaucher Bastien, Feb 21, 2007, in forum: Ruby - Replies: - 0 - Views: - 149 - Vaucher Bastien - Feb 21, 2007 XML::LibXML, newlines in nodes, and entities...Jay McGavren, Jul 7, 2005, in forum: Perl Misc - Replies: - 4 - Views: - 443 - A. Sinan Unur - Jul 7, 2005
http://www.thecodingforums.com/threads/libxml-cant-find-nodes-using-xpath-namespaces-mess.858848/
CC-MAIN-2015-40
refinedweb
127
57.95
Hi I have a problem that drives me crazy, same wiring and code working 100% on Arduino Mega but on Teensy 3.6 one button affects the other once. I used a 10 K resistor between GND and data pins and 3.3v goes to the other leg of the button, please see the diagram below. Even when I try to use Internal PULLUP / PULLDOWN resistors it still shows the wrong values for the button pressed. For Example Pushing Button #0 Gives me the following result: Pushing Button #4 Gives me the following result: Again, same schematics and code works fine on Arduino Mega 2560 (the only difference I can think of it's 5v if that relevant) Your help is much appreciated ! Hardware: Teensy 3.6 (3.3volt) Software: Arduino IDE v1.8.9 Error Messages: See Above Screenshot of Serial Monitor Wiring: See Above Code: /** * This example demonstrates how to read digital signals * It assumes there are push buttons with pullup resistors * connected to the 16 channels of the 74HC4067 mux/demux (in my case 8 buttons) * * For more about the interface of the library go to * */ const int ledPin = 13; #include "MUX74HC4067.h" // Creates a MUX74HC4067 instance // 1st argument is the Arduino PIN to which the EN pin connects // 2nd-5th arguments are the Arduino PINs to which the S0-S3 pins connect MUX74HC4067 mux(5, 0, 1, 2, 3); void setup() { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); // set the LED on Serial.begin(9600); // Initializes serial port // Configures how the SIG pin will be interfaced // e.g. The SIG pin connects to PIN 3 on the Arduino, // and PIN 3 is a digital input mux.signalPin(4, INPUT_PULLUP, DIGITAL); } // Reads the 16 channels and reports on the serial monitor // if the corresponding push button is pressed void loop() { byte data; for (byte i = 0; i < 8; ++i) { // Reads from channel i and returns HIGH or LOW data = mux.read(i); Serial.print("Push button at channel "); Serial.print(i); Serial.print(" is "); if ( data == LOW ) Serial.println("not pressed"); else if ( data == HIGH) Serial.println("pressed"); } Serial.println(); }
https://forum.pjrc.com/threads/57248-Teensy-3-6-Problem-with-Mux-(CD74HC4067)-and-Reading-Buttons?s=6891d47d445b4033ad90c1854154c38b&p=212659
CC-MAIN-2019-35
refinedweb
352
59.53
User Name: Published: 23 Feb. Improved browser capabilities, enabled by faster computers, have not only made complex and rich web applications possible but have also changed the way we use computers. Techniques like AJAX, and powerful JavaScript libraries that abstract away painful cross-browser issues, have resulted in client-side (in the browser) programming becoming one of the most important fields in modern software development. Despite this, web applications remain restricted by the user-interface capabilities of JavaScript and the performance of JavaScript when running large programs. Ways around these difficulties include web-programming frameworks such as Flash, AIR, Flex, and Silverlight, which have their own programming and user-interface models. In case you haven't heard of it, Silverlight is a cross-platform browser plug-in created by Microsoft. It's superficially similar to Flash but with the magic extra ingredient that we can program it with Python. Because Silverlight is based on the .NET framework, it's a major new platform that IronPython runs on. Silverlight has a user-interface model based on Windows Presentation Foundation, and we can use it to do some exciting things, such as media streaming, creating games, and building rich internet applications. In this chapter, we look at some of what Silverlight can do and how to do it from IronPython. We'll be exploring, creating, and deploying dynamic Silverlight applications and programming with the Silverlight APIs - some of which are familiar and some of which are new. Silverlight is a cross-platform, cross-browser plug-in for embedding into web pages. Silverlight has at its heart a cut-down and security-sandboxed version of the .NET framework called the CoreCLR. That means it contains many of the APIs we're already familiar with, including the WPF user interface. More important, the CoreCLR is capable of hosting the Dynamic Language Runtime, so Silverlight can be programmed with DLR languages like IronPython and IronRuby. In this chapter we explore some of the features that Silverlight provides. Figure 1 shows a Tetrislite game written for Silverlight 2, from the Silverlight community samples. By cross-platform, Microsoft means Windows and Mac OS X. By cross-browser, the Microsoft folks mean the Safari, Firefox, and Internet Explorer web browsers. This isn't the end of the story, though; Silverlight support is in the works for the Opera browser and for the Windows Mobile and Nokia S60 platforms. The Silverlight team members aren't working directly to support Linux, but they are working with the Mono team on an officially blessed Mono port of Silverlight called Moonlight. This currently works on Firefox on Linux, but the eventual goal is to get Moonlight working on multiple browsers (like Konqueror) and on every platform that Mono runs on. The stable version of Moonlight is compatible with Silverlight 2, and there's an early preview of Moonlight 3, which unsurprisingly targets compatibility with Silverlight 3. Meanwhile, Microsoft has also released their own developer preview, of Silverlight 4, with lots of exciting new features. Microsoft has assisted the Moonlight effort by providing access to the Silverlight test suite and the proprietary video codecs that Silverlight uses. Moonlight uses the Mono stack, but a lot of the work involved implementing the security model that provides the Silverlight browser sandboxing. Another major part was the user-interface model; this is particularly interesting, because previously the Mono team has said that they have no interest in implementing WPF. Perhaps this will change now that they have had to implement a subset of WPF for Moonlight. So what benefits for web application programming does Silverlight have over traditional JavaScript and AJAX? The first advantage is that it can be programmed in Python, and frankly that's enough for us. The Python community has long wanted to be able to script the browser with Python rather than JavaScript, and it's at least slightly ironic that it's Microsoft that has made this possible. Perhaps a more compelling reason is that Silverlight is fast. By some benchmarks (of course, all benchmarks are misleading, in the same way that all generalizations are wrong) IronPython code running in Silverlight runs two orders of magnitude faster than JavaScript! As well as having its own user-interface model, Silverlight gives you full access to the browser DOM (Document Object Model), so that everything you can do from JavaScript you can also do from inside Silverlight. The features of Silverlight include Deep Zoom is a fantastic image-zooming technology based on Seadragon: see. Adaptive streaming allows the browser to adjust the quality of streamed audio and video according to the available bandwidth and CPU power. The last point is particularly interesting. Although most example Silverlight applications take over the whole web page, this isn't the only way to use it. Like Flash, the Silverlight plug-in can occupy as little of a web page as you want (yes, you can use Silverlight to create those annoying adverts that everybody hates), and you can embed several plug-ins (which can communicate with each other) in the same page. In fact, the Silverlight plug-in needn't be visible at all. By interacting with JavaScript and the browser DOM, you can use all your favorite AJAX tricks from Silverlight, including using existing JavaScript libraries for the user interface, with the business logic implemented in Python. Creating Silverlight applications with dynamic languages is simple. Let's dive into the development process. Silverlight applications are packaged as xap files (compressed zip files), containing the assemblies and resources used by your application. An IronPython application is a normalapplication as far as Silverlight is concerned; a DLR assembly provides the entry point and is responsible for running the Python code. The standard IronPython distribution includes a special version of the DLR assemblies and IronPython compiled for Silverlight, along with the development tool Chiron.exe. Chiron packages IronPython Silverlight applications as the browser requests them. This means that you can have a truly dynamic experience developing Silverlight applications with IronPython. Edit the Python file with a text editor or IDE and refresh the browser, and you immediately see the changes in front of you. Chiron can create xap files for dynamic applications and will also work as a server, allowing you to use your applications from the filesystem while you're developing them. Chiron runs under Mono, so you can use it on the Mac. Silverlight lives on the web, so to use it we need to embed it into a web page. Embedding a Silverlight control into a web page is straightforward. You use an HTML <object> tag, with parameters that initialize the control and HTML that displays the Install Microsoft Silverlight link and image (shown in figure 2) if Silverlight isn't installed. Listing 1 is the typical HTML for embedding the Silverlight control into a web page. The onError parameter is a JavaScript function that'll be called if an error occurs inside Silverlight (including in your code). The value in initParams is a bit special. debug=true enables better exception messages. As well as getting the error message, you'll get a stack trace and a snapshot of the code that caused the exception. It works in conjunction with an errorLocation div in your HTML (plus a bit of CSS for styling), which is where the tracebacks from your application are displayed. You can see the necessary HTML/CSS in the sources of the examples for this chapter. onError initParams debug=true You can extend the error tracebacks to include the CLR errors by adding exceptionDetail to initParams: <param name="initParams" value="debug=true,reportErrors=errorDiv, exceptionDetail=true" /> <param name="initParams" value="debug=true,reportErrors=errorDiv, exceptionDetail=true" /> This is usually more information than you want in tracebacks, but it can be invaluable in tracking down the underlying reason for some errors. The xap file is a zip file with a different extension; you can construct xap files manually or Chiron can autogenerate them for you. The command-line magic to make Chiron create a xap file from a directory is bin\Chiron /d:dir_name /z:app_name.xap bin\Chiron /d:dir_name /z:app_name.xap If you're running this on the Mac, then the command line will look something like this: mono bin/Chiron.exe /d:dir_name /z:app_name.xap mono bin/Chiron.exe /d:dir_name /z:app_name.xap More important, xap files as they're requested. The command to launch Chiron as a web server is Chiron /w By default, this serves on localhost port 2060. The most important part of the xap file is the entry point, which in dynamic applications will be a file called app.py, app.rb, or app.js, depending on which dynamic language you're programming in. Our first app.py will be the simplest-possible IronPython Silverlight application. Because we're using the WPF UI system, we work with classes from the System.Windows namespaces. Listing 2 creates a Canvas, with an embedded TextBlock displaying a The important line, which is different from our previous work with WPF, is the last one, where we set the container canvas as the RootVisual on the current application. This makes our canvas the root (top-level) object in the object tree of the displayed user interface. You're not stuck with a single Python file for your application, though. Imports work normally for Python modules and packages contained in your xap file (or your application directory when developing with Chiron). You can use open or file to access other resources from inside the xap file, but they're sandboxed, and you can't use them to get at anything on the client computer. RootVisual In Silverlight projects you can break your applications into multiple Python files in the same way you can with normal Python applications. Import statements from Python files kept in the xap file work normally, including from Python packages. You can even keep Python files in a subdirectory and add it to sys.path to be able to import from them. Because we're using WPF, many applications load XAML for the basic layout. They do so with very similar code to listing 2, as shown in listing 3. Instead of setting the RootVisual on the application, this code loads the XAML with a call to LoadRootVisual. Listing 4 shows the app.xaml file, for a Canvas containing a TextBlock, loaded from the xap file in listing 3. LoadRootVisual The call to LoadRootVisual returns us an object tree. Like the object trees we worked with from XAML in chapter 9, we can access elements that we marked with x:Name as attributes on the object tree. This allows us to set the text on the TextBlock through xaml.textblock.Text. Many of the techniques we learned when working with the WPF libraries for desktop applications are relevant to Silverlight, but they're far from identical. One of the major differences is that we have fewer controls to work with. Let's look at some of the APIs available for creating Silverlight applications, including the extended set of controls. LoadRootVisual xaml.textblock.Text Silverlight ships with a set of standard controls based on WPF and contained in the System.Windows.Controls namespace. Figure 3 shows examples of the standard controls. As you might expect from their WPF inheritance, the Silverlight controls are attractive and easy to use. Figure 4 shows a TextBox with a Button and a TextBlock. Using and configuring the controls from code is splendidly simple. Listing 5 shows a Button and a TextBox inside a horizontally oriented StackPanel. When the Button is clicked, or you press Enter, a message is set on the TextBlock. Along with the standard controls, a set of extended controls comes with Visual Studio Tools for Silverlight. (Silverlight Tools for Visual Studio 2008 works with Visual Studio 2008 or Visual Web Developer 2008 Express. The tools are linked to from.) This set includes additional controls such as Calendar, DataGrid, DatePicker, TabControl, and so on. In addition to the standard and extended controls, Microsoft has a Codeplex project (available with source code and tests, under the same open source license as IronPython) called Silverlight Toolkit. The toolkit is a collection of controls and utilities for Silverlight, including TreeView, DockPanel, and charting components. Visual Studio Tools for Silverlight comes with a lot more than just a new set of controls. It also includes additional assemblies for working with JSON, XML, and so on (don't use the outdated version of IronPython it includes, though!). What we're about to cover is as relevant for using these other assemblies as it is for the extended controls. The two assemblies that implement the extended controls are System.Windows.Controls.dll System.Windows.Controls.Data.dll As with using other assemblies from IronPython, in order to use them we need to add a reference to them with clr.AddReference. Table 1 lists the Silverlight controls. Border DatePicker MultiScaleImage Slider Button Grid OpenFileDialog StackPanel Calendar GridSplitter Panel TabControl Canvas HyperlinkButton PasswordBox TextBlock CheckBox Image ProgressBar TextBox ComboBox InkPresenter RadioButton ToggleButton ContentControl ListBox RepeatButton ToolTip DataGrid MediaElement ScrollViewer UserControl It will be self-evident what most of these controls are for from their names (one of the advantages of consistent naming schemes). One that may not be familiar is MultiScaleImage. This control is for displaying multiresolution images using Deep Zoom. It allows the user to zoom and pan across the image. These assemblies extend the System.Windows.Controls namespace, so the extended controls are imported from the same place as the standard controls. Of course, you can use the extended controls from XAML as well as from code. Using the extended controls from XAML requires us to tell the XAML loader where to find the classes that correspond to the XAML elements. We do this by adding extra xmlns declarations to the first tag in the XAML. Listing 6 is a part of an XAML file that uses several of the extended controls (Calendar, DatePicker, and GridSplitter). xmlns To load this XAML from IronPython, like the example in listing 3 (This XAML has a UserControl as the root element, so you'll need to modify listing 3 to create a UserControl instead of a Canvas.), we don't need to explicitly add references to the assemblies containing the controls; the XML namespace declarations do this for us. The xmlns:c declaration also declares a prefix (c) that we must use to reference controls from the System.Windows.Controls assembly. For example, the DatePicker control is referenced with c:DatePicker in the XAML. Once this XAML is loaded, the results look like figure 5. c c:DatePicker If you don't like the standard silver theme, you can use a new theme for all the controls in an application. In discussing the extended controls, we've glossed over an important point. If you look in the source code for the example applications that use the extended controls, you'll see a file that we haven't yet discussed, AppManifest.xaml. This XML file tells Silverlight not only what assemblies your application uses but also which one provides the entry point. The reason it isn't included in the earlier examples is that Chiron can autogenerate it for applications that use no assemblies beyond the standard IronPython/DLR ones. When you deploy a typical dynamic application, the xap file contains the following: Listing 7 shows the manifest file needed for a basic dynamic application. You can either copy and paste this into your applications or let Chiron create it for you. Requiring XML manifest files may seem like unnecessary overhead for dynamic applications, but they serve a very serious purpose: making Silverlight applications fit for the enterprise. It's interesting to note the EntryPoint attribute in the top-level Deployment element. This is how Silverlight knows how to execute a dynamic application, and a dynamic application is a normal C# application as far as Silverlight is concerned. Microsoft.Scripting.Silverlight.dll does the magic for us. To use additional assemblies in your applications, including the extended controls, you need to include them in the manifest. This has a serious downside, even if your application is only a single Python file a few kilobytes in size; the resulting xap file will need to contain the IronPython assemblies and be several hundred kilobytes in size. Fortunately, there's a way around this. If instead of specifying the assembly name as the Source attribute for the assemblies you specify an absolute URL, the assemblies will be fetched separately rather than being expected inside the xap file. If several of your applications share the same assemblies, then the browser can cache them, and your application can shrink back to a more manageable size. At some point a mechanism like the Global Assembly Cache will be implemented for Silverlight, but there isn't one yet. We've covered all the basics now, and you have everything you need to start writing Silverlight applications; everything else is mere detail. The best way of learning these details is to use them, so in the next section we look at a more substantial Silverlight application: a Twitter client. This will be the topic of the next part of this series..
http://dotnetslackers.com/articles/silverlight/Silverlight-IronPython-in-the-browser-part1.aspx
CC-MAIN-2014-41
refinedweb
2,884
53.21
This article is a sample chapter (Chapter 1) from ASP.NET Professional Secrets, written Bill Evjen, and published by Wiley. If you are new to .NET—Welcome! If you are a .NET Framework 1.0 veteran—Welcome to .NET version 1.1! .NET 1.0 was introduced with tremendous excitement. It was original, answered many developers’ problems, and truly leap-frogged any of the other technologies out there—especially in the realm of browser-based Internet application development—or ASP.NET. .NET 1.1 and ASP.NET 1.1 are minor releases and should not be considered substantially different versions from 1.0. The next major revision of .NET and ASP.NET will come with the release of version 2.0. This chapter introduces the .NET Framework 1.1 and also shows you what’s new in ASP.NET 1.1. Welcome to .NET Every so often, a technology company needs to step back from itself, look at what it is trying to achieve, and then determine whether it needs to try a different approach. Microsoft did this as it stood back from the COM world it had created and asked itself, “Is there a better way?” The .NET Framework is this better way. .NET is confusing to many people because the Microsoft marketing folks took hold of the name and started applying it to every product that Microsoft produced. .NET had almost nothing to do with many products that acquired the .NET moniker. This problem is slowly being corrected. More products are now coming from Microsoft without .NET in their titles. Microsoft’s short definition of .NET is Microsoft’s platform for building XML Web services. But the .NET that I am talking about (and the .NET that you should be focused on understanding) is the .NET Framework itself. Microsoft’s .NET Framework is a new computing platform built with the Internet in mind, but without sacrificing the traditional desktop application platform. The Internet has been around for a number of years now, and Microsoft has been busy developing technologies and tools that are totally focused on it. These earlier technologies, however, were built on Windows Distributed InterNet Applications Architecture (DNA), which was based on the Component Object Model (COM). Microsoft’s COM was in development many years before the Internet became the force that we know today. Consequently, the COM model has been built upon and added to in order to adapt it to the world of the Internet. The .NET Framework enabled Microsoft to build everything from the ground up with the Internet in mind. Therefore, the .NET Framework focuses heavily on Internet-enabling your applications, whether these applications are thin-client or thick-client applications. Building a new platform from the ground up also allowed Microsoft to take a close look at how developers developed. Even more importantly, Microsoft began examining how to correct the problems developers experience and how to make them more productive in this new environment. .NET is a collection of tools, technologies, and languages that all work together in a framework to provide the solutions necessary for easily building and deploying truly robust enterprise applications. These .NET applications can also communicate with one another and provide information and application logic, regardless of platforms and languages. Figure 1-1 shows an overview of the structure of the .NET Framework. Figure 1-1: The .NET Framework. You might have seen this simple diagram of the .NET Framework before, but take a closer look at it now. Consider the .NET Framework as something that sits on an operating system. Presently, the operating systems that can take the .NET Framework include Windows Server 2003, Windows XP Professional, Windows 2000, and Windows NT. Note: Support for the .NET Framework on Windows NT is limited to functioning as a client. Windows NT does not support the Framework as a server. At the bottom layer of the .NET Framework is the Common Language Runtime (CLR). The CLR is the engine that manages the execution of the code, takes care of object management, provides security, and so much more. The next layer up from the CLR is the .NET Framework Base Class Libraries (BCL). The BCL layer contains classes, value types, and interfaces that are often used in the development process. The many classes in the BCL are organized into a series of namespaces. The third layer of the .NET Framework includes the Windows Forms model (more on that shortly), along with the area that is the primary focus of this book—ASP.NET. Don’t think of ASP.NET as the latest version of Active Server Pages—the one that comes after ASP 3.0. Instead, think of it as a dramatic new shift in Web application development. Using ASP.NET, it’s now possible to build robust Web applications that are even more functional than Win32 applications of the past, a difficult feat because of the stateless nature of the Internet. ASP.NET offers a number of different solutions to overcome the traditional limitations on the types of possible applications. The ASP.NET section of the .NET Framework is also where the XML Web services model resides. As I mentioned a moment ago, ASP.NET shares the top layer of the .NET Framework with Windows Forms applications. These are the traditional .exe applications, or Win32 thick-client applications. The programming models of the ASP.NET world and the Windows Forms world are quite similar, and these two models use the same objects from the Framework to accomplish their tasks. If you become a good ASP.NET programmer, you also become a good Windows Forms programmer. Interestingly enough, because the models are so similar, you can build a class that you can use in either your ASP.NET application or in a Windows Forms application. Looking to the future The .NET Framework is focused on how people will use technology in the future. One view (held not only by Microsoft) says that all devices and applications will one day be connected to the Internet. When this day arrives, people won’t use the Internet just for the browser-based applications as they currently do, but also for telephones, televisions, microwaves, Xbox and PlayStation units, and much more (see Figure 1-2). All these devices connected by the Internet can’t possibly be built on a single platform. The world will continue to have multiple platforms and languages at its disposal for a long time to come. Consequently, we need a common language that can communicate with the various platforms, applications, and devices. XML and SOAP are the common languages now facilitating communication among platforms, applications, and devices. By using these languages, devices can communicate over the Internet in an easy and straightforward manner. Microsoft enables you to start bringing this disparate but connected vision to reality with the .NET Framework. By building XML Web services, you are expressing objects and using XML and SOAP to communicate the object’s data or the application logic that it might provide. Cross-Reference: XML Web services are considered part of the ASP.NET model and are covered in Part VI of this book. You can also use your ASP.NET applications to consume data or application logic from other Web services on the Internet, regardless of the language or platform used in the creation of these Web services. Over time, more and more connections of applications with remote objects will use the XML Web services model in the .NET Framework. Figure 1-2: One Web service for multiple clients. Microsoft’s .NET solution Because of the prospect that the universe of devices and applications will be placed on the same medium and will be able to communicate with one another using a common language, Microsoft developed the .NET Framework. Developers using this platform can build their applications to take advantage now of this vision of the future. Before the .NET Framework came along in 2002, Microsoft offered quite a number of tools and technologies for building a wide variety of applications. As a developer, you could choose the environment, language, or tool appropriate for what you were trying to accomplish. For example, if you wanted to quickly build a thick-client application, you used Visual Basic. If you wanted to build low-level applications that gave you granular access to the platform, you used C++. If you wanted to build browser-based applications, you used Active Server Pages (ASP). With the .NET Framework, Microsoft has taken the best of all these different worlds and merged them into a single environment—the .NET world, as shown in Figure 1-3. Figure 1-3: A unified model. Because of this new unified model, you need only one environment, one platform, and any .NET language to build any .NET application. It doesn’t matter if the application is a desktop application, a browser-based application, a component, or even a driver. You now have a single environment to do all this work. One of the main objectives of the Framework is to provide a simplified development model that eliminates a lot of the plumbing required to develop in the past. The .NET Framework gives developers more power over their applications. This framework uses the latest in Internet standards such as XML, SOAP, and HTTP. The applications that you build on this platform are easier to deploy and maintain. .NET-capable IDEs Instead of multiple development environments for building various types of applications, Microsoft provides a single development environment to build any type of .NET application. This development environment is Visual Studio .NET. It’s the development environment that I recommend you use with this book as you build and work with your .NET applications. Visual Studio .NET enables you to build your ASP.NET applications in a code-only manner (writing code directly) or by dragging and dropping objects onto a design surface. You can also use Visual Studio .NET to build thick-client applications or Windows Forms and to build your classes, components, and everything else you need. Another development environment offered by Microsoft is the ASP.NET Web Matrix. This free tool is available from the ASP.NET Web site at. It is a great tool to help you get a feel for building Web applications. Unlike Visual Studio .NET, however, the ASP.NET Web Matrix limits you to building only ASP.NET applications and XML Web services. You can’t build any Windows Forms applications using the Web Matrix. Cross-Reference: You learn about the Visual Studio .NET environment in Chapter 2 and the ASP.NET Web Matrix environment in Chapter 3. Note: Besides these two Microsoft IDEs, other IDEs are capable of building .NET applications. One of the more popular development environments is Macromedia’s Dreamweaver MX. This IDE enables you to build ASP.NET applications as well as many other types, such as PHP and ColdFusion applications. You can also build ASP.NET applications by using Notepad and the compilers provided with the .NET Framework. In fact, you can type much of the code from this book into Notepad to build your ASP.NET applications. The .NET languages When developing on the Microsoft platform in the past, you chose the development language based on the type of application you wanted to build. The .NET Framework has completely changed this scenario for us. The .NET Framework enables you to build any type of application or object that can be used in the .NET platform, and you can also use any of the .NET languages to build these applications. For a language to be part of the .NET Framework, a language has to follow certain rules. The biggest and most important rule for inclusion is that the language must be an object-oriented language. Microsoft provides five languages with the .NET Framework: Visual Basic .NET, C#, C++.NET, JScript .NET, and now J#. You now have a choice of which language you are going to use to build your ASP.NET applications. For instance, you are not limited to just using Visual Basic .NET to build your browser-based applications; you can also use C#, JScript .NET, or even J# to build a Web-based application. Whenever this idea is presented, people always ask: Which is the better language to use? Does one language provide better performance than another? The answer to both these questions is an emphatic NO. There isn’t one language that is better than another. They all have access to the same classes and capabilities that are provided with the .NET Framework. If there is no difference in which language you can use to build your .NET applications, it then becomes simply a matter of style when deciding which of the languages to use. In addition to the languages that are provided with the install of the .NET Framework 1.1, quite a number (more than 40) of third-party languages are capable of being used in the .NET platform to build your .NET applications. For instance, you can also build ASP.NET applications using COBAL or Perl. To use either of these applications, however, you must install the language yourself because neither is provided with the default install of the .NET Framework. This book focuses on the two most popular .NET languages: Visual Basic .NET and C#. A Closer Look at the .NET Foundation The foundation of the .NET platform is the .NET Framework, which I introduced in the preceding section. The .NET Framework sits on top of the operating system and is made up of two parts, the Common Language Runtime and the Base Class Libraries. Each of these parts plays an important role in the development of .NET applications and services. The Common Language Runtime Many different languages and platforms provide a runtime, and the .NET Framework is no exception. Its runtime, however, is quite different from most. The Common Language Runtime (CLR) in the .NET Framework manages the execution of the code and provides access to a variety of services that make the development process easier. The CLR has been developed to be far superior to previous runtimes, such as the VB runtime, by providing the following functionality: - Cross-language integration - Code access security - Object lifetime management - Debugging and profiling support Code that is compiled and targeted to the CLR is known as managed code. Managed code has the metadata needed for the CLR to provide the services of multilanguage support, code security, object lifetime management, and memory management. Note: Metadata is basically data about data or a description of the contents of a .NET component. This metadata is stored within the assembly manifest. In the past, it was difficult for components written in competing languages to interact with one another. The .NET Framework uses metadata so that .NET components are self-describing, making them easy to interoperate with other components. Compilation to managed code When creating a .NET application, use one of the .NET languages. After the code is written, you (or Visual Studio .NET) uses the language’s compiler to compile the code down to Microsoft Intermediate Language (IL). IL is a CPU-independent set of instructions that can easily be converted to native code. The metadata (the self-describing information about the object created) is also contained within the IL. This is illustrated in Figure 1-4. You can see from the diagram of the compilation process that it really doesn’t matter which language you are using with the .NET platform. In the end, each .NET language compiles down to the same type of object. The IL is CPU-independent, which means that the object created by the compiler is not dependent upon the computer that created it. It, therefore, can be moved at this stage from the computer that created it to any other computer that has the .NET Framework on it. And because this IL object is self-describing, it doesn’t need to be registered in the Windows registry. You only have to copy it to the hard drive of the computer—that’s it. It makes XCopy possible with .NET applications. To run the application from here, it actually needs to be compiled even further—down to native code. This is handled by the .NET Framework’s JIT compiler. The IL contains everything that is needed to do this, such as the instructions to load, call methods, and a number of other operations. Figure 1-4: Managed-code execution process.
https://www.codeguru.com/csharp/introducing-net-and-asp-net/
CC-MAIN-2021-49
refinedweb
2,744
58.89
How would people feel about providing links to MathWorld and Wikipedia on the docstrings too? i.e. for "norm" add links to IMHO, it would also be worth adding the nearest equivalent commands in Macsyma, Mathematica, Maple and MATLAB, though I doubt that will be possible for many commands. sin() would have Sin[] - nearest equivalent command for Mathematica sin() - nearest equivalent command for MATLAB I don't know about the command for 'sine' in other packages, but no doubt someone is familiar with them. One could also add for packages where there is no similar command for the commercial packages. foobar() - As of version 7.0, Mathematica has no similar functionality. I think at one point, providing a list of equivalent commands in these packages should be done, to aid people porting code from these packages to Sage. A start would be to document the nearest equivalent commands in the actual docstrings. At least if a conversion list was ever made, the docstrings would provide some help to those compiling such a list. Dave On Tue, Sep 21, 2010 at 7:11 PM, Dr. David Kirkby <david....@onetel.net> wrote: > I think at one point, providing a list of equivalent commands in these > packages should be done, to aid people porting code from these packages to > Sage. A start would be to document the nearest equivalent commands in the > actual docstrings. I don't have a problem with this. In fact, I heartily support your suggestion. > At least if a conversion list was ever made, the docstrings would provide > some help to those compiling such a list. Nathann and I started a few months ago to make such a list for graph theory: Regards Minh Van Nguyen: Let's say one always had equivalent entries of the format: sage_command Nearest Mathematica equivalent: MathematicaCommand[]. Anything else in the doc files was ignored, since we only bother searching for the text "Nearest Mathematica equivalent:" drkirkby@hawk:~$ cat test.txt factor() Nearest Mathematica equivalent: Factor[] FactorInteger[] tan() Nearest Mathematica equivalent: Tan[] Some other stuff, unrelated to Mathematica cos() Nearest Mathematica equivalent: Cos[] Some other stuff, about birds and bees sin() Nearest Mathematica equivalent: Sin[] drkirkby@hawk:~$ grep awk "Nearest Mathematica equivalent:" | awk '{print $5, $1}' | sort | grep -v "^ " Cos[] cos() Factor[] factor() Sin[] sin() Tan[] tan() We would then search for lines where's there is a 6th entry too, as there might be two different commands needed in Mathematica, as there is for factor(). drkirkby@hawk:~$ grep "Nearest Mathematica equivalent" test.txt | awk '{print $6, $1}' | sort | grep -v "^ " FactorInteger[] factor() Combining the two, we now have a complete list of Mathematica vs Sage commands, sorted by the Mathematica name. (We don't need to sort each time - only at the end) drkirkby@hawk:~$ grep "Nearest Mathematica equivalent" test.txt | awk '{print $5, $1}' | grep -v "^ " > tmpfile drkirkby@hawk:~$ grep "Nearest Mathematica equivalent" test.txt | awk '{print $6, $1}' | grep -v "^ " >> tmpfile Now sort them. drkirkby@hawk:~$ sort tmpfile Cos[] cos() Factor[] factor() FactorInteger[] factor() Sin[] sin() Tan[] tan() I expect: 1) Someone will tell me there's a way to do it in Python. 2) There's better ways of doing it with shell scripts (one would want to recursive search files for example), but that's trivial (-R option on GNU grep, or with 'find' command). 3) There might be a better way of doing it in the dostrings. But if all else fails, then grabbing the data via a shell script and sorting it in order would be trivial as long as a consistent format was used. i.e. was always use ""Nearest Mathematica equivalent" or something like that, and people do not mis-spell it, swap the case of characters, or anything else that gets away from a rigid agreed structure. PS, it would also be trial to create an HTML web page from such a shell script! Dave >: I like very long bash lines, with as many pipes as I can. I'm in :-D > Let's say one always had equivalent entries of the format: > ... > We would then search for lines where's there is a 6th entry too, as there > might be two different commands needed in Mathematica, as there is for > factor(). I totally agree on the idea. Now some details : if we finally put these informations inside of the docstring then extract it from the python files, it means these informations will be available in the method's docstrings. So for example, it may be nice not to have to repeat the command's name in those "equivalent" lines.. def method_name(): r""" ... EQUIVALENTS: method_name Mathematica MethodName[] method_name Matlab MethodName[] method_name Scilab MethodName[] """ ... This can be extracted from the line containing "def" just before the r""" or the """. Then, because I am thinking of Graph Theory, it would be hard sometimes to give, as you say, just one equivalent. Sometimes, many are available, sometimes our Sage methods replace several Mathematica methods at once because of our optional arguments. Sometimes, there is no equivalent Mathematica method, but one doing "almost" the same job : I remember having seen that Mathematica was only able to approximate problems for which we had exact solvers, in which case we have to explain in the "Equivalent" line the difference between the two. All in all, I would quite love to be able to write a small paragraph corresponding to an "Equivalent" line, to deal with all of it. What would you think of such a paragraph ? EQUIVALENTS: Mathematica : Small paragraph if necessary (and most probably on multiple lines as we try to keep them short in the code), talking about the differences between the current method and Method 1/2. (This paragraph does not contain any list, as we want to be able to parse the following commands easily ?) * Method 1 * Method 2 Scilab : Same kind of things... * Method 1 * Method 2 > Combining the two, we now have a complete list of Mathematica vs Sage > commands, sorted by the Mathematica name. (We don't need to sort each time - > only at the end) Hmmm... Actually, we would only have a Mathematica Vs Sage comparison when we have a Sage method equivalent to the Mathematica one, or close enough. The methods that Mathematica can handle while we can not do not appear. Or perhaps those should just become TRAC tickets, and be written :-D Nathann Maybe "nearest" is not appropriate. Perhaps "similar" or something like that, so it avoids any arguments about what is similar and what is not. Nobody can expect the commands to be identical - except for trivial ones like Sin[], Cos[]. In the case of factor() there are two very obvious Mathematica commands that provide broadly similar functionality. At the end of the day, this is not a suggestion to make a Sage-> Mathematica or Mathematica -> Sage converter, So people would be expected to look at what commands might do. I'm not very conversant with how the doctests work, so I can't really comment on the way to do it, but I know if a precisely defined method was used, then it would be possible to extract data with a shell script very easily. No, I don't like that. If nothing else, it will be more confusing to those whose first language is not English, and even though mine is, I don't like that term. > As you've said or alluded to, without a > full transformation of the grammar, it's not a "Natural > Transformation"/functor if I'm using the correct maths terminology. If we were writing a Sage -> Mathematica converter, or a Mathematica -> Sage converter, then clearly we would need to be very precise over this. But if someone uses NIntegrate[] in Mathematica, they would probably want to know what commands are related in Sage. It might be only "integrate" but there might be others. At that point they know what commands it would be worth using the help system for. >> Nobody can expect the commands to be identical - except for trivial ones like >> Sin[], Cos[]. In the case of factor() there are two very obvious Mathematica >> commands that provide broadly similar functionality. > > Since Mma doesn't post it's BNF (Grammar), it's an exercise in reverse > engineering. > > -Don But we don't need that for documentation. I'd be quite keen to have Sage read Mathematica input, or at least some sort of converter. Then one needs to be a lot more accurate about the differences between commands. But for documentation like this, we don't need it. There's no need to reverse engineer anything. Dave To be honest, I'd guess Sage changes more in a backwards incompatible way than Mathematica! If for no other reason that the release cycle of Mathematica, Maple and MATLAB are much longer than Sages. (I don't know about Macsyma, but I know of product aimed at professionals with a release cycle like Sage.) Yes, maintenance could be an issue, but I believe even outdated references will be better than none at all. Perhaps there needs to be two sets of information then. 1) What I suggested. I'm not going to argue about the wording, but for the sake of this discussion assume "Related Mathematica commands" 2) What Nathann suggested, but wrapped inside some very rigid structure, so the full text can be extracted. Again, I'm not going to argue about the wording, but lets for this discussion keep it to "Notes about the relationship between Mathematica and Sage" and "End of notes about the use of Mathematica" So for Sage's factor(), we would have something like: **Related Mathematica commands:** Factor FactorInteger FactorList FactorSquareFree FactorSquareFreeList FactorTerms FactorTermsList **Notes about the relationship between Mathematica and Sage** FactorInteger[] is used in Mathematica to factor only integers, with several other commands used to factor polynomials. In contrast, Sage, factor() is used to factor both polynomials and integers. In both systems, testing if a number is prime is considerably quicker than factorising that number, so much larger integers can be checked for primality, that what can be factored in a reasonable amount of time. In Mathematica, the command PrimeQ[] is used to test whether a number is prime. In Sage, is_prime() can be used to test if a number is prime. ** End of notes about the use of Mathematica ** Then everything between: **Notes about the relationship between Mathematica and Sage** and ** End of notes about the use of Mathematica ** could easily be extracted with a script. (You don't need to have the *'s. I only put that to indicate what text would be in a rigid format.) The notes could be split into multiple paragraphs - one could still extract it with a shell script. As long as that information is in a rigid format, extracting it is very easy. As soon as people just write what they fancy on the day, then it would be an impossible task. > Though it kind of disappeared from the discussion, I also like adding > the Wikipedia and Mathworld references. Don't we already have a > "references" section? This could be extended to including not directly > cited material. Or we could add a "See also" section, like > Wikipedia's. I was thinking of adding them in the doctest, being specific to the command. So in the above case, we might add Related external references: End of related external references: Again, if the structure was rigid, these could be extracted with a script and if necessary one create hyperlinks, which people could click. > Cheers, > Johan Dave
https://groups.google.com/g/sage-devel/c/LhCm41I3yH4?hl=en
CC-MAIN-2022-21
refinedweb
1,928
60.35
ASP.NET MVC Calendar component I am writing simple ASP.NET MVC system that I plan to publish with source code pretty soon. I needed some simple calendar component that doesn’t require ASP.NET server-side form to work. I found different JavaScript based calendars and only one pretty old calendar that was specially written for ASP.NET MVC. I updated it and here is the source and binary downloads for Visual Studio 2008 and ASP.NET MVC 1.0. Well, this component is written for ASP.NET MVC Preview and with my modifications it also works for MVC 1.0 too. I was not able to get contact with author so I published files here. I changed no names of namespaces and classes, so it is easy to merge my changes to current code if author wishes it.. Download AllWebIdea.zip Visual Studio 2008 Project with binaries Size: 28KB
http://weblogs.asp.net/gunnarpeipman/asp-net-mvc-calendar-component
CC-MAIN-2014-52
refinedweb
151
68.06
Just the Cure, More Groovy Actor Christopher Walken once performed a skit on Saturday Night Live in which he proclaimed he needed more cowbell to get rid of his "fever". In the same light, the Groovy team has certainly heard the calls for more Groovy and have recently released 1.6 of their award winning language. There are a slew of new features mentioned in the release including, - One of the primary focuses in this release was on performance and the Groovy team claims to have made significant improvements ranging from 150% to 460%. Another feature included in this release was the official integration of the JMX builder, which is just another example of community efforts helping to improve Groovy. Below are some examples of several of the new features including multiple assignments and AST transformations. // this class' properties are immutable once the object is constructed @Immutable final class ServerConfig { String url int port } def getServerInfo() { ['', 8080] } // attempts to set a property on an Immutable object def setUrl(config, newUrl) { try { config.url = newUrl } catch (ReadOnlyPropertyException ex) { ex } } // multiple assignment def (url, port) = getServerInfo() assert url == '' assert port == 8080 def config = new ServerConfig(url, port) assert config.url == url assert config.port == port // try to change the property on the Immutable object def result = setUrl(config, '') // verify the property change failed assert result instanceof ReadOnlyPropertyException The example above shows how the @Immutable AST transformation provides a very simple way of creating a read-only object. The example also demonstrates using the new "multiple assignments" feature. For more information about the AST transformations you can visit the Groovy user guide, currently the section only covers the @Immutable transformation. Now that you've seen a quick overview of what Groovy 1.6 has to offer, check out What's New in Groovy 1.6, an in-depth article about Groovy 1.6 written for InfoQ by the Groovy Project Manager, Guillaume LaForge. Guillaume covers each of the new features and provides plenty of code examples which help clarify all of the new capabilities. Grape and grab are pretty nice by andrej koelewijn 1.6 is really more effective than 1.5.7 by qiu james gant is too slow so we have to rewrite it in python, or beanshell. congrats by Roger Pack JRuby or Groovy? by Joshua Partogi Re: JRuby or Groovy? by Guillaume Laforge That is the question now. Groovy, of course ;-) Re: JRuby or Groovy? by Marcio Garcia
http://www.infoq.com/news/2009/03/groovy_1_6
CC-MAIN-2014-52
refinedweb
409
55.54
0 Hi, While executing below code i am getting error like "memory clobbered before allocated block" and due to this assignment is not happening. could you let me know what can be reason for the same. I do understand it is not good to use raw pointer but in current scenario i don't have other than any option. #include<iostream.h> using namespace std; class Derived1 { int *m_p; public: Derived1 (int *m_p):m_p(m_p){}; Derived1& operator =( const Derived1 &obj); void show()const {cout<<"integer address="<<(void*)m_p<<endl; cout<<"integer="<<*m_p<<endl; } ~Derived1(){ delete m_p; } }; Derived1& Derived1::operator=(const Derived1 &obj) { if (this!=&obj) { cout<<"We are Here"; int *orig =m_p; m_p=new int (*obj.m_p); delete orig; } cout<<"objects are same"; return *this; } int main() { int x=110; int y=20; Derived1 s1(&x) ; s1.show(); Derived1 s2(&y); s2.show(); s2=s1; s1.show(); s2.show(); }
https://www.daniweb.com/programming/software-development/threads/476914/pointer-initialization-in-assignment-operator
CC-MAIN-2017-34
refinedweb
149
64.71
Technical Articles How to create CDS entities in SAP Business Application Studio Introduction This blog is continuation of my previous blog wherein I showed how to launch SAP Business Application Studio from SAP HANA Cloud and how to create a dev space to work in SAP Business Application Studio. In this blog I’ll show you how to create CDS entities in SAP Business Application Studio. In SAP HANA a CDS entity is a table that is organized into columns and rows with predefined data types for each column. Steps to create CDS Entities First step is to create a new application in a Workspace. - Go to Terminal menu and select the option New Terminal 2. You see a User $ prompt appears in the bottom section of the screen as shown below. user$ prompt 3. Type the command cd projects to go to projects $ prompt. cd projects 4. Now let us create a application test1. The command to create a application is cds init test1. Syntax is cds init <application_name> create a workspace 5. Go to File menu and select the option Open Workspace. 6. You see that the application test1 that you created in step 4 above appears here. Select it and click on Open. select your workspace 7. The below screen shows that you are in the workspace for the application Test1. 8. Again go to Terminal menu and select the option New Terminal. You do this every time you want to launch a terminal in SAP Business Application Studio. Go to Terminal menu 9. Now the command prompt in the terminal changes to test1 $ as shown in the screen below. 10. Let us now see how to create a CDS entity. Now on the left pane under Explorer menu, right click on the db folder and select the option New File to create a new file named schema.cds. 11. The file schema.cds is created by right clicking on db folder and selecting the option New File. Give the name as schema.cds. In schema.cds window you create and define the actual CDS entities. In this example I’ve created two CDS entities Sales and Purchases. Following is the syntax to create a CDS entity. namespace <namespace_name>; entity <entity_name> { Key id : Integer; —— One of the fields in the entity has to be defined as a Key. Here I’ve used the field id as my key field. Field1: field1 data type; Field2: field 2 data type; Field n: field n data type; } Code for the CDS entities I created in this blog namespace test; entity Sales { key id : Integer; Date_of_Sale : Date; —————- Date should be entered in the format YYYY-MM-DD Particulars : String(100); Amount : String(100); SalesPerson: String(100); Commission: String; } entity Purchases { key id : Integer; Date_of_Purchase : Date; —————- Date should be entered in the format YYYY-MM-DD Particulars : String(100); Amount : String(100); PurchaseAgent: String(100); } To arrange code in a legible manner, right click on the white space and select the option “Format document”. The code appears as shown in the below screen after selecting the option Format document. Format Document 12. Save the code. In terminal window enter the command cds watch and hit enter key. A popup appears with the message “ A service is listening to port 4004” with the button Open in New Tab. Hit on the button Open in New Tab. 13. After typing the cds watch command having defined the cds entities, the message appears as shown in the screen below, saying No service definitions found in loaded models. This means that the loaded models which are the CDS entities do not have a service layer defined with which they can connect to. Hence our next step is to define a service layer. 14. Now let us create a service layer. Right click on the srv folder on the left pane and select the option New File to create a new file called project.cds. Service layer is created under srv folder. This will expose the CDS entities as an odata service. I need to add a service layer to talk to the entities that I’ve created in db layer. Add the following code to the service layer. To create a service layer, right click on srv folder and choose the option New File. In this case I’ve named the file as project.cds. Enter the following code in the project.cds window. Code for Service layer – project.cds file using {test} from ‘../db/schema’; - using is the key word that I used here to refer to the test namespace that is located in schema file in db - I am using test namespace that I created in schema.cds. This schema.cds is located under db folder. - After the from keyword give space and type ‘.. and the system will automatically pickup the path where the test namespace was created. So the path /db/schema will popup after typing ‘.. and select it by pressing the tab key.] - In case you have more than one schema created then you have to select the schema where this namespace and entities is created. service project { [service is the keyword project is the name of the service. Here I am using the two entities that I created in schema.cds.] Code for service layer should appear as shown in the screen below. Code for service layer – project.cds file using {test} from ‘../db/schema’; service project { entity Sales as select from test.Sales; entity Purchases as select from test.Purchases; } [syntax for the above two lines is entity entity_name as select from namespace.entityname;]. 16. The code in project.cds window should appear as shown in the below screen. Save this code and you should see the messages as shown in the lower section of the terminal window that the model has been loaded from 2 files db/schema.cds and srv/project.cds and that they have been deployed to sqlite in-memory database. By default, the entities that you create are stored in sql lite database. You can change it to SAP Hana database. This is shown in the steps later in this blog below. 16. Now let us see how to load data into these two tables that we created above. - Create a new folder named data under db folder by right clicking on the db folder In data folder I will create the actual .csv files that will hold the data. 17. The syntax for the .csv file names is namespace.entityname.csv. So if my namespace is test and entity name is Sales then the .CSV file name will be test.Sales.csv. These .csv files will be created in data folder. - Right click on data folder and select the option New File. Here I’ve named the .csv file as test-Sales.csv. 18. Below screen showing creation of Purchases.csv file. Always your .csv file should be prefixed with namespace. In this case name of the namespace is test hence I’ve prefixed it with test and the file name is test.Purchases.csv. 19. Here is the data I’ve used in my Sales and Purchases CDS entities. Copy and paste this data in Sales and Purchases entities respectively. Then save it. Data for Sales.csv file id;Date_of_Sale;Particulars;Amount;SalesPerson;Commission 100;2020-04-15;Book;Rs. 550;Ajay;Rs. 55 200;2020-04-18;Pencil box;Rs. 110;Vijay;Rs. 10 300;2020-04-25;Pens;Rs. 200;Ramesh;Rs. 60 400;2020-05-15;Erasers;Rs. 75;Suresh;Rs. 5 Data for Purchase.csv file id;Date_of_Purchase;Particulars;Amount;PurchaseAgent 100;2020-02-02;LEDBulbs;Rs650;Raghupati 110;2020-03-15;Tubelightsx;Rs110;Raghava 120;2020-04-09;Cables;Rs00;Raja 130;2020-05-16;Fans;Rs75;Ram 20. Now type the cds watch command again and then click on the “Open in New Tab” button on the popup “A service is listening to port 4004” that appears on the lower right corner. You should now see the CDS entities that you created above, as shown in the screen below. 21. On clicking Purchases and sales links the data loaded in the two entities appears as shown in the below two screens. Data from Sales.cds Data from Purchases.cds 22. Now return to SAP Business Application Studio and in the terminal type the command cds add hana. You should see a message that says “adding feature(s) to project in current folder and adding feature ‘hana’…. as shown in the screen below. This command changes your database type from sqlite to hana database. change database type from sqlite to hana Conclusion These are the steps to create CDS entities in SAP Business Application Studio and change the database type from sqlite to HANA database. Additional Information For more information on how to work with SAP Business Application Studio you may also refer to the videos published in this link. Free Open Course : Please share your feedback about this blog. Hi, Thanks for showing interest in writing blog posts, actually few mistakes in this blog post which needs rework ,it would be great if you correct in your blog post as early as possible . To highlight major one are below ,you have written. Actually From step 11 to Step 13 you just added schema but you have not exposed any service definition yet but you are saying readers that service are available ,you also added screenshots Correct flow is when developers run “CDS watch “ after adding schema (CDS entities ) You can see below message cds] – launched in: 563.601ms [cds] – server listening on { url: ‘’ } [ terminate with ^C ] No service definitions found in loaded models. Waiting for some to arrive.. Correct behaviour is Then you continue by saying in Step 14 to add Service definition ….. ————————————————————————————————————————————– Other small mistake is at line 4 4) Now let us create a workspace test1. The command to create a workspace is cds init test1. Syntax is cds init <workspace_name> It is not <workspace_name> , actually it is application name , CAP bootstrap application based on node js runtime with app,db,srv structure …… # Also in SAP Business Applications Studio there is UI to generate CAP Project without commands # There is new feature SAP Business Applications to Graphical Editor to design entities ,views , association from UI i.e no need to write code ,if someone are interested in easy way of writing CDS without remembering syntax…. I have not reviewed fully your content & it was quick review I also suggest whenever you write blog posts to please have reference links as there are many self-study material available from with samples, if any improvements or new feature comes readers can verify Official CAP documentation : There are also many videos from SAP Developers ,experts basic & advance examples on SAP Business Application Studio , CAP For instance SAP Cloud Application Programming Model Free Open Course : A bunch of good tutorials from community already available with screenshots Thanks for your understanding ,since it is new technology others should not be confused with our blog posts Showkath. Thank you so much Pavan for explaining the steps in detail with screenshots. It was very helpful in creating the entities and following along with detailed steps. Hi, An alternative way to create the project is by using the application wizard: From the welcome page or from the command palette click/type create project from template: Thanks, Liat
https://blogs.sap.com/2020/09/24/how-to-create-cds-entities-in-sap-business-application-studio/
CC-MAIN-2021-43
refinedweb
1,904
65.22
Continuing the quest, I'm working on a framework for signal processing. The plan is to create objects in python and then compose them. The components are (in general) polymorphic. From python the components can be configured and controlled. Also, components can be retrieved back to python from the composites. I've been doing some experiments with boost::shared_ptr. It appears that if components are always stored as shared_ptr, and always passed (by value) as shared_ptr, that life is easy. For example: struct cnt { cnt (int _n) : n (_n) {} int n; }; struct A { A (boost::shared_ptr<cnt> _c) : c (_c) {} boost::shared_ptr<cnt> c; int get() const { return c->n; } void inc() { c->n++; } }; using namespace boost::python; BOOST_PYTHON_MODULE (testA) { class_<cnt> ("cnt", init<int>()); class_<A> ("A", init<boost::shared_ptr<cnt> >()) .def ("get", &A::get) .def ("inc", &A::inc) .def_readwrite ("c", &A::c) ; } >>> c = cnt (0) >>> a = A(c) >>> b = A(c) >>> a.c <testA.cnt object at 0x2aaaaab4b730> >>> b.c <testA.cnt object at 0x2aaaaab4b730> It appears that this design meets all the requirements. Not demonstrated above, but also polymorphism works as expected. Note that here only polymorphism of components written in c++ is required, and that is all I tested. I did not test or require that components could be subclassed in python. Just wondering if I am on the right path here? In particular, it seems there is no need for non-default call or return policies to make this work, which makes life a lot simpler.
http://mail.python.org/pipermail/cplusplus-sig/2006-June/010439.html
CC-MAIN-2013-20
refinedweb
251
67.25
Difference between sum and for loop Hi, I'm currently using sage to calculate some double sums over two variables, where s runs from 1 to t-1, and t runs from 2 to 2x+2n+1. I initially used two nested for loops inside the following function: def qentr(i,j,k,x,n): s,t,sm = var('s,t,sm') sm = 0 for t in range(2,2*x+2*n+2): for s in range(1,t): sm = sm + h(i,s,k,x,n)*h(j,t,k,x,n) - h(j,s,k,x,n)*h(i,t,k,x,n) return sm where i, j, k, x, n are all nonnegative integers. This gives me the correct values for what I am enumerating, for instance qentr(1,3,3,1,2) = 96, which is right. For some reason when I replace these for loops with two nested sums, say, sum(sum(h(i,s,k,x,n)*h(j,t,k,x,n)-h(i,t,k,x,n)*h(j,s,k,x,n),s,1,t-1),t,2,2*x+2*n+1) this no longer gives me the correct values. If I replace the two nested loops with this sum I get qentr(1,3,3,1,2)=196.... I wanted to replace the loops with sum in order to return an expression in x, the only way I can think to do this is with sum but this does not yield the right expression. Does anyone know why this happens? Does anyone know an alternative way I can get the function qentr() to return a polynomial in x? The function h from above is the following: def h(i,j,k,x,n): r = var('r') return binomial(j-1,i-1)-2*sum(binomial(r+i-k,i-k)*binomial(j-i-r+k-2,k-2),r,x+n+(k+1)/2+1-i,j-i) Cheers! Ok so I've had a look at it and the problem arises for some specific values in the double sum. For example, with the functions defined above, h(3,2,3,1,2) = 0 which is correct. However, when I try to compute the same value with sum, I get instead sum(h(3,t,3,1,2),t,2,2) = -6. I think this has something to do with the way in which sum evaluates its arguments. I can't work out how to deal with this, if anyone has any ideas I would really appreciate it.
https://ask.sagemath.org/question/10669/difference-between-sum-and-for-loop/
CC-MAIN-2017-04
refinedweb
429
67.69
Where is the documentation kept for spyder (python IDE) to access? As I am typing plot.savefig( import matplotlib.pyplot as plt plt.savefig() The documentation that you're seeing comes from the docstrings of the function you typed in. You can get the raw text with plt.savefig.__doc__, or get it with a bit of formatting by using the builtin help command from an interactive interpreter: help(plt.savefig). Spyder applies some additional fancy formatting to the contents of its documentation window. How detailed the documentation is will vary quite a bit from module to module. In the case of matplotlib, it's quite detailed, probably because the maintainers have put the effort in to make it easy to use that package without a lot of programming experience. As for your question about how you can view those docs outside of Spyder, I'd suggest looking online. I see on the matplotlib homepage they have extensive documentation, including web pages with the same contents as the docs you were seeing (presumably generated from the same docstrings).
https://codedump.io/share/CQkB1cTHg496/1/where-is-the-documentation-source-for-python-and-spyder-documentation-features
CC-MAIN-2017-04
refinedweb
178
57.27
Released Tuesday, February 23, 2016 Part A (Sections 0 and 1) due Wednesday, March 2, 2016, 10:00 PM Part B (Sections 2 and 3) due Friday, March 11, 2016, 8:00 PM Part C (Section 4) due Friday, March 25, 2016, 9:00 PM This lab will introduce you to privilege separation and server-side sandboxing. The lab continues with the zoobar sequence from MIT's 6.858, which extend assignments developed in Stanford's CS155. The context for this lab follows the design of the OKWS web server, discussed in class. In this lab, you will set up a privilege-separated web server and break up the application code into less-privileged components to contain the effects of vulnerabilities. You will also (possibly for extra credit; we haven't decided whether this part is required) extend the Zoobar web application to support executable profiles: Python code, uploaded by users, that displays a page to other users. Letting users decide what code runs in the context of the Web server sounds dangerous; the work of the lab is making this arrangement safe(r). We describe the details in part 4, below. [UPDATE] Parts B and C of this assignment may be completed pair programming-style. Pair programming means that both of you should be at the screen, together. Take turns with the keyboard, passing it back and forth. Only one member of each pair should submit. Do not begin collaborating until you have submitted part A. To fetch the new source code, connect to the virtual machine, either using ssh or by directly logging on to the shell after starting the virtual machine, navigate to the ~/labs directory, and use git to checkout the lab3 branch from our repo. $ cd ~/labs $ git pull .... $ git checkout -b lab3 origin/lab3 $ _ You'll then need to patch flask in order to get it to work with the lab: $ sudo make fix-flask password for httpd: cs480 ./fix-flask.sh patching file /usr/lib/python2.7/dist-packages/werkzeug/routing.py Done $ _ Once your source code is in place, make sure that you can compile and install the web server and the zoobar application: $ cd ~/labs/lab $ sudo make setup ./chroot-setup.sh + grep -qv uid=0 + id ... + python /jail/zoobar/zoodb.py init-person + python /jail/zoobar/zoodb.py init-transfer $ _ Let's begin by looking at some of the Web app code (as distinct from the code that implements the Web server). One of the killer features—we are talking major disruption here—of the zoobar application is the ability to transfer credits between users. This feature is implemented by the transfer.py script which lives in lab3/zoobar. To get a sense of what transfer does, start the zoobar Web site: $ cd ~/labs/lab3 $ sudo make setup [sudo] password for httpd: ./chroot-setup.sh + grep -qv uid=0 + id ... + python /jail/zoobar/zoodb.py init-person + python /jail/zoobar/zoodb.py init-transfer $ sudo ./zookld zook.conf zookld: Listening on port 8080 zookld: Launching zookd ... Now, make sure you can run the web server and access the web site from your browser as usual. Check the IP address of your virtual machine: $ ) In this particular example, you would want to open your browser and go to. You should see the zoobar web site. The purpose of this exercise is to learn your way around the source code. The rest of the lab is virtually impossible without this understanding (also, a mandatory skill for real-world software developers is to understand complex code bases with multiple interacting parts; use this opportunity to practice). Furthermore, if you try to understand what the source is doing in a "reactive" way (in response to the later exercises), you will very likely end up spending more time than if you had started with a global understanding. First, make sure you know how to run the system. These instructions are above. Second, get a feel for what the application does. users can do. In short, a registered user can update a profile, transfer "zoobars" (credits) to another user, and look up the zoobar balance, profile, and transactions of other users in the system. Third (and this is the part that takes effort), read through the code. A reasonable (but not the only) way to do this is to understand the logic of the transfer application. What does the transfer.py script in the lab3/zoobar directory do? And how is it invoked when a user issues a transfer on the "transfer" page? Other hints: The web server for this lab uses the /jail directory to setup chroot jails for different parts of the web server, much as in the OKWS paper. The make command compiles the web server, and make setup installs it with all ~/labs/lab3 so that it is straightforward to split, there are places where you must redesign certain parts. Second, you must ensure that each piece runs with minimal privileges, which requires setting permissions precisely and configuring the pieces correctly. Ideally, by the end of this lab, you'll have a solid, before proceeding further. If you cannot find the issue, contact the course staff. As noted earlier, the zookws web server is modeled after OKWS. Similar to OKWS, zookws consists of a launcher daemon, zookld, that launches services configured in the file zook.conf; a dispatcher, zookd, that routes requests to corresponding services; and several services. For simplicity, zookws does not implement analogs of OKWS's pubd or logd. and as root and can bind to a privileged port like 80. Note that in the default configuration, zookd and the services are inappropriately running under root and are not "jailed"; an attacker who exploits buffer overflows can cause damage to the entire server (for example, the link/unlink attack that you mounted in lab. As you work through the exercises below, "sudo make check" will check them; however, two disclaimers are in order. First, these tests are not exhaustive! Second, it is often more convenient to test by yourself rather than relying on make check. Nevertheless, as you plan your implementation for each of the exercises below, you may want to read over the test cases invoked by make check. Most of the log files produced by the test scripts will be saved in the /tmp directory. do the tests in check_lab3.py. First, modify the function launch_svc in zookld.c so that it sets the userID, groupID, and supplementary group list that are specified in zook.conf. You will need to use the system calls setresuid(), setresgid(), and setgroups(). Second, change the zook.conf uid and gid for zookd and zookfs so that they run as something other than root. Third, modify chroot-setup.sh: ensure that the data on the disk (meaning the databases)/or/directory which will set the owner of the given file or directory to 1234, the group to 5678, and the permissions to 755 (i.e., user read/write/execute, group read/execute, other read/execute). Hints: Run sudo make check to verify that your modified configuration passes our basic tests. Now that none of the services are running as root, we will try to further privilege-separate the zookfs_svc service that handles both static files and dynamic scripts. The first reason to do this is that some Python scripts could easily have security holes; if we do not separate the static and dynamic files, then a vulnerable Python script could be tricked into deleting and that the dynamic service cannot modify static files. This separation requires zookd to determine which service should handle a particular request. You can. zookfs can be configured to run only executables or scripts marked by a particular combination of owning user and group. To use this feature, add an args = UID GID line to the service's configuration. For example, the following zook.conf entry [safe_svc] cmd = zookfs uid = 0 gid = 0 dir = /jail args = 123 456 specifies that safe_svc will execute only files owned by user ID 123 and group ID 456. You need this args = mechanism for the dynamic server to ensure that it executes only. Here is a checklist for before you submit: $ git add <new file 1> <new file 2> ... $ git commit -am "My submission for lab 3 part A" ... $ git push -u origin lab3 # Prompts for username and password Counting objects: ... .... $ _ The previous part privilege-separated the components of zookws. In this part, you will privilege-separate the zoobar application itself by placing different components in different processes. This way, if one piece of the zoobar application has an exploitable bug, an attacker cannot use the bug to break into other parts of the zoobar application. A challenge in splitting the zoobar application into several processes is that the processes need to be able to communicate. You will first study a Remote Procedure Call (RPC) library that allows processes to communicate over a Unix socket. Then, you will use that library to separate zoobar into several processes that communicate using RPC. To illustrate how our EchoRpcServer RPC class defines the methods that the server supports, and rpclib invokes those methods when a client sends a request. The server defines a simple method that echoes the request from a connect to the socket. We have also included a simple client of this echo service as part of the Zoobar web application. In particular, when you direct your Web browser method separate the code that deals with user authentication data (meaning passwords and tokens) from the rest of the application. The current zoobar application stores everything about the user (profile,. Once the authentication data is split out into its own database, however, we can set Unix file and directory permissions such that only the authentication service—and not the rest of Zoobar—can access that information. Specifically, your job will be as follows: Implement privilege separation for user authentication, as described above. Don't forget to create a regular Person database entry for newly registered users. Hint: It may be useful to use Python's "unpacking syntactic rules". These allow the programmer to "unpack" an array of values into a list of arguments for a function, as in the following example: def f(x,y,z): return z - x*x + y*z - x b = {"x":4, "y":5, "z":5} # The following two lines do the same # thing. The first uses the "standard" # approach whereas the second uses # unpacking of the dictionary 'b'. f(4,5,5) # Standard way to call f f(**b) # Unpacking b as f's arguments Run sudo make check to verify that your privilege-separated authentication service passes our tests (but don't rely on these tests, since it can take longer and be less direct to test this way). When testing "manually", remember to do sudo make setup. We hash), an adversary will not be able to directly obtain the user's password. The server can still check if a user supplied the correct password during login, though: it will just hash the user's password, and check if the resulting hash value is the same as was previously stored. One weakness with hashing is that an adversary can build up a giant table (called a "rainbow table"), containing the hashes of all likely passwords. Then, if an adversary obtains someone's hashed password, the adversary can just look it up in its giant table. os.urandom returns a string of random binary data. To convert to and from hex strings (useful for storing in database tables), you may wish to import binascii, and invoke binascii.hexlify() and binascii.unhexlify(). Run sudo make check to verify that your hashing and salting code passes our tests. Keep in mind that our tests are not exhaustive. Furthermore, our tests can take longer and be less direct to test than when you test "manually". When testing "manually", remember to do sudo make setup.. labs/lab3 directory that gives a brief overview of your approach and bank's bank service and verifying that it is not possible to perform a transfer without supplying a valid token. Also, make sure that valid transfers go through (which you can do by running sudo make check again). Here is a checklist for before you submit: $ git add <new file 1> <new file 2> ... $ git commit -am "My submission for lab 3 part B" ... $ git push -u origin lab3 # Prompts for username and password Counting objects: ... .... $ _ As stated at the outset of the lab, a user can upload Python code to the server; the server runs that code when any user (including the user who uploaded the profile) selects that profile to view. To make a profile, a user saves a Python program in their profile on their Zoobar home page. (To indicate that the profile contains Python code, the first line must be #!python.) An example profile is one that keeps track of the last several visitors to that profile. Supporting this safely requires sandboxing the profile code on the server. This means preventing the code from performing arbitrary operations. What makes this challenging is that the profile code may wish to interact with the environment, for example to read and write files (as in the visitor-tracking example). So the system somehow needs to allow profiles to get their work done, while preventing them from interfering with other profiles or the rest of the system. Sound familiar? Indeed, for this purpose, you will use similar ideas and mechanisms to those you used in the earlier parts: the RPC library, file permissions, etc. At this point, familiarize yourself with the following components: First, the profiles/ directory contains several example profiles. These are executable Python scripts, which you will use as examples throughout this part of the lab: profiles/hello-user.py: prints back the name of the visitor when the profile code is executed, along with the current time. profiles/visit-tracker.py: keeps track of the last time that each visitor looked at the profile, and prints out the last visit time (if any). profiles/last-visits.py: records the last three visitors to the profile, and prints them out. profiles/xfer-tracker.py: prints out the last zoobar transfer between the profile owner and the visitor. profiles/granter.py: gives the visitor one zoobar. To make sure visitors can't quickly steal all zoobars from a user, this profile grants a zoobar only if the profile owner has some zoobars left, the visitor has less than 20 zoobars, and it has been at least a minute since the last time that visitor got a zoobar from this profile. Second, zoobar/profile-server.py: an RPC server that accepts requests to run some user's profile code, and returns the output from executing that code. This server uses sandboxlib.py (described below) to create a Sandbox and execute the profile code in it (via the run_profile function). profile-server.py also sets up another RPC server (besides itself). Finally, zoobar/sandboxlib.py is a Python module that implements sandboxing for untrusted Python profile code; see the Sandbox class, and the run() method which executes a specified function in the sandbox. The run method works by forking off a separate process and calling setresuid in the child process before executing the untrusted code, so that the untrusted code does not have any privileges; this is a key component of the sandboxing approach. The parent process reads the output from the unprivileged child process (which is now running the untrusted profile code) and returns this output to the caller of run() (the direct caller is profile-server.py; the indirect caller is the RPC client of the profile server). If the (sandboxed) child doesn't exit after a short timeout (5 seconds by default), the parent process kills the child. Another key aspect of the sandboxing is our friend chroot: Sandbox.run() uses this system call to jail the untrusted code,ed process,. To prevent this, Sandbox uses Unix's resource limits to prevent sandboxed code from forking. Specifically, the sandbox uses setrlimit, which limits the number of processes with a given user ID; the sandbox sets this limit to 0. As a consequence, after the parent process kills the child process (or notices that the child has exited), the parent knows that there are no remaining processes with that user ID.. Add profile-server.py to your web server. Change the uid value in ProfileServer.rpc_run() from being hard-coded to 0 to a value that comes from an additional argument (in the service's args entry) in zook.conf. That value should be be set in the configuration file to be non-0, and in particular, it should be compatible with your solutions to the exercises in the earlier parts. Make sure that your Zoobar site can support all of the five profiles. Depending on how you implemented privilege separation earlier, you may need to adjust how ProfileAPIServer implements rpc_get_xfers or rpc_xfer. Run sudo make check to verify that your modified configuration passes our tests. The test case (see check_lab3_part. The next problem we need to solve is that some of the user profiles store data in files. (See last-visits.py and visit-tracker.py.). Now that profiles contain Python code and can give away the user's zoobars, it's important that the user's profile code is not modified by an attacker, and labs/lab3 directory so we know to take a look at your solution. Here is a checklist for before you submit: $ git add <new file 1> <new file 2> ... $ git commit -am "My submission for lab 3 part C" ... $ git push -u origin lab3 # Prompts for username and password Counting objects: ... .... $ _ Last updated: 2016-04-15 16:24:03 -0400 [validate xhtml]
https://cs.nyu.edu/~mwalfish/classes/16sp/labs/lab3.html
CC-MAIN-2018-34
refinedweb
2,979
62.38
LibreOffice » oox View module in: cgit Doxygen Support for Office Open XML, the office XML-format designed by Microsoft.: example of drawingml custom shape (equal to star5 preset): we needed to extend our custom shapes for missing features and so 5 new segment commands were added. G command for arcto drawingml record and H I J K commands for darken, darkenless, lighten, lightenless records. the commands are save into ODF in special namespace drawooo, which is extension not yet in the standard. Thorsten suggested to put it in such a namespace and keep original (incomplete) geometry for backward compatibility, before we can extend the ODF. that's why you will see 2 of them in cases where some of the new commands was needed. In order to convert preset shapes to LO's enhanced custom shape, we need to load shape definition of preset shapes. The procedure to convert the definition from OOXML spec for LO is documented ( also a script ) in oox/source/drawingml/customshapes/README. The scripts in oox/source/drawingml/customshapes/ also generate pptx files for single presets and also for all presets cshape-all.pptx. The cshape-all.pptx file is then loaded into Impress build with debug enabled in oox and the command line output contains information. The generated definition is oox-drawingml-cs-presets. Check CustomShapeProperties::initializePresetDataMap() to see how generated presets data are loaded into LO. While importing presets, we prefix the name with "ooxml-" so that we can detect it on export as save it again as preset. The generated pptx files can be used when debugging bugs in custom shapes import/export. also the cshape-all.pptx can be used to test the round trips. there's small problem with these pptx as they cannot be imported into powerpoint, but that can be fixed quickly. when fixed, we can use it to test powerpoint odp export and see how complete it is regarding custom shapes. OpenXML SDK tools might help when fixing cshape-all.pptx Check Andras Timar's presentation1 and ShapeExport::WriteCustomShape() for further detail. FUTURE WORK: because we have to make sure that all the roundtrips like PPTX --> ODP --> PPTX work correctly and doesn't lose data. the only problematic part is probably saving custom shapes (ie. not presets) to PPTX. that part of code predates work on custom shapes and is unable to export general custom shapes yet. It will need a bit of work as LO has more complex equations than DrawingML. other parts should work OK, PPTX --> ODP should work and don't lose any data. presets should already survive PPTX --> ODP --> PPTX roundtrip 1 slides/1184/export/events/attachments/drawingml/slides/1184/ andras_timar_fosdem_2016.pdf Generated by Libreoffice CI on lilith.documentfoundation.org Last updated: 2019-08-11 15:14:37 | Privacy Policy | Impressum (Legal Info)
https://docs.libreoffice.org/oox.html
CC-MAIN-2019-35
refinedweb
470
56.45
Decoding QR Codes with Python Last Updated: 2019-03-24 17:08:04 UTC by Didier Stevens (Version: 1) In diary entry "Sextortion Email Variant: With QR Code", I had to decode a QR code. I didn't mention it in my diary entry, but I used an online service to decode the QR Code (I didn't want to use my smartphone). But what if you don't want to use any online service? You can also use a Python module: python-qrtools. I installed it on Ubuntu 18 with the following command: sudo apt-get install python-qrtools And then I used a simple Python program like this one: import sys import qrtools qr = qrtools.QR() print(qr.decode(sys.argv[1])) print(qr.data) We received the sextortion email with QR code as a .msg file. These files can be analyzed with oledump.py: Plugin plugin_msg can help with locating the streams that contain the attachments (images): The beginning of the content of the attachment data streams indicates that these are .png files: \x89PNG. Grepping for PNG reveals that stream 3, 11 and 19 contain the .png files: Extracting the .png attachments to disk: Decoding the QR code: Images 1 and 2 don't contain a QR code (False), but image 3 does (True), and the Bitcoin address is displayed. Didier Stevens Senior handler Microsoft MVP blog.DidierStevens.com DidierStevensLabs.com
https://www.dshield.org/diary/Decoding+QR+Codes+with+Python/24774
CC-MAIN-2022-05
refinedweb
234
63.49
A mobile, desktop and website App with the same code React-native, NW, Electron and React, all in one A few months ago after react-native was released I started to wonder how it would be possible to do a mobile App, desktop App and website App with the same code base. I knew it was possible but I wanted to explore how to do it and what would be the final volume of reused code. So I created this project. Get the code on Github Of course, all of the code is available on Github under this repository react-native-nw-react-calculator . More about the project This project shows how the source code can be architectured to run on multiple devices. As of now, it is able to run as: - an iOS and Android Apps (based on react-native ) - a desktop App (based on NW or Electron ) - a website App in any browser (based on react ) It is a beautiful calculator with the “memory of previous formulae” feature based on the design of Robert O’Dowd who kindly authorized me the use it. The original design made by Robert was part of his project called “Simplifycation” visible here . Like a production project I wanted for this project to use all the tools that I would have used in a production project, so it is based on the flux architecture and uses tools like grunt and webpack to create the builds and for the hot reloading feature. In the code 3 main builds Although we are going to run on 4 devices (iOS, Android, desktop, web), we only need to create 3 builds. Entry files for those builds are at the root of the src directory. - index.ios.js is the entry file for the iOS App build - index.android.js is the entry file for the Android App build - index.js is the entry file for the website App and desktop App builds (both with NW and Electron) The build for the website App and the desktop Apps is the same because it is possible to reuse the exact same code in both environments. Then, this build is simply called from different .html sources. Flux architecture actions/stores All the flux architecture is share at 100% to all the different builds. This means that all the logic and data management code is done once and reuse everywhere. This allows us to have an easy tests suite and to ensure that our code is working properly on all the devices. Components Here comes the real interest of the project. Finding how the components can be structured to share most of their logic but still allowing for some specificity for each device was not so easy. Having inheritance for the shared logic and only redefine what is specific to every device sounds the right solution but how to include only the code that we want for each build. It could have been done with webpack and its variables evaluated during the build but thanks to @cjbprime I managed to do it based on the file extensions. Basically, every component has a main Class which inherits a base Class containing all the logic. Then, the main component import a different Render function which has been selected during the build. The file extension .ios.js, .android.js or .js is (Screen.js) which composes the other files. 'use strict'; import Base from './ScreenBase'; import Render from './ScreenRender'; export default class Screen extends Base { constructor (props) { super(props); } render () { return Render.call(this, this.props, this.state); } } As the last code sample, here is the ScreenRender.ios.js file which imports the ScreenRender.native.js file. 'use strict'; import Render from ‘./ScreenRender.native’; export default function () { return Render.call(this, this.props, this.state); } Originally published at blog.benoitvallon iOS, Android, desktop and website App with the same code 评论 抢沙发
http://www.shellsec.com/news/14985.html
CC-MAIN-2018-09
refinedweb
648
62.07
Getting Started with Ionic: Angular Concepts & Syntax By Josh Morony This article was originally written following the release of Ionic 2, and focused on the new concepts and syntax introduced in the new version of Angular, along with some comparisons to Ionic 1.x and AngularJS. Since then, Ionic 4 has been released which now allows us to use Ionic with any framework (not just Angular). Angular still remains the most popular choice for Ionic development, so I decided to revisit this post and update it to be relevant today. This article focuses mostly on some basic concepts behind using Angular, which have mostly stayed the same since the initial release. With the current iterations of the Angular and Ionic frameworks, we are able to make apps that perform better on mobile, adhere to the latest web standards, are scalable, reusable, modular, and so on. As always, we continue to use the web tech (HTML, CSS, and Javascript) that we know and love to build applications, but there are some conceptual and syntax differences that we need to understand when using Ionic and Angular (versus standard HTML/CSS/JavaScript). For example, the HTML we use in our templates looks a little different than you might be used to: <ion-header> <ion-toolbar> <ion-title> Ionic Blank </ion-title> </ion-toolbar> </ion-header> <ion-content> <div class="ion-padding"> The world is your oyster. <p>If you get lost, the <a target="_blank" rel="noopener" href="">docs</a> will be your guide.</p> </div> <ion-list> <ion-item button * </ion-item> </ion-list> </ion-content> and the same goes for the Javascript: import { Component } from '@angular/core'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { constructor(private navCtrl: NavController){ } viewItem(item){ this.navCtrl.navigateForward('/items/' + item.id) } } If you’re already familiar with ECMAScript 6 or TypeScript then a lot of this will likely already look somewhat familiar. I also have an introduction to ECMAScript 6 and Angular for Ionic developers, but in this post I wanted to dive into the actual syntax we will be using in Ionic/Angular applications. Angular & Ionic Concepts Before I get into the syntax, I wanted to cover a few new general concepts you might come across when learning Ionic & Angular. Transpiling Transpiling means converting from one language to another language. Why is this important to us? Basically, ES6 gives us all this new stuff to use, but ES6 is just a standard and it is not completely supported by browsers yet. We use a transpiler to convert our ES6 code into ES5 code (i.e. “normal Javascript”) that is compatible with the browsers of today. Once ES6 is widely supported, this step wouldn’t be necessary. In the context of Ionic applications, here’s an idea of how it might look: When we run ionic serve, our code inside of [the app folder] is transpiled into the correct Javascript version that the browser understands (currently, ES5). That means we can work at a higher level using TypeScript and ES6+, but compile down to the older form of Javascript the browser needs. - Ionic Website You don’t need to worry about how this process works, this all happens automatically when you build your Ionic applications. However, it is useful to understand why you can use the fancy new JavaScript stuff. Web Components Web Components are kind of the big thing that is emerging now – they weren’t really feasible to use in Angular 1.x but the current version of Ionic is entirely based on web components. Web Components are not specific to Angular or Ionic, they are becoming a new standard on the web to create modular, self-contained, pieces of code that can easily be inserted into a web page (kind of like Widgets in WordPress). In a nutshell, they allow us to bundle markup and styles into custom HTML elements. - Rob Dodson Rob Dodson wrote a great post on Web Components where he explains how they work and the concepts behind it. He also provides a really great example, and I think it really drives the point home of why web components are useful. Basically, if you wanted to add an image slider as a web component, the HTML for that might look like this: <img-slider> <img src="images/sunset.jpg" alt="a dramatic sunset"> <img src="images/arch.jpg" alt="a rock arch"> <img src="images/grooves.jpg" alt="some neat grooves"> <img src="images/rock.jpg" alt="an interesting rock"> </img-slider> instead of> Rather than downloading some jQuery plugin and then copying and pasting a bunch of HTML into your document, you could just import the web component and add something simple like the image slider code shown above to get it working. Web Components are super interesting, so if you want to learn more about how they work (e.g. The Shadow Dom and Shadow Boundaries) then I highly recommend reading Rob Dodson’s post on Web Components. Since originally writing this article, I have also released articles of my own about various aspects of web components (and how they relate to Ionic): However, keep in mind that some of these concepts are little on the advanced side. For the most part, you don’t actually need to know much about how web components work if you just want to use them in Ionic. If you are not interested in the mechanics of it all, then most of the time it is going to be as simple as dropping a web component into your template like this: <ion-button>Click me</ion-button> This is how Ionic works today, we can use the web components that Ionic provides to us, or we can create our own custom Angular components. By adding these tags to our templates, whatever functionality they provide will be embedded right there. Ionic provides a lot of these pre-made components that we can just drop into our applications to create sleek mobile user interfaces, which is one of the reasons the Ionic framework is so powerful (Ionic does most of the work for us). Classes Classes are a concept from Object Oriented Programming. There’s quite a lot to cover on the topic of classes, and I’m not going to attempt to do that here. A good place to start understanding the concept of classes is Introduction to Object-Oriented JavaScript, but keep in mind this is the current (soon to be old) way of implementing objects in JavaScript. JavaScript has never had a class statement, so instead of creating actual classes functions were used to act as classes, but now we will be able to use an actual class syntax with ES6. In general, a class represents an object. Each class has a constructor which is called when the class is created (this is where you would run some initialisation code and maybe set up some data that the class will hold), and methods that can be called (both from within the class itself, but also by code outside of the class that wants access to something). We could have a Page object for example. That Page object could store values like title, author and date which could be initialised in the constructor. Then we could add some methods to the class like getAuthor which would return the author of the page, or setAuthor which would change the author. How the concept of classes apply to Ionic/Angular applications should start to become apparent as you begin learning and building applications, but having a bit of background on the general concept helps. Angular Syntax Now let’s take a look at some actual Angular syntax that you will be using in your Ionic applications. Before I get into that though, I think it’s useful to know about the APIs that each and every DOM element (that is, a single node in your HTML like <input>) have. Let’s imagine we’ve grabbed a single node by using something like getElementById(‘myInput’) in JavaScript. That node will have attributes, properties, methods and events. An attribute is some data you supply to the element, like this: <input id = "myInput" value = "Hey there"> This attribute is used to set an initial property on the element. Attributes can only ever be strings. A property is much like an attribute, except that we can access it as an object and we can modify it after it has been created. For example: var myInput = document.getElementById('myInput'); console.log(myInput.value); // Hey there myInput.value = "What's up?"; console.log(myInput.value); // What's up? myInput.value = new Object(); // We can also store objects instead of strings on it A method is a function that we can call on the element, like this: myInput.setValue('Hello'); An element can also fire events like focus, blur, click and so on – elements can also fire custom events. Ok, now let’s take a look at some Angular code! There’s a great Angular cheat sheet you can check out here, I’ll be using some examples from there. The examples in the following section are specific to Angular. The syntax we will be using and the functionality they achieve is something built-in to Angular, unlike the stuff up until this point which have mostly just been generic web concepts. Binding a Property to a Value <input [value]="firstName"> This will set the elements value property to the expression firstName. Note that firstName is an expression, not a string. This means that the value of the firstName variable (defined in your class) will be used here, not the literal string ‘firstName’. Binding a Function to an Event <ion-button (click)="someFunction($event)"> This will call the someFunction function and pass in the event whenever the button is clicked. You can replace click with any native or custom event you like. Rendering Expressions with Interpolations <p>Hi, {{name}}</p> This will evaluate the expression and render the result in the template. In this case, it would just display the name variable here, but you can also create other expressions like {{1+1}} which would render 2 in the template. Two Way Data Binding Angular has a concept of two-way data binding, meaning that if we updated a value in our class the change would be reflected in the template, and if we changed the value in the template it would be reflected in the class. We could achieve this two way data binding in Angular like this: <input [value]="name" (input)="name = $event.target.value"> This sets the value to the expression name and when we detect the input event we update name to be the new value that was entered. To make this easier, we can use ngModel in Angular like this to achieve the same thing: <input [(ngModel)]="name"> This syntax is just a shortcut for the same syntax we described above. Creating a Template Variable to Access an Element <p #myParagraph></p> This creates a local variable that we can use to access the element, so if I wanted to add some content into this paragraph I could do the following: <ion-button (click)="myParagraph.innerHTML = 'Once upon a time...'"> NOTE: This is just an example to show that you can access the properties of the paragraph tag using the template variable – you shouldn’t actually modify the content of elements using innerHTML in this way. Structural Directives <section * <li * We can use structural directives to modify our templates. The *ngIf directive will remove a DOM element if the condition it is attached to is not met. The *ngFor directive can loop over an array, and repeat a DOM element for each element in that array. Decorators @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) Decorators like @Component, @Directive and so on allow you to attach information to your components. The example above would sit on top of a class to indicate that it is a “component” and also additional information like the selector that should be used for the tag name, the path to the template that is being used with this class, and the associated styles as well. You can read more about decorators here which is a preview from my book. Import & Export ES6 allows us to Import and Export components. Take the following component for example: import { Component } from '@angular/core'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-cool-component', templateUrl: 'cool-component.component.html', styleUrls: ['cool-component.component.scss'], }) export class MyCoolComponent { constructor(private navCtrl: NavController){ } } This component is making use of Component and NavController so it imports them. The MyCoolComponent component that is being created here is then exported. Now you would be able to access MyCoolComponent by importing it elsewhere: import { MyCoolComponent } from './components/my-cool-component/my-cool-component'; Depdendency Injection Let’s take another look at one of the examples from above to briefly touch on what “dependency injection” is: import { Component } from '@angular/core'; import { NavController } from '@ionic/angular'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { constructor(private navCtrl: NavController){ } viewItem(item){ this.navCtrl.navigateForward('/items/' + item.id) } } We first import the NavController at the top of the file. We then “inject” it through the constructor like this: constructor(private navCtrl: NavController){} By adding navCtrl as an argument in the constructor and assigning it a “type” of NavController (the thing we just imported) it will set up a reference to NavController for us on a class member called navCtrl. This means that we can then access the functionality that NavController provides using the navCtrl variable which is now accessible throughout the entire class. This is what we are doing inside of the viewItem method. Summary I hope that this article has been able to familiarise you with a few key concepts behind Ionic & Angular. Of course, there is much more to learn about both Ionic & Angular on top of the concepts we have covered in this article (and even the stuff we have covered in this article have only been touched upon lightly). You will find plenty of additional tutorials on this website, as well as in my book, to help you along the way.
https://www.joshmorony.com/ionic-2-first-look-series-new-angular-2-concepts-syntax/
CC-MAIN-2019-51
refinedweb
2,395
50.36
Tetrahedral Numbers September 13, 2011 Before I started writing my own programming exercises, I enjoyed solving other programming exercises available on the internet, many of them mathematical in nature. Today’s exercise comes from and concerns triangular and tetrahedral numbers. A triangular number tells the number of ways that balls can be stacked in a triangle. The first triangular number is 1, the second is 3 (a row of 1 plus a row of 2), the third triangular number is 6 (the first two rows plus a row of 3), the fourth triangular number is 10 (adding a row of 4), the fifth triangular number is 15 (think of the 15 balls on a pool table), and so on. A tetrahedral number is the three-dimensional equivalent of a triangular number; think of cannonballs stacked in a three-sided pyramid. The top layer has one ball, the second layer has 3 balls (the second triangular number) so the second tetrahedral number is 1 + 3 = 4, the third layer has 6 balls giving a total of 10 balls in the tetrahedron, and so on. Your task is to find the base of the tetrahedron that contains 169179692512835000 balls. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below. import Data.List tria = tail $ scanl (+) 0 [1..] tetra = 1:zipWith (+) tetra (tail tria) main = do let (Just n) = findIndex (==169179692512835000) tetra putStrLn $ show n My Haskell solution (see for a version with comments): […] today’s Programming Praxis, our goal is to find the base of the three-sided pyramid that has […] For my Python solution, I wrote a linear search as well as a binary one: def tetra(n): return n * (n + 1) * (n + 2) / 6 def prob18_linear(target): n = 1 while tetra(n) < target: n += 1 return n def bin_search(target, func): lo, hi = 1, 10 while func(hi) < t: hi *= 10 mid = (lo + hi) / 2 fmid = func(mid) while fmid != target: if fmid < target: lo, mid = mid, (mid + hi) / 2 else: hi, mid = mid, (lo + mid) / 2 fmid = func(mid) return mid def prob18_log(t): return bin_search(t, tetra) Sorry for the formatting error, I forgot a second quotation mark. Trying again: Python 3 added accumulate() to the itertools library, which makes implementing a linear search a snap. Inspired by Graham’s binary search, I tried to find a way to use ‘bisect’ from the standard library. The Tetrahedrals class fakes being a list of tetrahedral numbers by calculating the numbers on the fly based on the index passed to __getitem__(). This is enough to get bisect() to work when using the lo and hi parameters. In Ruby … We use a lambda to create a tetrahedral function we can pass around specifically to the linear (very slow in this case) and binary (much faster). ;; With binary search. Quite naive. Optimised/more clean version: @Mike: very elegant. I was looking for a way to let bisect do the search for me, but didn’t think beyond having a very large list. all brute force solutions? here’s one using newton’s method: and since the theme seems to be keeping it as concise as possible, good luck reading this one (x^3+3*x^2+2*x)/6 = 169179692512835000; one real root: 1005000 Constant time. Thanks for playing. quick and dirty solution: n<-500 #initial length of vector #b<-20958500 b<-169179692512835000 #number of balls in tetrahedron of interest for (y in 1:20) { tri<-1 for (a in 2:n) { tri<-c(tri,max(tri)+a) } dtri<-1 for (a in 2:n) { dtri<-c(dtri,max(dtri)+tri[a]) } c<-1 for (a in 1:n) { if (dtri[a]==b) { print(a) c<-a } } if (c==1) { n<-n*10 } else { break } }
https://programmingpraxis.com/2011/09/13/tetrahedral-numbers/?like=1&_wpnonce=e3a0b2f395
CC-MAIN-2017-22
refinedweb
641
62.61
You know how some lessons you can only learn from experience? This is such a lesson. I'm sharing it with you so that I may remember it better. That thing that you can't learn in a 6 month bootcamp but takes years of trial and error to hone. I don't know a name for it.— Swizec Teller published ServerlessHandbook.dev (@Swizec) January 7, 2018 Let's say you're building a system for drip campaigns. Because that's how I learned this lesson. Your system is given a set of leads. You have to send them a series of messages, update metadata in your database, and keep the sales CRM (customer relationship management) system up-to-date so when a lead eventually replies to your message, a sales person knows what to do. Hundreds of these systems have been developed by thousands of developers. You're building your own because startups. The core of your system is a send_next_message function. Something like this 👇 def send_next_message(lead)campaign = lead.campaignTwilio.send_message(lead, campaign.message)CRM.update_data(lead)campaign.advance_to_next_messageend It makes sense, right? You take the drip campaign, send the current message with Twilio, update some metadata on your CRM, then advance your campaign to the next message. Works perfect 👌 You run it in a cronjob once a day. Like this: def send_campaignsLead.active.each do |lead|send_next_message.perform_async(lead)endend You go through active leads, pick their campaign, and spawn a new background worker with perform_async. Eventually, your queue will run the code and send your campaign. If anything goes wrong, each campaign is isolated in its own worker. Errors don't affect other campaigns. 👌 Even better, if something goes wrong while sending the campaign, you can retry the worker. And you've just spammed your leads and made them angry Let's review our send_next_message code. def send_next_message(lead)campaign = lead.campaignTwilio.send_message(lead, campaign.message)CRM.update_data(lead)campaign.advance_to_next_messageend An error can happen at any point here. Maybe something goes wrong when you read campaigns from the database. The worker terminates on 1st instruction, and all is good. Things can go wrong when talking to Twilio as well. Their service could be down, your internet could act up, or something else entirely. The worker terminates on 2nd instruction, and all is still good. What if things break when updating your CRM? Third party service, complex set of instructions with multiple API calls, a lot can go wrong. Worker terminates on 3rd instruction. Now you're in trouble. You've already sent a message to your user, but you weren't able to save that info. Your system doesn't know sending happened, and your CRM doesn't know either. When the worker retries, you send the message again. And again. And again. Until the whole worker succeeds. 😅 Your lead just got a bazillion messages, and they're upset. Here's what you should do instead 👇 def send_next_message(lead)campaign = lead.campaignmessage = campaign.messageCRM.update_data(lead)campaign.advance_to_next_messageTwilio.send_message(lead, campaign.message)end Fetch campaign, save the message in a local variable. Then update data in your CRM. Now if updating the CRM fails, you can keep retrying until it succeeds. Updating the CRM was least reliable in my experience. After updating the CRM, you update your local database. This is a reliable operation, but the most common source of programmer errors and nil failures. It happens. Break fast and move things, right? :) At the end, when you're absolutely certain all your data is updated, you send the message to your lead. This is least likely to fail, and if it does, screw it. With this approach, you are guaranteed never to spam your leads. The worst that could happen is that you advance the campaign too early and they get 4 messages instead of 5 and your sales pitch is less polished. That's okay 🙏🏻 Your copy is robust, and annoying people is bad. And now I know why sales automation companies have so much money. This stuff is hard. 😅 PS: There are ways to further improve your worker. You could do your DB first, then rollback if an error occurs. You could try to rollback changes on the CRM if sending fails etc. But that gets complicated️
https://swizec.com/blog/always-put-side-effects-last/
CC-MAIN-2021-21
refinedweb
715
68.87
How are the variables outside of the scope of the function pulled into the function when it's created? I tried decompiling, but I had trouble understanding it. It looked like it uses putfield. Does putfield make a pointer to an object reference? Let's see a concrete example : scala> var more = 1 more: Int = 1 scala> val f = (x: Int) => x + more f: Int => Int = <function1> This closure is an open term. scala> f(1) res38: Int = 2 scala> more = 2 more: Int = 2 scala> f(1) res39: Int = 3 As you see, the closure contains a reference to the captured more variable Here is the Bytecode for the following method containing a closure: def run() { val buff = new ArrayBuffer[Int](); val i = 7; buff.foreach( a => { a + i } ) } Bytecode: public class com.anarsoft.plugin.scala.views.ClosureTest$$anonfun$run$1 extends scala.runtime.AbstractFunction1$mcII$sp implements scala.Serializable { // Field descriptor #14 J public static final long serialVersionUID = 0L; // Field descriptor #18 I private final int i$1; public ClosureTest$$anonfun$run$1(com.anarsoft.plugin.scala.views.ClosureTest $outer, int i$1); ... The Compiler generates a new ClosureTest$$anonfun$run$1 with a constructor with two fields for the variables outside the scope, e.g. i and this of the calling class. The answer is "it depends". There will probably be some major changes to this with the scala 2.11 release. Hopefully 2.11 will be able to inline simple closures. But anyway, let's try to give an answer for the current scala version (javap below is from scala 2.10.2). Below is a very simple closure that uses a val and a var, and the javap output of the generated closure class. As you can see there is a major difference if you capture a var or if you capture a val. If you capture a val it just gets passed to the closure class as a copy (you can do this since it is a val). If you capture a var, the declaration of the var itself has to be changed at the call site location. Instead of a local int that sits on the stack, the var gets turned into an object of type scala.runtime.IntRef. This is basically just a boxed integer, but with a mutable int field. (This is somewhat similar to the java approach of using a final array of size 1 when you want to update a field from inside an anonymous inner class) This has some impact on performance. When you use a var in a closure, you have to generate the closure object and also the xxxRef object to contain the var. One mean thing is that if you have a block of code like this: var counter = 0 // some large loop that uses the counter And add a closure that captures counter somewhere else, the performance of your loop will be lowered significantly. So the bottom line is: capturing vals is usually not a big deal, but be very careful with capturing vars. object ClosureTest extends App { def test() { val i = 3 var j = 0 val closure:() => Unit = () => { j = i } closure() } test() } And here is the javap code of the generated closure class: public final class ClosureTest$$anonfun$1 extends scala.runtime.AbstractFunction0$mcV$sp implements scala.Serializable { public static final long serialVersionUID; public final void apply(); Code: 0: aload_0 1: invokevirtual #24 // Method apply$mcV$sp:()V 4: return public void apply$mcV$sp(); Code: 0: aload_0 1: getfield #28 // Field j$1:Lscala/runtime/IntRef; 4: aload_0 5: getfield #30 // Field i$1:I 8: putfield #35 // Field scala/runtime/IntRef.elem:I 11: return public final java.lang.Object apply(); Code: 0: aload_0 1: invokevirtual #38 // Method apply:()V 4: getstatic #44 // Field scala/runtime/BoxedUnit.UNIT:Lscala/runtime/BoxedUnit; 7: areturn public ClosureTest$$anonfun$1(int, scala.runtime.IntRef); Code: 0: aload_0 1: iload_1 2: putfield #30 // Field i$1:I 5: aload_0 6: aload_2 7: putfield #28 // Field j$1:Lscala/runtime/IntRef; 10: aload_0 11: invokespecial #48 // Method scala/runtime/AbstractFunction0$mcV$sp."<init>":()V 14: return } Similar Questions
http://ebanshi.cc/questions/1424236/how-are-closures-implemented-in-scala
CC-MAIN-2017-04
refinedweb
692
62.48
Testing GPAW¶ Testing of gpaw is done by a nightly test suite consisting of many small and quick tests and by a weekly set of larger test. Quick test suite¶ Use the gpaw command to run the tests: $ gpaw test --help usage: gpaw test [-h] [-x test1.py,test2.py,...] [-f] [--from TESTFILE] [--after TESTFILE] [--range test_i.py,test_j.py] [-j JOBS] [--reverse] [-k] [-d DIRECTORY] [-s] [--list] [tests [tests ...]] Run the GPAW test suite. The test suite can be run in parallel with MPI through gpaw-python. The test suite supports 1, 2, 4 or 8 CPUs although some tests are skipped for some parallelizations. If no TESTs are given, run all tests supporting the parallelization. positional arguments: tests optional arguments: -h, --help show this help message and exit -x test1.py,test2.py,..., --exclude test1.py,test2.py,... Exclude tests (comma separated list of tests). -f, --run-failed-tests-only Run failed tests only. --from TESTFILE Run remaining tests, starting from TESTFILE --after TESTFILE Run remaining tests, starting after TESTFILE --range test_i.py,test_j.py Run tests in range test_i.py to test_j.py (inclusive) -j JOBS, --jobs JOBS Run JOBS threads. Each test will be executed in serial by one thread. This option cannot be used for parallelization together with MPI. --reverse Run tests in reverse order (less overhead with multiple jobs) -k, --keep-temp-dir Do not delete temporary files. -d DIRECTORY, --directory DIRECTORY Run test in this directory -s, --show-output Show standard output from tests. --list list the full list of tests, then exit A temporary directory will be made and the tests will run in that directory. If all tests pass, the directory is removed. The test suite consists of a large number of small and quick tests found in the gpaw/test/ directory. The tests run nightly in serial and in parallel. Adding new tests¶ A test script should fulfill a number of requirements: - It should be quick. Preferably a few seconds, but a few minutes is OK. If the test takes several minutes or more, consider making the test a big test. - It should not depend on other scripts. - It should be possible to run it on 1, 2, 4, and 8 cores. A test can produce standard output and files - it doesn’t have to clean up. Remember to add the new test to list of all tests specified in the gpaw/test/__init__.py file. Use this function to check results: Big tests¶ The directory in gpaw/test/big/ contains a set of longer and more realistic tests that we run every weekend. These are submitted to a queueing system of a large computer. Adding new tests¶ To add a new test, create a script somewhere in the file hierarchy ending with agts.py (e.g. submit.agts.py or just agts.py). AGTS is short for Advanced GPAW Test System (or Another Great Time Sink). This script defines how a number of scripts should be submitted to niflheim and how they depend on each other. Consider an example where one script, calculate.py, calculates something and saves a .gpw file and another script, analyse.py, analyses this output. Then the submit script should look something like: def create_tasks(): from myqueue.task import task return [task('calculate.py', cores=8, tmax='25m'), task('analyse.py', cores=1, tmax='5m', deps=['calculate.py'])] As shown, this script has to contain the definition of the function create_tasks(). See for more details.
https://wiki.fysik.dtu.dk/gpaw/devel/testing.html
CC-MAIN-2019-09
refinedweb
580
76.72
So, I’m learning Haskell. I’ve done the Yorgey course and want to write a web app. How do I start? Should I learn Snap or Yesod? Well, the short answer is no. Here I’m going to outline the creation of the simplest possible Haskell “Hello World” web application. Wai Wai Pom Pom Pom Snap and Yesod are both “big” web frameworks. Of the two, Snap aims to be the smaller. Both have their own web server, templating system and so on. Both are sufficiently complex to need a program to set up a starter project. Both have fairly sophisticated monad stacks to understand. They’re also both phenomenal high-performance pieces of engineering. What this means for a beginner is that you’re going to spend as much time trying to get to grips with the framework as you are learning how to use Haskell. If like me, you’re coming from Clojure, they both feel a bit more like Rails than Compojure. So, are there simpler to understand models out there? Well, the equivalent of Compojure/Sinatra is Scotty. But I found the next level down again more interesting: Wai. Wai corresponds most closely to Ring or Rack. It was intended to be a common API that Haskell web servers could expose. In practice, it’s only Warp that really supports it. However, Warp is a damn fine web server so that shouldn’t hold us back too much. Nearly every Ring app runs Jetty and hardly anyone really worries that the “standard” isn’t as portable in practice as it is in theory. Setting up Hello World To start, create a new directory. For our purposes we’ll call it “example”. Then we set up a completely blank project. mkdir example cd example cabal sandbox init wget cabal init The “sandbox” and “wget” lines I’ll gloss over, but they basically constitute the best way I know to avoid what’s known as “cabal hell”. And believe me, you don’t want cabal hell. When you run the init command, you’ll be asked a whole bunch of questions. The defaults are fine, just make sure you specify you’re creating an executable. It’ll create a file “example.cabal”. You then need to go in and make it look like this: -- Initial semele.cabal generated by cabal init. For further -- documentation, see name: example version: 0.1.0.0 -- synopsis: -- description: license: AGPL-3 license-file: LICENSE author: Rainbow Dash maintainer: rainbow.dash@gmail.com -- copyright: category: Web build-type: Simple -- extra-source-files: cabal-version: >=1.10 executable semele hs-source-dirs: src main-is: Main.hs -- other-modules: -- other-extensions: build-depends: base >=4.7 && <4.8, wai, warp, http-types default-language: Haskell2010 There’s two import edits here. The first is that we specify hs-source-dirs. The default is that the Haskell files are dumped in the project’s root directory, which is a lousy default. The other is that we set up our dependencies: wai, warp and http-types. Wai and http-types from our API, Warp our implementation. Note that dependencies are case-sensitive. You may also be wondering why I haven’t specified any version constraints. That’s because we’ve set them up in the cabal.config instead. Welcome to the new world of LTS Haskell. Writing Hello World mkdir src cd src Now create Main.hs. {-# LANGUAGE OverloadedStrings #-} We need this because Wai uses ByteStrings rather than Strings, and overloaded strings makes using them lower friction. import qualified Network.Wai as W import qualified Network.HTTP.Types.Status as HS import qualified Network.Wai.Handler.Warp as Warp I’m qualifying everything for clarity. In practice, I do this a fair bit even when I’m not writing a blog post. main :: IO () main = main = do putStrLn "Starting Web Server..." Warp.runSettings Warp.defaultSettings app So, all we’re saying here is “Run the app with the default settings for a Warp server.” The default port is 3000. Finally, we need the app itself: app :: W.Application Let’s take a huge detour and examine what that actually means. Understanding W.Application Now, the type of app is W.Application, but that tells us nothing. So let’s look it up (LTS has a hoogle, search for Wai.Application). You’ll find type Application = Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived So, it’s a alias for a type of function. However, the type’s way more complex that we were expecting. What were we expecting? Well, in Ring the type’s more like type ApplicationRing = Request -> Response Take a request, return a response. However, in order to allow for correct resource management, it uses a continuation passing style instead. (I’m hoping to expand on that in another post.) So instead, you need a callback. As you see, we called that respond. What’s respond‘s type? Well, it’s got to take a response. At this point I hit the limits of my understanding. I’d have made the function return (), but instead it returns ResponseReceived which appears to be a placeholder type. Finally, obviously respond is going to have to write to a socket, so it’s going to have to incorporate the IO monad. Now, in most of the more complex APIs, what you find here is a monad transformer stack with IO somewhere in the mix. In Wai, you just get a naked IO ResponseReceived and can build your own later. To summarize, the type of respond is Response -> IO ResponseReceived and that means “when you call it with a response it will do some IO and return that it’s been processed`. Finally, Application expects IO ResponseReceived to be returned from the function. I believe this to be practically motivated: nearly every handler is going to want to call respond as the last thing it does, and this means that the types work when you do that. You Had Me At Hello So, now we’ve understood the type, let’s write the function app request respond = respond $ W.responseLBS HS.status200 [] "Hello World" To unpack this: when you receive a request, respond using status 200 (success), no headers ( []) and byte string “Hello World”. So, that’s about the simplest thing we can possibly do without writing our own web server. Let’s Be Frank So, how does this compare to Sinatra’s famously good home page? Well, for a start we have three files instead of one. However, two of those files are devoted to ensuring that our dependencies don’t mess us around, if you want to do the same in Ruby, you’ll be setting up bundler, using a gemfile.lock in addition to your normal gemfile, so three files again. Haskell actually comes out slightly ahead here if you’re willing to forgo some flexibility, in that the cabal.config is repeatable and upgrading is a matter of trying a new cabal.config/ reverting if it doesn’t work. In comparison, bundler generates a lock file dependent on your current gemfile. If you need to add another library later, it’s up to you to figure out which versions are compatible with your code. On the other hand, if you need more flexibility, you’re going to encounter cabal hell pretty quickly. Good luck. We’ve got three dependencies instead of one. That’s a pity. But it comes from the two sources: - We’ve got to import types declaring interfaces as well as just implementation code. - We don’t have the web server appearing by magic. On the other hand, Sinatra’s actually provided a routing library, and we don’t have one yet. But we could have used Scotty instead. Keep On Running So, let’s see it in action. Get back to the root project directory and type cabal install && dist/*/build/example/example and navigate to. Hey presto, you’ve served a web page. Looking at the headers, all that it’s specified is a Date, the Server and Transfer-Encoding, so we’ll definitely have a bit more work to do to for a full experience. FOOTNOTE: I’m quite pleased with the response this article had on reddit. This discussion is quite interesting and I recommend reading it. FOOTNOTE: Quite a few people have remarked that the comparison section isn’t really fair on Haskell in that I’ve implemented something at the Rack/Wai level, rather than the Sinatra/Scotty level, which is true. However, I wanted to use Wai rather than Scotty to avoid going into monads and monad transformers and ultimately, I think the Haskell one is still quite concise and beautiful in a very precise manner. EDIT:A number of people have pointed out that modern ruby is indeed capable of precise version locking. I’ve updated and expanded the comparison to reflect that. EDIT:Originally I believed that Wai’s continuation passing style was due to asynchronous concerns. Instead, it’s driven by resource management concerns. I’ve corrected the line.
https://colourcoding.net/2015/02/
CC-MAIN-2018-34
refinedweb
1,517
67.25
Tutorial: Get started with the Flask web framework in Visual Studio are part of Flask itself. For example, Flask itself doesn't provide a page template engine. Templating is provided by extensions such as Jinja and Jade, as demonstrated in this tutorial.) - Use the Polls Flask Web Project template to create an polling app that uses a variety of storage options (Azure storage, MongoDB, or memory). Over the course of these steps you create a single Visual Studio solution that contains three separate projects. You create the project using different Flask project templates that are included with Visual Studio. By keeping the projects in the same solution, you can easily switch back and forth between different files for comparison.) Over the course of these steps you create a single Visual Studio solution that contains two separate projects. You create the project using different Flask project templates that are included with Visual Studio. By keeping the projects in the same solution, you can easily switch back and forth between different files for comparison. Note This tutorial differs from the Flask Quickstart in that you learn more about Flask as well as how to use the different Flask project templates that provide a more extensive starting point for your own projects. For example, the project templates automatically install the Flask package when creating a project, rather than needing you to install the package manually as shown in the Quickstart. Prerequisites - Visual Studio 2017 or later on Windows with the following options: - The Python development workload (Workload tab in the installer). For instructions, see Install Python support in Visual Studio. - Git for Windows and GitHub Extension for Visual Studio on the Individual components tab under Code tools. Flask project templates are included with all earlier versions of Python Tools for Visual Studio, though details may differ from what's discussed in this tutorial. Python development is not presently supported in Visual Studio for Mac. On Mac and Linux, use the Python extension in Visual Studio Code. Step 1-1: Create a Visual Studio project and solution In Visual Studio, select File > New > Project, search for "Flask", and select the Blank Flask Web Project template. (The template is also found under Python > Web in the left-hand list.) In the fields at the bottom of the dialog, enter the following information (as shown in the previous graphic), then select OK: - Name: set the name of the Visual Studio project to BasicProject. This name is also used for the Flask project. - Location: specify a location in which to create the Visual Studio solution and project. -. If you don't see this option, run the Visual Studio installer and add the Git for Windows and GitHub Extension for Visual Studio on the Individual components tab under Code tools. After a moment, Visual Studio prompts you with a dialog saying This project requires external packages (shown below). This dialog appears because the template includes a requirements.txt file referencing the latest Flask 1.x package. (Select Show required packages to see the exact dependencies.) Select the option I will install them myself. You create the virtual environment shortly to make sure it's excluded from source control. (The environment can always be created from requirements.txt.) Step 1-2: Examine the Git controls and publish to a remote repository Because you selected the Create new Git repository in the New Project dialog, the project is already committed to local source control as soon as the creation process is complete. In this step, you familiarize yourself with Visual Studio's Git controls and the Team Explorer window in which you work with source control. Examine the Git controls on the bottom corner of the Visual Studio main window. From left to right, these controls show unpushed commits, uncommitted changes, the name of the repository, and the current branch: Note If you don't select the Create new Git repository in the New Project dialog, the Git controls show only an Add to source control command that creates a local repository. Select the changes button, and Visual Studio opens its Team Explorer window on the Changes page. Because the newly created project is already committed to source control automatically, you don't see any pending changes. On the Visual Studio status bar, select the unpushed commits button (the up arrow with 2) to open the Synchronization page in Team Explorer. Because you have only a local repository, the page provides easy options to publish the repository to different remote repositories. You can choose whichever service you want for your own projects. This tutorial shows the use of GitHub, where the completed sample code for the tutorial is maintained in the Microsoft/python-sample-vs-learning-flask repository. When selecting any of the Publish controls, Team Explorer prompts you for more information. For example, when publishing the sample for this tutorial, the repository itself had to be created first, in which case the Push to Remote Repository option was used with the repository's URL. If you don't have an existing repository, the Publish to GitHub and Push to Azure DevOps options let you create one directly from within Visual Studio. As you work through this tutorial, get into the habit of periodically using the controls in Visual Studio to commit and push changes. This tutorial reminds you at appropriate points. Tip To quickly navigate within Team Explorer, select the header (that reads Changes or Push in the images above) to see a pop-up menu of the available pages. Question: What are some advantages of using source control from the beginning of a project? Answer: First of all, using source control from the start, especially if you also use a remote repository, provides a regular offsite backup of your project. Unlike maintaining a project just on a local file system, source control also provides a complete change history and the easy ability to revert a single file or the whole project to a previous state. That change history helps determine the cause of regressions (test failures). Furthermore, source control is essential if multiple people are working on a project, as it manages overwrites and provides conflict resolution. Finally, source control, which is fundamentally a form of automation, sets you up well for automating builds, testing, and release management. It's really the first step in using DevOps for a project, and because the barriers to entry are so low, there's really no reason to not use source control from the beginning. For further discussion on source control as automation, see The Source of Truth: The Role of Repositories in DevOps, an article in MSDN Magazine written for mobile apps that applies also to web apps. Question: Can I prevent Visual Studio from auto-committing a new project? Answer: Yes. To disable auto-commit, go to the Settings page in Team Explorer, select Git > Global settings, clear the option labeled Commit changes after merge by default, then select Update. Step 1-3: Create the virtual environment and exclude it from source control Now that you've configured source control for your project, you can create the virtual environment the necessary Flask packages that the project requires. You can then use Team Explorer to exclude the environment's folder from source control. In Solution Explorer, right-click the Python Environments node and select Add Virtual Environment. An Add Virtual Environment dialog appears, with a message saying We found a requirements.txt file. This message indicates that Visual Studio uses that file to configure the virtual environment. Select Create to accept the defaults. (You can change the name of the virtual environment if you want, which just changes the name of its subfolder, but envis a standard convention.) Consent to administrator privileges if prompted, then be patient for a few minutes while Visual Studio downloads and installs packages, which for Flask and its dependencies means expanding about a thousand files in over 100 subfolders. You can see progress in the Visual Studio Output window. While you're waiting, ponder the Question sections that follow. You can also see a description of Flask's dependencies on the Flask installation page (flask.pcocoo.org). On the Visual Studio Git controls (on the status bar), select the changes indicator (that shows 99*) which opens the Changes page in Team Explorer. Creating the virtual environment brought in hundreds of changes, but you don't need to include any of them in source control because you (or anyone else cloning the project) can always recreate the environment from requirements.txt. To exclude the virtual environment, right-click the env folder and select Ignore these local items. After excluding the virtual environment, the only remaining changes are to the project file and .gitignore. The .gitignore file contains an added entry for the virtual environment folder. You can double-click the file to see a diff. Enter a commit message and select the Commit All button, then push the commits to your remote repository if you like. Question: Why do I want to create a virtual environment? Answer: A virtual environment is a great way to isolate your app's exact dependencies. Such isolation avoids conflicts within a global Python environment, and aids both testing and collaboration. Over time, as you develop an app, you invariably bring in many helpful Python packages. By keeping packages in a project-specific virtual environment, you can easily update the project's requirements.txt file that describes that environment, which is included in source control. When the project is copied to any other computers, including build servers, deployment servers, and other development computers, it's easy to recreate the environment using only requirements.txt (which is why the environment doesn't need to be in source control). For more information, see Use virtual environments. Question: How do I remove a virtual environment that's already committed to source control? Answer: First, edit your .gitignore file to exclude the folder: find the section at the end with the comment # Python Tools for Visual Studio (PTVS) and add a new line for the virtual environment folder, such as /BasicProject/env. (Because Visual Studio doesn't show the file in Solution Explorer, open it directly using the File > Open > File menu command. You can also open the file from Team Explorer: on the Settings page, select Repository Settings, go to the Ignore & Attributes Files section, then select the Edit link next to .gitignore.) Second, open a command window, navigate to the folder like BasicProject that contains the virtual environment folder such as env, and run git rm -r env. Then commit those changes from the command line ( git commit -m 'Remove venv') or commit from the Changes page of Team Explorer. Step 1-4: Examine the boilerplate code Once project creation completes, you see the solution and project in Solution Explorer, where the project contains only two files, app.py and requirements.txt: As noted earlier, the requirements.txt file specifies the Flask package dependency. The presence of this file is what invites you to create a virtual environment when first creating the project. The single app.py file contains three parts. First is an importstatement for Flask, creating an instance of the Flaskclass, which is assigned to the variable app, and then assigning a wsgi_appvariable (which is useful when deploying to a web host, but not used at present): from flask import Flask app = Flask(__name__) # Make the WSGI interface available at the top level so wfastcgi can get it. wsgi_app = app.wsgi_app The second part, at the end of the file, is a bit of optional code that starts the Flask development server with specific host and port values taken from environment variables (defaulting to localhost:5555): if __name__ == '__main__': import os HOST = os.environ.get('SERVER_HOST', 'localhost') try: PORT = int(os.environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 app.run(HOST, PORT) Third is a short bit of code that assigns a function to a URL route, meaning that the function provides the resource identified by the URL. You define routes using Flask's @app.routedecorator, whose argument is the relative URL from the site root. As you can see in the code, the function here returns only a text string, which is enough for a browser to render. In the steps that follow you render richer pages with HTML. @app.route('/') def hello(): """Renders a sample page.""" return "Hello World!" Question: What is the purpose of the name argument to the Flask class? Answer: The argument is the name of the app's module or package, and tells Flask where to look for templates, static files, and other resources that belong to the app. For apps contained in a single module, __name__ is always the proper value. It's also important for extensions that need debugging information. For more information, and additional arguments, see the Flask class documentation (flask.pocoo.org). Question: Can a function have more than one route decorator? Answer: Yes, you can use as many decorators as you want if the same function serves multiple routes. For example, to use the hello function for both "/" and "/hello", use the following code: @app.route('/') @app.route('/hello') def hello(): """Renders a sample page.""" return "Hello World!" Question: How does Flask work with variable URL routes and query parameters? Answer: In a route, you mark any variable with <variable_name>, and Flask passes the variable to the function using a named argument in the URL path. For example, a route in the form of /hello/<name> generates a string argument called name to the function. Query parameters are available through the request.args property, specifically through the request.args.get method. For more information, see The Request object in the Flask documentation. # URL: /hello/<name>?message=Have%20a%20nice%20day @app.route('/hello/<name>') def hello(name): msg = request.args.get('message','') return "Hello " + name + "! "+ msg + "." To change the type, prefix the variable with int, float, path (which accepts slashes to delineate folder names), and uuid. For details, see Variable rules in the Flask documentation. Question: Can Visual Studio generate a requirements.txt file from a virtual environment after I install other packages? Answer: Yes. Expand the Python Environments node, right-click your virtual environment, and select the Generate requirements.txt command. It's good to use this command periodically as you modify the environment, and commit changes to requirements.txt to source control along with any other code changes that depend on that environment. If you set up continuous integration on a build server, you should generate the file and commit changes whenever you modify the environment. Step 1-5: Run the project In Visual Studio, select Debug > Start Debugging (F5) or use the Web Server button on the toolbar (the browser you see may vary): Either command assigns a random port number to the PORT environment variable, then runs python app.py. The code starts the app using that port within Flask's development server. If Visual Studio says Failed to start debugger with a message about having no startup file, right-click app.py in Solution Explorer and select Set as Startup File. When the server starts, you see a console window open that displays the server log. Visual Studio then automatically opens a browser to:<port>, where you should see the message rendered by the hellofunction: When you're done, stop the server by closing the console window, or by using the Debug > Stop Debugging command in Visual Studio. Question: What's the difference between using the Debug menu commands and the server commands on the project's Python submenu? Answer: In addition to the Debug menu commands and toolbar buttons, you can also launch the server using the Python > Run server or Python > Run debug server commands on the project's context menu. Both commands open a console window in which you see the local URL (localhost:port) for the running server. However, you must manually open a browser with that URL, and running the debug server does not automatically start the Visual Studio debugger. You can attach a debugger to the running process later, if you want, using the Debug > Attach to Process command. Next steps At this point, the basic Flask project contains the startup code and page code in the same file. It's best to separate these two concerns, and to also separate HTML and data by using templates. Go deeper - Flask Quickstart (flask.pocoo.org) - Tutorial source code on GitHub: Microsoft/python-sample-vs-learning-flask
https://docs.microsoft.com/en-us/visualstudio/python/learn-flask-visual-studio-step-01-project-solution?cid=kerryherger&view=vs-2019
CC-MAIN-2021-39
refinedweb
2,757
53.61
{-# LANGUAGE Rank2Types, ScopedTypeVariables, PatternSignatures, MultiParamTypeClasses, DeriveDataTypeable, GeneralizedNewtypeDeriving, TemplateHaskell, CPP #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns -fno-warn-name-shadowing #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Param.FSVec -- Copyright : (c) 2008 Alfonso Acosta, Oleg Kiselyov, Wolfgang Jeltsch -- and KTH's SAM group -- License : BSD-style (see the file LICENSE) -- -- Maintainer : alfonso.acosta@gmail.com -- Stability : experimental -- Portability : non-portable -- -- 'FSVec': Fixed sized vectors. Vectors with numerically parameterized size. -- -- Tutorial: <> ---------------------------------------------------------------------------- module Data.Param.FSVec (FSVec, empty, (+>), singleton, vectorCPS, vectorTH, #if __GLASGOW_HASKELL__ >= 609 v, #endif unsafeVector, reallyUnsafeVector, readFSVec, readFSVecCPS, length, genericLength, lengthT, fromVector, null, (!), replace, head, last, init, tail, take, drop, select, group, (<+), (++), map, zipWith, foldl, foldr, zip, unzip, shiftl, shiftr, rotl, rotr, concat, reverse, iterate, generate, copy ) where import Data.TypeLevel.Num hiding ((-),(+),(*),(>),(<),(>=),(<=),(==)) import Data.TypeLevel.Num.Aliases.TH (dec2TypeLevel) import Data.Generics (Data, Typeable) import qualified Prelude as P import Prelude hiding ( null, length, head, tail, last, init, take, drop, (++), map, foldl, foldr, zipWith, zip, unzip, concat, reverse, iterate) import qualified Data.Foldable as DF (Foldable, foldr) import qualified Data.Traversable as DT (Traversable(traverse)) import Language.Haskell.TH import Language.Haskell.TH.Syntax (Lift(..)) #if __GLASGOW_HASKELL__ >= 609 import Language.Haskell.TH.Quote #endif -- | Fixed-Sized Vector data type, indexed with type-level naturals, the -- first index for all vectors is 0 newtype Nat s => FSVec s a = FSVec {unFSVec :: [a]} deriving (Eq, Typeable, Data) instance Show a => Show (FSVec s a) where showsPrec _ = showV.unFSVec where showV [] = showString "<>" showV (x:xs) = showChar '<' . shows x . showl xs where showl [] = showChar '>' showl (x:xs) = showChar ',' . shows x . showl xs ------------------------- -- Constructing functions ------------------------- empty :: FSVec D0 a empty = FSVec [] -- | Cons operator, note it's not a constructor (+>) :: (Nat s, Pos s', Succ s s') => a -> FSVec s a -> FSVec s' a x +> (FSVec xs) = FSVec (x:xs) infixr 5 +> -- | A FSVec with a single element singleton :: a -> FSVec D1 a singleton x = x +> empty -- | Build a vector from a list (CPS style) vectorCPS :: [a] -> (forall s . Nat s => FSVec s a -> w) -> w vectorCPS xs = unsafeVectorCPS (P.length xs) xs -- | Build a vector from a list (using Template Haskell) vectorTH :: Lift a => [a] -> ExpQ vectorTH xs = (vectorCPS xs) lift #if __GLASGOW_HASKELL__ >= 609 -- | Vector quasiquoter v :: QuasiQuoter v = undefined -- v = QuasiQuoter (fst.parseFSVecExp) parseFSVecPat -- Build a vector using quasiquotation -- Not possible in the general case! It is feasible, though, when only -- allowing monomorphic vectors. For example, in the case of Ints: -- parseFSVecExp :: String -> ExpQ -- parseFSVecExp str = (readFSVec str) (lift :: Nat s => FSVec s Int -> ExpQ) parseFSVecExp :: forall a . String -> (ExpQ, a) parseFSVecExp str = ((readFSVec str) (lift :: (Nat s, Lift a) => FSVec s a -> ExpQ), undefined) -- Pattern match a vector using quasiquotation parseFSVecPat :: String -> PatQ parseFSVecPat = error "Data.Param.FSVec: quasiquoting paterns not supported" -- __GLASGOW_HASKELL__ #endif -- | Build a vector from a list (unsafe version: The static/dynamic size of -- the list is checked to match at runtime) unsafeVector :: Nat s => s -> [a] -> FSVec s a unsafeVector l xs | toNum l /= P.length xs = error (show 'unsafeVector P.++ ": dynamic/static length mismatch") | otherwise = FSVec xs -- | Build a vector from a list. -- -- Unlike unsafeVector, reallyunsafeVector doesn't have access to the -- static size of the list and thus cannot not check it against its -- dynamic size (which saves traversing the list at runtime to obtain -- the dynamic length). -- -- Therefore, reallyUnsafeVector (the name is that long on purspose) -- can be used to gain some performance but may break the consistency -- of the size parameter if not handled with care (i.e. the size -- parameter can nolonger be checked statically and the fullfilment of -- function constraints is left to the programmers judgement). -- -- Do not use reallyUnsafeVector unless you know what you're doing! reallyUnsafeVector :: [a] -> FSVec s a reallyUnsafeVector = FSVec -- | Read a vector (Note the the size of -- the vector string is checked to match the resulting type at runtime) readFSVec :: (Read a, Nat s) => String -> FSVec s a readFSVec = read instance (Read a, Nat s) => Read (FSVec s a) where readsPrec _ str | all fitsLength posibilities = P.map toReadS posibilities | otherwise = error (fName P.++ ": string/dynamic length mismatch") where",t) <- lexFSVec s] P.++ [(x:xs,1+n,u) | (x,t) <- reads s, (xs,n,u) <- readl' t] readl' s = [([],0,t) | (">",t) <- lexFSVec s] P.++ [(x:xs,1+n,v) | (",",t) <- lex s, (x,u) <- reads t, (xs,n,v) <- readl' u] readParen' b g = if b then mandatory else optional where optional r = g r P.++ mandatory r mandatory r = [(x,n,u) | ("(",s) <- lexFSVec r, (x,n,t) <- optional s, (")",u) <- lexFSVec t ] -- Custom lexer for FSVecs, we cannot use lex directly because it considers -- sequences of < and > as unique lexemes, and that breaks nested FSVecs, e.g. -- <<1,2><3,4>> lexFSVec :: ReadS String lexFSVec ('>':rest) = [(">",rest)] lexFSVec ('<':rest) = [("<",rest)] lexFSVec str = lex str
http://hackage.haskell.org/package/parameterized-data-0.1.3/docs/src/Data-Param-FSVec.html
CC-MAIN-2016-50
refinedweb
784
52.6
Created on 2014-12-07 15:24 by jcea, last changed 2015-08-07 15:50 by r.david.murray. This issue is now closed. mock_open(read_data=b'...') gives an error: """Traceback (most recent call last): File "z.py", line 6, in <module> print(f.read()) File "/usr/local/lib/python3.4/unittest/mock.py", line 896, in __call__ return _mock_self._mock_call(*args, **kwargs) File "/usr/local/lib/python3.4/unittest/mock.py", line 962, in _mock_call ret_val = effect(*args, **kwargs) File "/usr/local/lib/python3.4/unittest/mock.py", line 2279, in _read_side_effect return ''.join(_data) File "/usr/local/lib/python3.4/unittest/mock.py", line 2244, in _iterate_read_data data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')] """ Easy to reproduce: """ from unittest.mock import mock_open, patch m = mock_open(read_data= b'abc') with patch('__main__.open', m, create=True) : with open('abc', 'rb') as f : print(f.read()) """ Looks like this bug was introduced as result of issue #17467. I add those people to the nosy list. I've created a patch that fixes this, and added an accompanying unit test (which fails without the change). Thanks for the patch Aaron. Unfortunately this doesn't quite fix the issue. There are two problems with the patch: If a bytes object is passed into mock_open, I'd expect a bytes object in the output. In your patch, not only is this not the case (the output is a string object), but the bytes object is being coerced into its string representation in the resulting list. For example (simplified from your patch): >>> data = b'foo\nbar' >>> newline = b'\n' >>> >>> ['{}\n'.format(l) for l in data.split(newline)] ["b'foo'\n", "b'bar'\n"] What I would expect to see in this case is: [b'foo\n', b'bar\n'] > There are two problems with the patch That was intended to be removed after I changed the wording :P I've created a new patch, which addresses the problem. Your example now currently returns [b'foo\n', b'bar\n'] Thanks for the update, but this doesn't quite work either as you're assuming utf-8 (which is what .encode() and .decode() default to). For example, when using latin-1: >>> m = mock_open(read_data= b'\xc6') >>> with patch('__main__.open', m, create=True) : ... with open('abc', 'rb') as f : ... print(f.read()) ... Traceback (most recent call last): [snip] UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc6 in position 0: unexpected end of data Additionally, a bytes object may simply be binary data that doesn't adhere to any specific encoding. My suggestion is to remove the use of format() altogether as it's really not doing anything complex and simply append either '\n' or b'\n' depending on the type of object passed in. That way, you can deal with the type of object passed in directly without coercion. Thanks, I've fixed that. Not sure why I thought decoding and re-encoding would work with any binary data. I've also updated one of the tests to use non-utf8-decodeable binary data, to prevent a future regression. Thanks again for the update Aaron, I've left a couple small comments in Rietveld. Other than those, the patch looks good to me. Thanks for the contribution! I've fixed the issues you pointed out. Is there a better way than uploading a new patch file to make changes? Thanks for the updated patch, looks good to me. If you haven't already read it, the patch workflow is here: and is the only workflow currently available. I've fixed the formatting issues. A few more comments were left in Rietveld for you, likely hidden by spam filters. LGTM. New changeset 3d7adf5b3fb3 by Berker Peksag in branch '3.4': Issue #23004: mock_open() now reads binary data correctly when the type of read_data is bytes. New changeset 526a186de32d by Berker Peksag in branch '3.5': Issue #23004: mock_open() now reads binary data correctly when the type of read_data is bytes. New changeset ed15f399a292 by Berker Peksag in branch 'default': Issue #23004: mock_open() now reads binary data correctly when the type of read_data is bytes. Thanks for the patch, Aaron(also thanks to Demian for reviews). I've fixed the merge conflict and added more tests. Post merge review: looks like data_as_list = read_data.splitlines(True) would be a little cleaner. data_as_list = read_data.splitlines(True) is not actually the equivalent of data_as_list = [l + sep for l in read_data.split(sep)] It will change the behavior of the _iterate_read_data helper. See the comment at However, in default branch, we can simplify it to yield from read_data.splitlines(keepends=True) splitlines(keepends=True) is not ever equivalent to splitting by just '\n'. I don't know the details here, but switching to that would certainly be a behavior change. (Especially if the code path also applies to non-binary data!): >>> b'abc\nde\r\nf\x1dg'.splitlines(True) [b'abc\n', b'de\r\n', b'f\x1dg'] >>> 'abc\nde\r\nf\x1dg'.splitlines(True) ['abc\n', 'de\r\n', 'f\x1d', 'g']
https://bugs.python.org/issue23004
CC-MAIN-2020-16
refinedweb
849
60.01
I've got some Python code that farms out expensive jobs using ThreadPoolExecutor, and I'd like to keep track of which of them have completed so that if I have to restart this system, I don't have to redo the stuff that already finished. In a single-threaded context, I could just mark what I've done in a shelf. Here's a naive port of that idea to a multithreaded environment: from concurrent.futures import ThreadPoolExecutor import subprocess import shelve def do_thing(done, x): # Don't let the command run in the background; we want to be able to tell when it's done _ = subprocess.check_output(["some_expensive_command", x]) done[x] = True futs = [] with shelve.open("done") as done: with ThreadPoolExecutor(max_workers=18) as executor: for x in things_to_do: if done.get(x, False): continue futs.append(executor.submit(do_thing, done, x)) # Can't run `done[x] = True` here--have to wait until do_thing finishes for future in futs: future.result() # Don't want to wait until here to mark stuff done, as the whole system might be killed at some point # before we get through all of things_to_do done[x] = True future.add_done_callback While you're still in the outer-most with context manager, the done shelve is just a normal python object- it is only written to disk when the context manager closes and it runs its __exit__ method. It is therefore just as thread safe as any other python object, due to the GIL (as long as you're using CPython). Specifically, the reassignment done[x] = True is thread safe / will be done atomically. It's important to note that while the shelve's __exit__ method will run after a Ctrl-C, it won't if the python process ends abruptly, and the shelve won't be saved to disk. To protect against this kind of failure, I would suggest using a lightweight file-based thread safe database like sqllite3.
https://codedump.io/share/Dtw3V3WAQ8vl/1/light-persistence-in-the-context-of-threadpoolexecutor-in-python
CC-MAIN-2017-47
refinedweb
326
67.69
malware submission fails sometimeschipitsine Oct 7, 2015 2:59 AM Hello, sometimes malware submission fails with McAfee Labs - Beaverton Current Scan Engine Version:5700.7163 Current DAT Version:7946.0000 Thank you for your submission. Analysis ID: 9591037 File Name Findings Detection Type Extra --------------------|------------------------------|--------------------------- -|------------|----- 1eba.zip |extraction failure | | |no extraction failure [1eba.zip] ------------------------------------------------------------------ can you have a deeper look at it ? I attached both python script and failing malware sample to this message 1. Re: malware submission fails sometimesPeacekeeper Oct 7, 2015 3:02 AM (in response to chipitsine) First I have removed all samples forum rules ask that possible infected files are not posted here. when you zipped the file did you password protect it with password infected? I would retry the submission maybe use getsusp that is mentioned in the faq as long as you add your email details to its preferences that will submit the file as well. What To Do When McAfee Detects Software As An Infection - How to Submit To McAfee Labs & Appeal 2. Re: malware submission fails sometimeschipitsine Oct 7, 2015 3:07 AM (in response to Peacekeeper) I attached send.py script in order to describe how we send samples. it is not malware ok, I uploaded both python script and malware sample to Yandex.Disk, Yandex.Disk (password "test) have a look at send.py, is it ok ? be careful about included zip, it is malware. as we send sample from Cuckoo Sandbox, we need some automated way. what is appropriate ? however, we are not McAfee users, we are malware researchers, so we do not have access to McAfee web interface (and it is not good for python scripting) can you provide REST api for malware submission ? 3. Re: malware submission fails sometimeschipitsine Oct 7, 2015 3:12 AM (in response to Peacekeeper) here's send.py, is it ok ? #!/usr/bin/env python # coding=utf-8 from pyminizip import compress from email.header import Header from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate import smtplib from os.path import basename from sys import argv def sendMcAfee(filename, help_text, email): try: name = basename(filename) compress(filename, filename + ".zip", "infected", 5) filename += ".zip" name += ".zip" msg = MIMEMultipart( From=email, To="virus_research@mcafee.com", Subject="Potential virus", Date=formatdate(localtime=True) ) msg.attach(MIMEText(help_text)) with open(filename, 'rb') as archive: msg_attach = MIMEApplication( archive.read(), Name=name, ) msg_attach.add_header('Content-Disposition', 'attachment', filename=(Header(name, 'utf-8').encode())) msg.attach(msg_attach) smtp = smtplib.SMTP("smtp") smtp.sendmail(email, "virus_research@mcafee.com", msg.as_string()) smtp.close() return 0, "Success! %s" % name except Exception as e: print "MacAfee error: %s" % e return 1, "Something went wrong: %s" % e if __name__ == "__main__": if len(argv) < 2: print "Usage: %s <email> <file>" % argv[0] exit(1) print sendMcAfee(argv[2], "Wrong archive", argv[1]) 4. Re: malware submission fails sometimesPeacekeeper Oct 7, 2015 3:26 AM (in response to chipitsine) Sorry I am only a volunteer helper here cannot program. You can submit it to and link to the analysis results I can then point a lab tech to the analysis. Try resubmitting the file if if fails both zipping and using getsusp I have another way to do it but will have to talk via email. Best we try the other two options first All that said rereading you say the file is infected correct? 5. Re: malware submission fails sometimeschipitsine Oct 7, 2015 3:33 AM (in response to Peacekeeper) for instance, we got "Analysis ID: 9591037" for the failing malware sample. can you have a look at McAfee side ? I guess you can find answers regarding "was the archive protected with password infected" there, there's sample, right ? anything else ? 6. Re: malware submission fails sometimesPeacekeeper Oct 7, 2015 3:42 AM (in response to chipitsine) Well as I said I am a volunteer just a user of the software and note I have no Mcafee permissions. That said I can ask immediately will post back when I get an answer 7. Re: malware submission fails sometimeschipitsine Oct 7, 2015 3:45 AM (in response to Peacekeeper) I'm looking for an answer from McAfee, I'm not sure volunteer can help here. 8. Re: malware submission fails sometimesPeacekeeper Oct 7, 2015 3:50 AM (in response to chipitsine) Well I have emailed two McAfee lab techs who actually are the guys analyzing the false +ves so I will get an answer as soon as 1 arrives at work. 9. Re: malware submission fails sometimesdmeier Oct 9, 2015 8:26 AM (in response to chipitsine)1 of 1 people found this helpful The issue is likely caused by our side. We've had sporadic submission issues, that are being worked on. I don't think you need to adjust your submission process any. We do not have any REST API for you to submit through. - David
https://community.mcafee.com/message/394580
CC-MAIN-2018-05
refinedweb
826
65.62
Created on 2011-07-22 16:49 by VPeric, last changed 2019-03-15 23:53 by BreamoreBoy. The itertools fixer (izip -> zip, among others), fails for the following code: from itertools import izip print msg % str(bool(symbol_swapped) and list(izip(*swap_dict).next()) or symbols) It gets converted to: print(msg % str(bool(symbol_swapped) and list(next(izip(*swap_dict))) or symbols)) (note how izip is still there) I've worked aroudn this by introducing tmp = izip(...) and using that, but it'd be nice if 2to3 caught it by default. A smaller snippet to reproduce: izip().next() This gets converted to: next(izip()) It seems to me that the pattern of the itertools fixer doesn't match to izip().something(), and thus this is skipped. I see two problems that cause the posted test cases to fail: 1. The 'next' fixer runs before the 'itertools' fixer and strips out a 'power' node. This keeps the 'itertools' fixer from matching. 2. The 'itertools' fixer does not handle any 'trailer' nodes after the itertool function application it is transforming. I have fixed both of these issues in the attached patch. Full test suite run; no regressions. The patch is small and looks clean to me. Can someone take a look with a view to committing please, thanks.
https://bugs.python.org/issue12613
CC-MAIN-2020-40
refinedweb
216
75.3
Introduction Google Sheet is a very powerful tool in terms of collaboration, it allows multiple users to work on the same rows of data simultaneously. It also provides fine-grained APIs in various programming languages for your application to connect and interact with Google Sheet. Sometimes when you just need some simple operations like reading/writing data from a sheet, you may wonder if there is any higher level APIs that can complete these simple tasks easily. The short answer is yes. In this article, we will be discussing how can we read/write Google Sheet in 5 lines of Python code. Prerequisites As the prerequisite, you will need to have a Google service account in order for you to go through the Google cloud service authentication for your API calls. You can follow the guide from here for a free account setup. Once you have completed all the steps, you shall have a JSON file similar to below which contains your private key for accessing the Google cloud services. You may rename it to “client_secret.json” for our later use. { "type": "service_account", "project_id": "new_project", "private_key_id": "xxxxxxx", "private_key": "-----BEGIN PRIVATE KEY-----\xxxxx\n-----END PRIVATE KEY-----\n", "client_email": "[email protected]", "client_id": "xxx", "auth_uri": " "token_uri": " "auth_provider_x509_cert_url": " "client_x509_cert_url": " } From this JSON file, you can also find the email address for your newly created service account, if you need to access your existing Google Sheet files, you will need to grant access of your files to this email address. Note: There is a limit of 100 requests per every 100 seconds for the free Google service account, you may need to upgrade your account to the paid account if this free quota is not sufficient for your business. In addition to the service account, we need another two libraries google-auth and gspread which are the core modules to be used for authentication and manipulating the Google Sheet file. Below is the pip command to install the two libraries: pip install gspread pip install google-auth Lastly, let’s create a Google Sheet file namely “spreadsheet1” with some sample data from US 2020 election result: Once you have all above ready, let’s dive into our code examples. Read Google Sheet data into pandas Let’s first import the necessary libraries at the top of our script: import gspread from google.oauth2.service_account import Credentials import pandas as pd To get the access to Google Sheet, we will need to define the scope (API endpoint). For our case, we specify the scope to read and write the Google Sheet file. If you would like to restrict your program from updating any data, you can specify spreadsheets.readonly and drive.readonly in the scope. scope = [' ' And then we can build a Credentials object with our JSON file and the above defined scope: creds = Credentials.from_service_account_file("client_secret.json", scopes=scope) Next, we call the authorize function from gspread library to pass in our credentials: client = gspread.authorize(creds) With this one line of code, it will be going through the authentication under the hood. Once authentication passed, it establishes the connection between your application and the Google cloud service. From there, you can send request to open your spreadsheet file by specifying the file name: google_sh = client.open("spreadsheet1") Besides opening file by name, you can also use open_by_key with the sheet ID or open_by_url with the URL of the sheet. If the proper access has been given to your service account, you would be able to gain the control to your Google Sheet, and you can continue to request to open a particular spreadsheet tab. For instance, below returns the first sheet of the file: sheet1 = google_sh.get_worksheet(0) With the above, you can simply read all records into a dictionary with get_all_records function, and pass into a pandas DataFrame: df = pd.DataFrame(data=sheet1.get_all_records()) Now if you examine the df object, you shall see the below output: So that’s it! With a few lines of code, you’ve successfully downloaded your data from Google Sheet into pandas, and now you can do whatever you need in pandas. If you have duplicate column names in your Google Sheet, you may consider to use get_all_values function to get all the values into a list, so that duplicate column remains: df = pd.DataFrame(data=sheet1.get_all_values()) All the column and row labels will default to RangeIndex as per below: Now let’s take a further look at what else we can achieve with the this library. Add/Delete work sheets With gspread, you can easily add new sheets or duplicate from the existing sheets. Below is an example to create a new sheet namely “Sheet2” with max number of rows and columns specified. The index parameter tells Google Sheet where you want to insert your new sheet. index=0 indicates the new sheet to be inserted as the first sheet. sheet2 = google_sh.add_worksheet(title="Sheet2", rows="10", cols="10", index=0) Duplicating an existing sheet can be done by specifying the source sheet ID and the new sheet name: google_sh.duplicate_sheet(source_sheet_id=google_sh.worksheet("Sheet1").id, new_sheet_name="Votes Copy") Similarly, you can delete an existing sheet by passing in the worksheet object as per below: google_sh.del_worksheet(sheet2) If you would like to re-order your worksheets, you can do it with reorder_worksheets function. Assuming you want the sheet2 to be shown before sheet1: google_sh.reorder_worksheets([sheet2, sheet1]) Read/Write Google Sheet cells The worksheet object has the row_count and col_count properties which indicate the max rows and columns in the sheet file. But it’s not that useful when you want to know how many rows and columns of actual data you have: print(sheet1.row_count, sheet1.col_count) #1000, 26 To have a quick view of the number of rows and columns of your data, you can use: #Assuming the first row and first column have the full data print("no. of columns:", len(sheet1.row_values(1))) #no. of columns: 3 print("no. of rows:", len(sheet1.col_values(1))) #no. of rows: 8 To access the individual cells, you can either specify the row and column indexes, or use the A1 notation. For instance: #Access the row 1 and column 2 sheet1.cell(1, 2).value # or using A1 notation sheet1.acell('B1').value Note: the row/column index and A1 notation are all one-based numbers which is similar to the MS excel Similarly, you can update the value for each individual cell as per below: sheet1.update_cell(1, 2, "BIDEN VOTES") #or sheet1.update_acell("B1", "BIDEN VOTES") To update multiple cells, you shall use the worksheet update function with the list of cells and values to be updated. For instance, below code will replace the values in row 8: sheet1.update("A8:C8", [["Texas", 5261485, 5261485]]) Or use batch_update to update multiple ranges: sheet1.batch_update([{"range": "A8:C8", "values" : [["Texas", 5261485, 5261485]]}, {"range": "A9:C9", "values" : [["Wisconsin", 1630673, 1610065]]}, ]) or use append_rows to insert a row at the last row: sheet1.append_rows(values=[["Pennsylvania", 3458312, 3376499]]) Besides updating cell values, you can also update the cell format such as the font, background etc. For instance, the below will update the background of the 6th row to red color: sheet1.format("A6:C6", {"backgroundColor": { "red": 1.0, "green": 0.0, "blue": 0.0, "alpha": 1.0 } }) Note that Google is using RGBA color model, so the color values must be numbers between 0-1. Below is how it looks like in Google Sheet: Sometimes, it might be difficult to locate the exact index of the cell to be updated. You can find the cell by it’s text with the find function. It will return the first item from the matches. cell = sheet1.find("Michigan") print(cell.row, cell.col, cell.value) #6, 1, 'Michigan' You can also use Python regular express to find all matches. For instance, to find all cells with text ending as “da”: import re query = re.compile(".*da") cells = sheet1.findall(query) print(cells) #[<Cell R4C1 'Florida'>, <Cell R7C1 'Nevada'>] Add/Remove permission for your Google Sheet Adding or removing permission for a particular Google Sheet file can be also super easy with gspread. Before adding/removing permission, you shall check who are the users currently have access to your file. You can use list_permission function to retrieve the list of users with their roles: google_sh.list_permissions() To give access of your file to other users, you can use: #perm_type can be : user, group or domain #role can be : owner, writer or reader google_sh.share('[email protected]', perm_type='user', role='reader') When you check your file again, you shall see the email address you shared is added into the list of authorized users. To revert back the access for a particular user, you can use remove_permissions function. By default, it removes all the access that has been granted to the user: google_sh.remove_permissions('[email protected]', role="writer") When the role you’ve specifying does not match with the roles the user currently has, the function returns without doing anything. Conclusion Google Sheet API provides comprehensive interfaces for manipulating the sheets from the normal operations like reading/writing of the data, to validation, formatting, building pivot tables and charts etc. Often you find that you may just need some simple APIs to read and write Google Sheet files. In this article, we have reviewed though the gspread package which provides the high level APIs for working with Google Sheets to serve for this purpose. With gspread, you are able to open existing sheet or create new Google Sheet file, read/write the data as well as do simply formatting. In fact, there are a few other libraries such as gspread-formatting and gspread-pandas which offer extensive functionalities for sheet formatting and interacting sheets with pandas dataframe, you may take a look in case you need something more complicated than what we have covered here.
https://www.codeforests.com/category/automation/page/2/
CC-MAIN-2022-21
refinedweb
1,657
61.06
Sometimes we require to merge two lists that are sorted. This type of sorting is known as merge sorting. There are various ways to merge two sorted lists in python. In this entire tutorial, you will know how to merge two sorted lists in python with various examples. Methods to Merge two sorted lists in Python In this section, you will know all the methods you can use to merge two already sorted lists in python. Let’s know each of them. Method 1 : Using the sorted() function You can use the python inbuild function sorted() for sorting the two combine lists. Here you have to first append the list and then pass the combined list as an argument of the sorted() function. Execute the below lines of code and see the output. list1 = [1,2,3,4,5] list2= [10,20,30,40,50,60] print(sorted(list1 + list2)) Output Method 2: Using the heapq merge The second method to combine two already sorted lists is using the heapq module. It has a merge method that meger the lists in a sorted way. Just execute the below lines of code. from heapq import merge list1 = [1,2,3,4,5] list2= [10,20,30,40,50,60] print(list(merge(list1,list2))) Output Method 3: Merge two sorted lists using stack You can merge two sorted lists using a stack. In this method, you have to treat each sorted list as a stack. After that, continuously pop the smaller elements from the top of the stack and append the popped item to the list. It will continue to do so until the stack is empty. At last, the remaining elements of the list will be appended to the final list. Execute the below lines of code and see the output. list1 = [1,2,3,4,5] list2= [10,20,30,40,50,60] #Using stack sorted_list =[] while list1 and list2: if list1[0] < list2[0]: sorted_list.append(list1.pop(0)) else: sorted_list.append(list2.pop(0)) sorted_list += list1 sorted_list += list2 print(sorted_list) Output These are the methods to merge two sorted lists. You can use any one of them. I hope you have liked this tutorial. If you have any queries then you can contact us for more help. Join our list Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
https://www.datasciencelearner.com/merge-two-sorted-lists-python-methods/
CC-MAIN-2021-39
refinedweb
398
82.54
| My Account More Articles Excerpt from Professional ASP.NET 2.0 AJAX by Matt Gibbs AJAX development centers on using more JavaScript. With increased use of JavaScript comes the need for better ways to manage, reference, localize (that is, provide different script versions for specific language and culture combinations), and transmit script code to the client browser. The ASP.NET ScriptManager is at the center of ASP.NET AJAX functionality. The ScriptManager is the key component that coordinates the use of JavaScript for the Microsoft AJAX Library. Custom controls also use it to take advantage of script compression and reliable loading, as well as for automatic access to localized versions of scripts. A ScriptManager is required on every page that wants to use the AJAX Library. When the ScriptManager is included in the page, the AJAX Library scripts are rendered to the browser. This enables support for partial page rendering and use of the ASP.NET AJAX Client Library. Listing 1 (Bare.aspx) is a page with a barebones ScriptManager that does nothing more than render the Microsoft AJAX Library files to the browser Bare.aspx <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""><html xmlns=""> <head runat="server"> <title>ASP.NET AJAX ScriptManager</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager <div> </div> </form> </body> </html> Notice how the rendering changes when the ScriptManager is added to the page. You get five new script elements in the HTML sent to the browser. The following HTML is part of what is sent to the browser when Bare.aspx is requested. You can see that querystring parameters in the script references are long. They include time stamp elements and unique hash identifiers for script that is registered dynamically. If you copy the path from the src attribute of the script element and paste it into your browser's address bar, you will get the actual script resources returned from the server. src script <script type="text/javascript"> <!--(); } } // --> </script> <script src="/chapter05/WebResource.axd?d=6kIHBZsykATBSq3fbEmsYQ2&t= 632968784944906146"3RT853s6OS8dnx NpQibyXs1&t=633054056223442000"_clCUeTRolYBVlv TyhBCrs1&t=633054056223442000" type="text/javascript"></script> The first script is rendered inline in the HTML without a callback to the server. There is no src attribute on the script element. It is the method for initiating a postback. The second is a script reference for the approximately 500 lines of JavaScript included in most ASP.NET pages. It is the fundamental script providing some of the essential functionality of ASP.NET 2.0, including callbacks, performing validation, and managing focus. The next script reference is for the MicrosoftAjax Library. It is the same as the MicrosoftAjax.js file copied to the \Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\MicrosoftAjaxLibrary\System.Web.Extensions\1.0.61025 directory when installing ASP.NET AJAX. The code can be used with other server technologies, as it is focused on enriched client-side development. There are debug and release versions of the script files. The resources are also embedded in the System.Web.Extensions.dll and then extracted by the HTTP request to the ScriptResource.axd handler. This is the JavaScript that supports the client-side type system and Base Class Libraries as discussed Chapter 4, "Understanding the ASP.NET AJAX Client Library," of the book, Professional ASP.NET 2.0 AJAX (Wrox, 2007, ISBN: 978-0-470-10962-5). MicrosoftAjax.js \Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\MicrosoftAjaxLibrary\System.Web.Extensions\1.0.61025 ScriptResource.axd The third script reference is for the MicrosoftWebForms Library. This code is retrieved as a resource from the dll by default, but is also copied onto disk. These scripts provide support for the UpdatePanel and the lifecycle of events associated with using partial page rendering. The other two script entries are rendered inline in the page. You can see this in the following code, which is again part of the page output from requesting Bare.aspx from Listing 1. The first is for the PageRequestManager that handles partial page updates. The second piece of script performs the primary startup of the client page lifecycle by initializing the application object. PageRequestManager <script type="text/javascript"> //<![CDATA[ Sys.WebForms.PageRequestManager._initialize('ctl02', document.getElementById('form1')); Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90); //]]> </script> <script type="text/javascript"> <!-- Sys.Application.initialize(); // --> </script> You have seen that including the ScriptManager in the page results in rendering the scripts necessary to use the client-side Microsoft AJAX Library and to take advantage of partial page rendering as well. It also renders the scripts necessary for initiating the lifecycle of JavaScript events. The ScriptManager element can contain a scripts collection for adding scripts to the page. The way you would typically include a separate file of JavaScript in a page would be to use the HTML script element. You set the type attribute to "text/javascript" and the src attribute to the path of the JavaScript file, as shown in the following code. ScriptManager type "text/javascript" <script type="text/javascript" src="script.js"></script> Instead of writing the script element directly, the script can be added to the set of scripts that the ScriptManager controls using a ScriptReference element. By including it this way, I am assured that it will be loaded at a point when the ASP.NET AJAX Library is available. This is shown in Listing 2 (ScriptReference.aspx). ScriptReference ScriptReference.aspx < </Scripts> </asp:ScriptManager> <div> </div> </form> </body> </html> You would expect that requesting this page would result in the same output as running Bare.aspx from Listing 1 (with one additional script element), but this is not exactly the case. After the initial request for the page, everything appears to be the same, but during partial page updates when asynchronous updates are happening and scripts are being loaded, a JavaScript error is encountered, as shown in Figure 1. A call to Sys.Application.notifyScriptLoaded is required so that the ScriptManager can provide the client lifecycle reliably on various browsers. Not all browsers provide an event in their DOM for detecting this automatically. The script would actually run fine without it, but to ensure cross-browser support, the ScriptManager requires the call. Listing 3 (Sample.js) shows the recommended way of modifying scripts so that they can provide the required call to the Microsoft AJAX Library when it is present, and still function reliably when used separately. Sys.Application.notifyScriptLoaded Sample.js // filesystem based script resource function identityFunction(arg) { return arg; } if(typeof('Sys') !== 'undefined') Sys.Application.notifyScriptLoaded(); Rather than directly making the call, I first need to check that the Sys namespace is defined. The script can then be included in a page where the ASP.NET AJAX Library is not being used without causing an error. Sys The ScriptManager and ScriptReferences both allow you to set the ScriptMode. The default value of this enum is Auto. The other possible values are Release, Debug, and Inherit. The ScriptMode determines whether release or debug versions of the scripts are used. When set to Auto, the determination is primarily the result of server settings. Debug scripts are used when debug is set to true in the compilation section of the web.config file, or when the debug page directive is set to true. The deployment setting in the configuration file trumps all of the other settings. When retail is set to true, all other debug settings are treated as false and you won't get debug versions of the scripts. ScriptMode Auto Release Debug Inherit debug web.config retail ASP.NET AJAX includes release and debug versions of the scripts, but for ScriptReferences that refer to files on disk, the ScriptManager does not assume that you have provided debug versions of the script, so the path given is used regardless of the server's debug setting. The Auto setting for ScriptMode is almost identical to the Inherits value, except for this behavior. Inherits will take the value directly from the server configuration. The ScriptManager doesn't look to configuration or page settings when the ScriptMode is set directly to Release or Debug. Release The pattern you use to provide debug versions of scripts is to add .debug to the filename before the .js suffix. The name the ScriptManager would assume for the debug version of Sample.js would be Sample.debug.js. The filenames are not validated, so specifying the debug version of a script file that doesn't exist will result in an error like the one shown in Figure 2. Again, this error is only produced when script loading is validated during asynchronous postbacks, not during the initial loading of the page. .debug Sample.debug.js The choice of using .debug in the script name is arbitrary, but it does allow automation in finding the right version of scripts on disk, as well as when they are embedded as resources in a dll. You won't have to keep swapping files during development and deployment. You can set the debug mode you want and get the right version for the scripts you want to debug. For file-based script resources, you toggle between the release and debug versions by setting the ScriptMode attribute to Debug directly on the ScriptReference. There are some advantages to embedding JavaScript files as resources in a dll and deploying them that way. You don't have to wonder whether someone has modified the scripts on the server. You can maintain a set of release and debug scripts in a single location and use the ScriptManager to dynamically switch between versions. And once deployed, you have version information on the scripts, allowing for easier maintenance and servicing. One key difference exists in how the ScriptManager treats scripts retrieved from the filesystem compared with those embedded as a resource in a dll. When the path to a script is used, the ScriptManager provides a callback to the ScriptResource handler, which retrieves the contents. The script itself is not modified (no extra calls are injected). When a script is retrieved as an embedded resource, however, the ScriptManager injects the call to Sys.Application.notifyScriptLoaded for you automatically. This allows you to start using scripts that you already have with ASP.NET AJAX without having to rebuild the dlls. ScriptResource In Visual Studio, you first create a class library project. You can do this from your existing web application by right-clicking the Solution name in the Solution Explorer window. From the Add New Project dialog, you can add a new project by selecting the Class Library template (see Figure 3). Alternatively, you can choose to create a new Project from the File menu. In the dialog where you select the Class Library type you can also choose to add this project to the current Visual Studio Solution. You create the script files as you normally would, by adding JScript files to the project. Remember that using the naming convention of adding .debug into the filename for the debug version of a script alenables automatic switching between release and debug versions at runtime. To embed the scripts into the resulting dll, you set the Build Action in the Properties pane for the script file to Embedded Resource, as shown in Figure 4. In this example, I have added embeddedSample.js with a function called doubleArg that just returns double what it is passed. Listing 4 (embeddedSample.debug.js) includes some error checking. For some functions, you want to do parameter validation in release scripts, but for many situations, you just want the extra checks during development and testing. embeddedSample.js doubleArg embeddedSample.debug.js) function doubleArg(arg) { if(typeof(arg) === 'undefined') { throw Error.argumentUndefined('arg'); } if(arg === null) { throw Error.argumentNull('arg'); } if((arg % 0) === 0) { throw Error.argumentOutOfRange('arg', arg); } return 2*arg; } To be able to add a ScriptReference for the embeddedSample script, you need to define the WebResource for the project. The WebResource attribute is in the System.Web.UI namespace. The attribute is used in the code of your project to include the script into the compiled dll. The project needs a compile-time reference to the System.Web assembly to compile. Right-click the References entry of the Solution Explorer in Visual Studio and select Add Reference. Figure 5 shows the dialog where you can select System.Web. embeddedSample WebResource System.Web.UI System.Web The WebResource is added to the AssemblyInfo.cs file, which is in the Properties directory of the class library project. The WebResource attribute tells ASP.NET the names and types of resources available from assemblies in your web project. In this case, there are two resources, and both of them are JavaScript files to be embedded in the assembly. WebResource AssemblyInfo.cs [assembly: WebResource("MyScripts.embeddedSample.js", "text/javascript")] [assembly: WebResource("MyScripts.embeddedSample.debug.js", "text/javascript")] If you create the class library as a project within your web project in Visual Studio, you can modify the properties of the project to have the resource assembly copied into the bin directory of your web application. If it is a separate project, you will need to explicitly set the output location or copy the dll into your application manually. bin Now you have a dll with script resources embedded, and can include them in your page with a ScriptReference. Listing 5 (EmbeddedReference.aspx) is a page that includes the script and calls to the doubleArg function with valid and invalid parameters. EmbeddedReference.aspx doubleArg <%@ Page Language="C#" %> < </Scripts> </asp:ScriptManager> <div> </div> </form> </body> </html> <script type="text/javascript"> function pageLoad() { alert(doubleArg(3)); alert(doubleArg()); } </script> When debugging is not enabled for the page, the browser displays the number 6 and NaN. The second call to the function does not include an argument, and the release script just tries to double it and returns the "Not A Number" JavaScript value. When using the debug version of the script, however, you get the benefit of running the debug version of the script, and a better error message is displayed, explaining that the argument cannot be undefined. NaN You saw when using the path attribute of a ScriptReference to load a script from a file that the ScriptManager does not switch automatically between debug and release versions of the script. And when using the name and assembly attributes to specify loading of an embedded script, it will pick up the right version based on the server setting. If you do not provide a debug version of the script, the ScriptManager will notice this and fall back to the release version. It is not an error to skip inclusion of debug script resources. You can include all three attributes — name, assembly, and path — in a single ScriptReference element and get a slightly different behavior still. The path will be used to retrieve the script from disk, but the determination of whether or not a debug version of the script is available is made by looking at the embedded resources. If you have a debug embedded resource and choose to get the script from disk, it is an error to try and retrieve the debug version if it does not exist on disk. The ScriptManager will not fallback from the filesystem to the embedded resource. The .NET Framework has good support for providing and using localized resources in .NET applications. This is a feature that has been lacking in JavaScript. ASP.NET AJAX makes it possible to provide localized string resources and have the correct language used automatically at runtime. Script localization allows you to provide for specific translations of text for use in JavaScript in the browser. Script globalization is the ability to format and parse data using a specific culture. For example, it is customary in U.S. English for dates to be formatted as month, followed by the day and then the year (8/21/1993). But in many other cultures, the day of the month is presented first (21/8/1993). Both script localization and script globalization are discussed with examples in Chapter 5, "Using the ScriptManager," of the book, Professional ASP.NET 2.0 AJAX (Wrox, 2007, ISBN: 978-0-470-10962-5). This article is excerpted from Chapter, "Using the ScriptManager," of the book, Professional ASP.NET 2.0 AJAX (Wrox, 2007, ISBN: 978-0-470-10962-5) by Matt Gibbs and Dan Wahlin. Matt is currently the development manager of Microsoft's UI Framework and Services Team. This talented group is responsible for ASP.NET and the AJAX Framework as well as the new Integrated Pipeline of IIS 7. Matt has been working on Microsoft web technologies since joining the IIS 4 team to work on "classic"ASP in 1997. He has co-authored several books on ASP and ASP.NET.
http://www.wrox.com/WileyCDA/Section/id-305492.html
crawl-001
refinedweb
2,806
56.86
BassBoost bassBoost = new BassBoost( id ); // id here is the audioSessionId for the playing audio. bassBoost.setEnabled(true); bassBoost.setStrength(i); //i = intger value ranging from 0 to 1000 including the extremes ([0,1000]) . //All values less than 0 and greater than 1000 will be neglected bool b = await bassBoost.getEnabled();//b will get a boolean value in return. int strength = await bassBoost.getStrength();//strength will get an integer value in return. Updated the description of the plugin and also formatted bass_boost.dart => Only supported in android => Control bass of any audio playing in the device. Uses the BassBoost Class in AudioEffects package in android. example/README.md Demonstrates how to use the bass_boost: bass_boost: ^0.1.1 You can install packages from the command line: with Flutter: $ flutter pub get Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:bass_boost/bass_boost.dart'; We analyzed this package on Aug 16, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: Detected platforms: Flutter References Flutter, and has no conflicting libraries.
https://pub.dev/packages/bass_boost
CC-MAIN-2019-35
refinedweb
193
51.14
pipe - Create an interprocess channel #include <unistd.h> int pipe( int filedes[2] ); Interfaces documented on this reference page conform to industry standards as follows: pipe(): XSH4.0, XSH4.2, XSH5.0 Refer to the standards(5) reference page for more information about industry standards and associated tags. Specifies the address of an array of two integers into which the new file descriptors are placed. The pipe() function creates a unidirectional interprocess channel called a pipe, and returns two file descriptors, filedes[0] and filedes[1]. The file descriptor specified by the filedes[0] parameter is opened for reading and the file descriptor specified by the filedes[1] parameter is opened for writing. Their integer values will be the two lowest available at the time of the call to the pipe() function. A process has the pipe open for reading if it has a file descriptor open that refers to the read end, filedes[0]. A process has the pipe open for writing if it has a file descriptor open that refers to the write end, filedes[1]. A read operation on file descriptor filedes[0] accesses the data written to filedes[1] on a first-in, first-out (FIFO) basis. Note In the System V compatiblity environment, filedes[0] and filedes[1] are STREAMS based and are bidirectional. Data written on filedes[0] appears on filedes[1] and vice versa. Data is read in a first-in, first-out (FIFO) basis. The O_NONBLOCK and the FD_CLOEXC flags are set clear on both file descriptors. (The fcntl() function can be used to set the O_NONBLOCK flag.) Upon successful completion, the pipe() function marks the st_atime, st_ctime and st_mtime fields of the pipe for update. [Tru64 UNIX] When a read() or write() system call on a pipe is interrupted by a signal and no bytes have been transferred through the pipe, the read() or write() system call returns a -1 and errno is set to [EINTR]. This behavior differs from behavior in early releases of the operating system, when both system calls either restarted the transfer or caused errno to be set to [EINTR], depending on the setting of the SA_RESTART flag for the interrupting signal. [Tru64 UNIX] As a result of this change, applications must now either handle the [EINTR] return or block any expected signals for the duration of the read or write operation. [Tru64 UNIX] When compiled in the X/Open UNIX environment, calls to the pipe() function are internally renamed by prepending _E to the function name. When you are debugging a module that includes the pipe() function and for which _XOPEN_SOURCE_EXTENDED has been defined, use _Epipe to refer to the pipe() call. See standards(5) for further information. Upon successful completion, a value of 0 (zero) is returned. If the pipe() function fails, a value of -1 is returned and errno is set to indicate the error. If the pipe() function fails, errno may be set to one of the following values: [Tru64 UNIX] The filedes parameter is an invalid address. [Tru64 UNIX] A read() or a write() call on a pipe is interrupted by a signal and no bytes have been transferred through the pipe. More than OPEN_MAX-2 file descriptors are already opened by this process. [Tru64 UNIX] More than getdtablesize(2) file descriptors are already opened by this process. The system file table is full, or the device containing pipes has no free i-nodes. [Tru64 UNIX] The system was unable to allocate kernel memory for more file descriptors. Commands: sh(1) Functions: fcntl(2), getmsg(2), getdtablesize(2), poll(2), putmsg(2), read(2), select(2), write(2) Standards: standards(5) pipe(2)
http://nixdoc.net/man-pages/Tru64/man2/pipe.2.html
CC-MAIN-2020-10
refinedweb
611
61.16
On Mon, Apr 2, 2012 at 12:08 AM, Graham Dumpleton <graham.dumpleton at gmail.com> wrote: > > When using CGI or FASTCGI, with a hosting system where an executable > script needs to be supplied, it is beneficial to be able to say > something like: > > #!/usr/bin/env python -m cgi2wsgi > > #!/usr/bin/env python -m fcgi2wsgi > > where the rest of the script is the just the WSGI application. > > I have implemented this for CGI as an example at: > > > > I have done it for FASTCGI using flup as well before but that isn't > available anywhere. That's a clever trick for CGI and a great reason to +x a script, since it's so helpful to people who need to deploy against CGI for any reason, but don't want to couple to CGI in the long run. I wouldn't personally use hashbangs with wsgiref because if I can run a Python interpreter, I have equal access to excellent pure-Python servers which are - not to slight wsgiref - miles ahead (e.g. concurrent requests, easy config, reloading). And it's not unlikely that I can just deploy locally on the same server I use in production. The use case I can imagine, if stdlib acquired a good server, is that someone writes the next Jenkins and wants to let *nix users check it out real quick by just running a script. But that case is already completely handled with a __name__ == __main__ clause at the bottom, which is also portable. > You don't see such niceties for Python where a system > admin sets up that a .wsgi script file would be understood to be a > Python WSGI application with no extra magic needing to be added to it > by the user, even though not that difficult in principle. That's a very appealing idea... Is anything really necessary besides a convention for finding a single WSGI application callable in a given directory? (i.e.: to do the job of e.g. the WSGIScriptAlias directive, only inside a directory.) To flesh out how easy this could be: * could have __init__.py put a WSGI callable called 'application' in its namespace. * Or if that is too inefficient for servers to discover, it might be done in __main__.py (still retrievable using `from foo.__main__ import application` - though maybe this is an abuse of the purpose of __main__.py since we are not running a process so much as importing just to get a Python object which doesn't know if it will be run with threads, processes, greenlets, etc.) * Or if we want to avoid spuriously running __main__.py (e.g. what if it runs a blocking process) then just pick a specially named Python file. __wsgi__.py or some such. * Or if importing things to yield the application is a concern, a text file like 'web.txt' which simply reads 'foo.app' or even 'foo:app' to point to the object named app inside foo.py. Then the server loads however it wants to. If people just agreed arbitrarily on (say) "__wsgi__.py" and "application" it would work as soon as implemented (pretty easy). What have I missed?
http://mail.python.org/pipermail/web-sig/2012-April/005158.html
CC-MAIN-2013-20
refinedweb
528
73.58
History | View | Annotate | Download (16.5 * <>. */ #ifndef FatStructs_h #define FatStructs_h /** * \file * FAT file structures /* * mostly from Microsoft document fatgen103.doc * //------------------------------------------------------------------------------ /** Value for byte 510 of boot block or MBR */ uint8_t const BOOTSIG0 = 0X55; /** Value for byte 511 of boot block or MBR */ uint8_t const BOOTSIG1 = 0XAA; * \struct partitionTable * \brief MBR partition table entry * A partition table entry for a MBR formatted storage device. * The MBR partition table has four entries. struct partitionTable { /** * Boot Indicator . Indicates whether the volume is the active * partition. Legal values include: 0X00. Do not use for booting. * 0X80 Active partition. */ uint8_t boot; * Head part of Cylinder-head-sector address of the first block in * the partition. Legal values are 0-255. Only used in old PC BIOS. */ uint8_t beginHead; * Sector part of Cylinder-head-sector address of the first block in * the partition. Legal values are 1-63. Only used in old PC BIOS. unsigned beginSector : 6; /** High bits cylinder for first block in partition. */ unsigned beginCylinderHigh : 2; * Combine beginCylinderLow with beginCylinderHigh. Legal values * are 0-1023. Only used in old PC BIOS. uint8_t beginCylinderLow; * Partition type. See defines that begin with PART_TYPE_ for * some Microsoft partition types. uint8_t type; * head part of cylinder-head-sector address of the last sector in the * partition. Legal values are 0-255. Only used in old PC BIOS. uint8_t endHead; * Sector part of cylinder-head-sector address of the last sector in * the partition. Legal values are 1-63. Only used in old PC BIOS. unsigned endSector : 6; /** High bits of end cylinder */ unsigned endCylinderHigh : 2; * Combine endCylinderLow with endCylinderHigh. Legal values uint8_t endCylinderLow; /** Logical block address of the first block in the partition. */ uint32_t firstSector; /** Length of the partition, in blocks. */ uint32_t totalSectors; }; /** Type name for partitionTable */ typedef struct partitionTable part_t; * \struct masterBootRecord * \brief Master Boot Record * The first block of a storage device that is formatted with a MBR. struct masterBootRecord { /** Code Area for master boot program. */ uint8_t codeArea[440]; /** Optional WindowsNT disk signature. May contain more; /** Type name for masterBootRecord */ typedef struct masterBootRecord mbr_t; /** * \struct biosParmBlock * \brief BIOS parameter block * * The BIOS parameter block describes the physical layout of a FAT volume. struct biosParmBlock { * Count of bytes per sector. This value may take on only the * following values: 512, 1024, 2048 or 4096 uint16_t bytesPerSector; * Number of sectors per allocation unit. This value must be a * power of 2 that is greater than 0. The legal values are * 1, 2, 4, 8, 16, 32, 64, and 128. uint8_t sectorsPerCluster; * Number of sectors before the first FAT. * This value must not be zero. uint16_t reservedSectorCount; /** The count of FAT data structures on the volume. This field should * always contain the value 2 for any FAT volume of any type. uint8_t fatCount; * For FAT12 and FAT16 volumes, this field contains the count of * 32-byte directory entries in the root directory. For FAT32 volumes, * this field must be set to 0. For FAT12 and FAT16 volumes, this * value should always specify a count that when multiplied by 32 * results in a multiple of bytesPerSector. FAT16 volumes should * use the value 512. */ uint16_t rootDirEntryCount; * This field is the old 16-bit total count of sectors on the volume. * This count includes the count of all sectors in all four regions * of the volume. This field can be 0; if it is 0, then totalSectors32 * must be non-zero. For FAT32 volumes, this field must be 0. For * FAT12 and FAT16 volumes, this field contains the sector count, and * totalSectors32 is 0 if the total sector count fits * (is less than 0x10000). uint16_t totalSectors16; * This dates back to the old MS-DOS 1.x media determination and is * no longer usually used for anything. 0xF8 is the standard value * for fixed (non-removable) media. For removable media, 0xF0 is * frequently used. Legal values are 0xF0 or 0xF8-0xFF. uint8_t mediaType; * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. * On FAT32 volumes this field must be 0, and sectorsPerFat32 * contains the FAT size count. uint16_t sectorsPerFat16; /** Sectors per track for interrupt 0x13. Not used otherwise. */ uint16_t sectorsPerTrtack; /** Number of heads for interrupt 0x13. Not used otherwise. */ uint16_t headCount; * Count of hidden sectors preceding the partition that contains this * FAT volume. This field is generally only relevant for media * visible on interrupt 0x13. uint32_t hidddenSectors; * This field is the new 32-bit total count of sectors on the volume. * of the volume. This field can be 0; if it is 0, then * totalSectors16 must be non-zero. uint32_t totalSectors32; * Count of sectors occupied by one FAT on FAT32 volumes. uint32_t sectorsPerFat32; * This field is only defined for FAT32 media and does not exist on * FAT12 and FAT16 media. * Bits 0-3 -- Zero-based number of active FAT. * Only valid if mirroring is disabled. * Bits 4-6 -- Reserved. * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. * -- 1 means only one FAT is active; it is the one referenced in bits 0-3. * Bits 8-15 -- Reserved. uint16_t fat32Flags; * FAT32 version. High byte is major revision number. * Low byte is minor revision number. Only 0.0 define. uint16_t fat32Version; * Cluster number of the first cluster of the root directory for FAT32. * This usually 2 but not required to be 2. uint32_t fat32RootCluster; * Sector number of FSINFO structure in the reserved area of the * FAT32 volume. Usually 1. uint16_t fat32FSInfo; * If non-zero, indicates the sector number in the reserved area * of the volume of a copy of the boot record. Usually 6. * No value other than 6 is recommended. uint16_t fat32BackBootBlock; * Reserved for future expansion. Code that formats FAT32 volumes * should always set all of the bytes of this field to 0. uint8_t fat32Reserved[12]; /** Type name for biosParmBlock */ typedef struct biosParmBlock bpb_t; * \struct fat32BootSector * \brief Boot sector for a FAT16 or FAT32 volume. */ struct fat32BootSector { /** X86 jmp to boot program */ uint8_t jmpToBootCode[3]; /** informational only - don't depend on it */ char oemName[8]; /** BIOS Parameter Block */ bpb_t bpb; /** for int0x13 use value 0X80 for hard drive */ uint8_t driveNumber; /** used by Windows NT - should be zero for FAT */ uint8_t reserved1; /** 0X29 if next three fields are valid */ uint8_t bootSignature; /** usually generated by combining date and time */ uint32_t volumeSerialNumber; /** should match volume label in root dir */ char volumeLabel[11]; char fileSystemType[8]; /** X86 boot code */ uint8_t bootCode[420]; /** must be 0X55 */ uint8_t bootSectorSig0; /** must be 0XAA */ uint8_t bootSectorSig1; // End Of Chain values for FAT entries /** FAT16 end of chain value used by Microsoft. */ uint16_t const FAT16EOC = 0XFFFF; /** Minimum value for FAT16 EOC. Use to test for EOC. */ uint16_t const FAT16EOC_MIN = 0XFFF8; /** FAT32 end of chain value used by Microsoft. */ uint32_t const FAT32EOC = 0X0FFFFFFF; /** Minimum value for FAT32 EOC. Use to test for EOC. */ uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; /** Mask a for FAT32 entry. Entries are 28 bits. */ uint32_t const FAT32MASK = 0X0FFFFFFF; /** Type name for fat32BootSector */ typedef struct fat32BootSector fbs_t; * \struct directoryEntry * \brief FAT short directory entry * Short means short 8.3 name, not the entry size. * * 9-15: Count of years from 1980, valid value range 0-127 * inclusive (1980-2107). * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. * Bits 0-4: Day of month, valid value range 1-31 inclusive. * Time Format. A FAT directory entry time stamp is a 16-bit field that has * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the * 16-bit word, bit 15 is the MSB of the 16-bit word). * Bits 11-15: Hours, valid value range 0-23 inclusive. * Bits 5-10: Minutes, valid value range 0-59 inclusive. * * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). * The valid time range is from Midnight 00:00:00 to 23:59:58. struct directoryEntry { /** * Short 8.3 name. * The first eight bytes contain the file name with blank fill. * The last three bytes contain the file extension with blank fill. uint8_t name[11]; /** Entry attributes. * * The upper two bits of the attribute byte are reserved and should * always be set to 0 when a file is created and never modified or * looked at after that. See defines that begin with DIR_ATT_. uint8_t attributes; * Reserved for use by Windows NT. Set value to 0 when a file is * created and never modify or look at it after that. uint8_t reservedNT; * The granularity of the seconds part of creationTime is 2 seconds * so this field is a count of tenths of a second and its valid * value range is 0-199 inclusive. (WHG note - seems to be hundredths) uint8_t creationTimeTenths; /** Time file was created. */ uint16_t creationTime; /** Date file was created. */ uint16_t creationDate; * Last access date. Note that there is no last access time, only * a date. This is the date of last read or write. In the case of * a write, this should be set to the same date as lastWriteDate. uint16_t lastAccessDate; * High word of this entry's first cluster number (always 0 for a * FAT12 or FAT16 volume). uint16_t firstClusterHigh; /** Time of last write. File creation is considered a write. */ uint16_t lastWriteTime; /** Date of last write. File creation is considered a write. */ uint16_t lastWriteDate; /** Low word of this entry's first cluster number. */ uint16_t firstClusterLow; /** 32-bit unsigned holding this file's size in bytes. */ uint32_t fileSize; // Definitions for directory entries // /** Type name for directoryEntry */ typedef struct directoryEntry dir_t; /** escape for name[0] = 0XE5 */ uint8_t const DIR_NAME_0XE5 = 0X05; /** name[0] value for entry that is free after being "deleted" */ uint8_t const DIR_NAME_DELETED = 0XE5; /** name[0] value for entry that is free and no allocated entries follow */ uint8_t const DIR_NAME_FREE = 0X00; /** file is read-only */ uint8_t const DIR_ATT_READ_ONLY = 0X01; /** File should hidden in directory listings */ uint8_t const DIR_ATT_HIDDEN = 0X02; /** Entry is for a system file */ uint8_t const DIR_ATT_SYSTEM = 0X04; /** Directory entry contains the volume label */ uint8_t const DIR_ATT_VOLUME_ID = 0X08; /** Entry is for a directory */ uint8_t const DIR_ATT_DIRECTORY = 0X10; /** Old DOS archive bit for backup support */ uint8_t const DIR_ATT_ARCHIVE = 0X20; /** Test value for long name entry. Test is (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ uint8_t const DIR_ATT_LONG_NAME = 0X0F; /** Test mask for long name entry */ uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; /** defined attribute bits */ uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; /** Directory entry is part of a long name */ static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; } /** Mask for file/subdirectory tests */ uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); /** Directory entry is for a file */ static inline uint8_t DIR_IS_FILE(const dir_t* dir) { return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; /** Directory entry is for a subdirectory */ static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; /** Directory entry is for a file or subdirectory */ static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; #endif // FatStructs_h
https://roboticsclub.org/redmine/projects/quadrotor/repository/revisions/58d82c77908eee0e1c222f7b38691e6532deb77b/entry/arduino-1.0/libraries/SD/utility/FatStructs.h
CC-MAIN-2016-50
refinedweb
1,779
58.28
Now that it is needed since web2py exports already in CSV but you can do define def export_xml(rows): idx=range(len(rows.colnames)) colnames=[item.replace('.','_') for item in rows.colnames] records=[] for row in rows.response: records.append(TAG['record'](*[TAG[colnames[i]](row[i]) for i in idx])) return str(TAG['records'](*records)) Now if you have a model like db=SQLDB('sqlite://test.db') db.define_table('mytable',SQLField('myfield')) for i in range(100): db.mytable.insert(myfield=i) you can get your data in XML by doing print export_xml(db().select(db.mytable.ALL)) Notice that TAG.name('a','b',c='d') and TAG['name']('a','b',c='d') both generate the following XML <name c="d">ab</name> where 'a' and 'b' and 'd' are escaped as appropriate. Using TAG you can can generate any HTML/XML tag you need and is not already provided in the API. TAGs can be nested and are serialized with str()
http://www.web2py.com/AlterEgo/default/show/74
CC-MAIN-2016-30
refinedweb
164
51.75
Docs | Forums | Lists | Bugs | Planet | Store | GMN | Get Gentoo! Not eligible to see or edit group visibility for this bug. View Bug Activity | Format For Printing | XML | Clone This Bug configure output contains: checking for Kerberos (/usr/kerberos)... checking for AFS (/usr/afsws)... checking for afs/kauth.h... no checking for afs/kautils.h... no checking for afs/auth.h... no no Judging from your configure output, you have the /usr/afsws directory in place, and do not have /usr/include/afs/{kauth.h,kautils.h,auth.h}. On my system, I get: checking for Kerberos (/usr/kerberos)... checking for AFS (/usr/afsws)... checking for afs/kauth.h... yes checking for afs/kautils.h... yes checking for afs/auth.h... yes yes I think: - it compiles without AFS-support on installations with old (non-FHS-compliant) openafs installations - it compiles with AFS-support whenever someone with a new (FHS-compliant) openafs installation also creates the directory /usr/afsws (hence the output above). Suggestion: remove this check - the ebuild itself is currently totally AFS-unaware No, I do have /usr/afsws as it contains the binaries I use to distribute within the cell. I just wanted to make you aware of yet another dependency on afs. But am in contact with developers of mpich and mpich2 and some fixes will appear shortly. anyway, this I get with mpich-1.2.7: configure:1423: checking for Kerberos (/usr/kerberos) configure:1495: checking for AFS (/usr/afsws) configure:1503: checking for afs/kauth.h configure:1513: icc -E conftest.c >/dev/null 2>conftest.out configure(1509): catastrophic error: could not open source file "afs/kauth.h" #include <afs/kauth.h> ^ configure: failed program was: #line 1508 "configure" #include "confdefs.h" #include <afs/kauth.h> configure:1537: checking for afs/kautils.h configure:1547: icc -E conftest.c >/dev/null 2>conftest.out configure(1543): catastrophic error: could not open source file "afs/kautils.h" #include <afs/kautils.h> ^ configure: failed program was: #line 1542 "configure" #include "confdefs.h" #include <afs/kautils.h> configure:1571: checking for afs/auth.h configure:1581: icc -E conftest.c >/dev/null 2>conftest.out configure(1577): catastrophic error: could not open source file "afs/auth.h" #include <afs/auth.h> ^ configure: failed program was: #line 1576 "configure" #include "confdefs.h" #include <afs/auth.h> It's clear that I have to pass -I/usr/afsws/include in CPPFLAGS. ;) Come on. We're talking Gentoo here. You know perfectly well that Gentoo chooses to put OpenAFS in FHS locations. Therefore the only thing that needs to be adapted to get this thing working properly, is to remove the requirement that /usr/afsws exists, just as I said in my previous comment. Yes, I did test this myself. You can pass all the -I/usr/afsws/include in CPPFLAGS that you want on your own system, but please, your last remark is just here to confuse any developer that would need to check up on this later. So now to get this straight: when using one of the newer openafs ebuilds (>=1.2.13) that will be promoted to stable, the include files required will be in /usr/include/afs/... The checking for /usr/afsws is for Transarc-paths, which aren't used on Gentoo and will therefore not be found, thus this check should be omitted if AFS-support is wanted. So follow-up for comment #3: yes, so someone has to patch configure so it finds the headers in FHS. ;-) Fixed in CVS, sorry for the delay.
http://bugs.gentoo.org/103430
crawl-002
refinedweb
591
61.63
20 March 2012 04:12 [Source: ICIS news] By Clive Ong SINGAPORE (ICIS)--Asian acrylonitrile-butadiene-styrene (ABS) prices are under downward pressure this week as traders seeking to lock in profits have started to sell low-priced parcels, market source said on Tuesday. Spot deals were heard at $2,100-2,200/tonne (€1,596-1,672/tonne) CFR (cost and freight) China and Hong Kong, much lower than suppliers’ offers at $2,190-2,270/tonne CFR China and Hong Kong, they said. “The lower priced parcels are mainly from traders, while producers are mostly holding on to their higher offers,” said a Hong Kong-based trader. While values of ABS feedstocks butadiene (BD) and styrene (SM) have declined in recent weeks, ABS makers still deem the prices quite high. BD spot prices fell by about 13% from mid-February to $3,425/tonne in the week ended 16 March. SM prices, on the other hand, stood at an average of $1,467.50/tonne on 19 March, down by 2.2% over the past week, ICIS data showed. “Margins are still thin with ABS prices and feedstock prices at current levels,” said a Taiwanese producer. Suppliers in Hong Kong and ?xml:namespace> “Orders for finished products are starting to trickle in and demand for ABS will likely improve in April,” said another dealer in Factories in But economic conditions in Europe and the “The weak eurozone will continue to dampen exports from ABS is used in making toys, consumer electronics, office equipment and has applications in the construction sector. (
http://www.icis.com/Articles/2012/03/20/9543005/Asia-ABS-under-pressure-as-traders-sell-low-priced-parcels.html
CC-MAIN-2015-18
refinedweb
262
66.57
PowerS: Basic terminology. Why new Cmdlets. – Cons: Use of non-standard DCOM protocol. Does not work for non-Windows. WinRM Cmdlets – Pros: Works with Windows and non-Windows using standard protocol. –”. Key goals for new CIM. Goal 1 – Rich PowerShell experience 1. Discovery of classes and namespaces. -. 3. Working with associations. The table below shows the list of WMI cmdlets and their CIM equivalent:. The rule here is, if the WMI cmdlet experience is not ideal, we don’t want to carry it forward. It’s better to break a bad experience (like in the example given above) Goal 2 – Standard Compliance): Goal 3 – Support for down-level OS or non-windows machines Here is an off the wall comment, does the New-CimSession work under a PowerShell WorkFlow? RT @Gyz. You would need a CIMOM like OMI or Open Pegasus on Linux + providers for the entities you want to manage. Osama Sajid. Program Manager. WMI! And yet the bug to link to on Connect is still marked as Active and Microsoft has not even responded to it. Bad. Thank you so much for this! "CIM" vs "WMI" is a mystery several will struggle with, but the fog will clear eventually. Wow, great stuff you guys did. Looking forwward to manage my hetergenous environment this way. Do you know what goodies are needed on a linux box to be managed via CIM in PS? Many thanks What version of Intel AMT can be managed with new CIM Cmdlets? Other than Intel AMT (and Open MI) what other WsMan implementations have been tested with these Cmdlets?
https://blogs.msdn.microsoft.com/powershell/2012/08/24/introduction-to-cim-cmdlets/
CC-MAIN-2017-17
refinedweb
265
76.01
Scrapy Beginners Series Part 3: Storing Data With Scrapy In Part 1 and Part 2 of this Python Scrapy 5-Part Beginner Series we learned how to build a basic scrapy spider and get it to scrape some data from a website as well as how to clean up data as it was being scraped. In Part 3 we will be exploring how to save the data into files/formats which would work for most common use cases. We'll be looking at how to save the data to a CSV or JSON file as well as how to save the data to a database or S3 bucket.. (This Tutorial)! In this tutorial, Part 3: Storing Data With Scrapy we're going to cover: - Using Feed Exporters - Saving Data to a JSON or CSV file - Saving Data to Amazon S3 Storage - Saving Data to a Database With the intro out of the way let's get down to business. Need help scraping the web? Then check out ScrapeOps, the complete toolkit for web scraping. Using Feed Exporters Scrapy already has a way to save the data to several different formats. Scrapy call's these ready to go export methods Feed Exporters. Out of the box scrapy provides the following formats to save/export the scraped data: - JSON file format - CVS file format - XML file format - Pythons pickle format The files which are generated can then be saved to the following places using a Feed Exporter: - The machine Scrapy is running on (obviously) - To a remote machine using FTP (file transfer protocall) - To Amazon S3 Storage - To Google Cloud Storage - Standard output In this guide we're going to give examples on how your can use Feed Exporters to store your data in different file formats and locations. However, there are many more ways you can store data with Scrapy. Saving Data to a JSON or CSV File We've already quickly looked at how to export the data to JSON and CSV in part one of this series but we'll quickly go over how to store the data to a JSON file and a CSV file one more time. Feel free to skip ahead if you know how to do this already! To get the data to be saved in the most simple way for a once off job we can use the following commands: Saving in JSON format To save to a JSON file simply add the flag -o to the scrapy crawl command along with the file path you want to save the file to: scrapy crawl chocolatespider -o my_scraped_chocolate_data.json You can also define an absolute path like this: scrapy crawl chocolatespider -O Saving in CSV format To save to a CSV file add the flag -o to the scrapy crawl command along with the file path you want to save the file to: scrapy crawl chocolatespider -o my_scraped_chocolate_data.csv You can also define an absolute path like this: scrapy crawl chocolatespider -O You can also decide whether to overwrite or append the data to the output file. For example, when using the crawl or runspider commands, you can use the -O option instead of -o to overwrite the output file. (Be sure to remember the difference as this might be confusing!) Saving Data to Amazon S3 Storage Now that we have saved the data to a CSV file, lets save the created CSV files straight to an Amazon S3 bucket (You need to already have one setup). You can check out how to set up an S3 bucket with amazon here: OK- First we need to install Botocore which is an external Python library created by Amazon to help with connecting to S3. pip3 install botocore Now that we have that installed we can save the file to S3 by specifying the URI to your Amazon S3 bucket: scrapy crawl chocolatespider -O s3://aws_key:aws_secret@mybucket/path/to/myscrapeddata.csv:csv Obviously you will need to replace the aws_key & aws_secret with your own Amazon Key & Secret. As well as putting in your bucket name and file path. We need the :csv at the end to specify the format but this could be :json or :xml. You can also save the aws_key & aws_secret in your project settings file: AWS_ACCESS_KEY_ID = 'myaccesskeyhere' AWS_SECRET_ACCESS_KEY = 'mysecretkeyhere' Note: When saving data with this method the AWS S3 Feed Exporter uses delayed file delivery. This means that the file is first temporarily saved locally to the machine the scraper is running on and then it's uploaded to AWS once the spider has completed the job. Saving Data to MySQL and PostgreSQL Databases Here well show you how to save the data to MySQL and PostgreSQL databases. To do this we'll be using Item Pipelines again. For this we are presuming that you already have a database setup called chocolate_scraping. For more information on setting up a MySQL or Postgres database check out the following resources: Windows: MySQL - Postgres - Mac: MySQL - Postgres - Ubuntu: MySQL - Postgres - Saving data to a MySQL database We are assuming you have already have a database setup and a table called chocolate_products in your DB. If not you can login to your database and run the following command to create the table: CREATE TABLE IF NOT EXISTS chocolate_products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), price VARCHAR(255), url TEXT ); To save the data to the databases we're again going to be using the Item Pipelines. If you don't know what they are please check out part 2 of this series where we go through how to use Scrapy Item Pipelines! The first step in our new Item Pipeline class, as you may expect is to connect to our MySQL database and the table in which we will be storing our scraped data. We are going to need to install the mysql package for Python. pip install mysql If you already have mysql installed on your computer - you might only need the connection package. pip install mysql-connector-python Then create a Item pipeline in our pipelines.py file that will connect with the database. import mysql.connector class SavingToMySQLPipeline(object): def __init__(self): self.create_connection() def create_connection(self): self.conn = mysql.connector.connect( host = 'localhost', user = 'root', password = '123456', database = 'chocolate_scraping' ) self.curr = self.conn.cursor() Now that we are connecting to the database, for the next part we need to save each chocolate product we scrape into our database item by item as they are processed by Scrapy. To do that we will use the scrapy process_item() function (which runs after each item is scraped) and then create a new function called store_in_db in which we will run the MySQL command to store the Item data into our chocolate_products table. import mysql.connector class SavingToMySQLPipeline(object): def __init__(self): self.create_connection() def create_connection(self): self.connection = mysql.connector.connect( host = 'localhost', user = 'root', password = '123456', database = 'chocolate_scraping' ) self.curr = self.connection.cursor() def process_item(self, item, spider): self.store_db(item) #we need to return the item below as Scrapy expects us to! return item def store_db(self, item): self.curr.execute(""" insert into chocolate_products ( name, price, url) values (%s,%s,%s)""", ( item["name"], item["price"], item["url"] )) self.connection.commit()ToMySQLPipeline': 300, } Saving data to a PostgreSQL database As in the above section - we are assuming you have already have a postgres database setup and you have created a table called chocolate_products in your DB. If not you can login to your postgres database and run the following command to create the table: CREATE TABLE IF NOT EXISTS chocolate_products ( id SERIAL PRIMARY KEY, name VARCHAR(255), price VARCHAR(255), url TEXT ); To save the data to a PostgreSQL database the main thing we need to do is to update how the connection is created. To do so we will will install the Python package psycopg2. pip install psycopg2 And update the connection library in our function. import psycopg2 class SavingToPostgresPipeline(object): def __init__(self): self.create_connection() def create_connection(self): self.connection = psycopg2.connect( host="localhost", database="chocolate_scraping", user="root", password="123456") self.curr = self.connection.cursor() def process_item(self, item, spider): self.store_db(item) #we need to return the item below as scrapy expects us to! return item def store_db(self, item): try: self.curr.execute(""" insert into chocolate_products (name, price, url) values (%s, %s, %s)""", ( item["name"], item["price"], item["url"] )) except BaseException as e: print(e) self.connection.commit() AgainToPostgresPipeline': 300, } After running our spider again we should be able to see the data in our database if we run a simple select command like the following(after logging into our database!): select * from chocolate_products; Next Steps We hope you now have a good understanding of how to save the data you've scraped into the file or database you need! If you have any questions leave them in the comments below and we'll do our best to help out! If you would like the code from this example please check it out on Github. The next tutorial covers how to make our spider production ready by managing our user agents & IPs so we don't get blocked. (Part 4) Need a Free Proxy? Then check out our Proxy Comparison Tool that allows to compare the pricing, features and limits of every proxy provider on the market so you can find the one that best suits your needs. Including the best free plans.
https://scrapeops.io/python-scrapy-playbook/scrapy-beginners-guide-storing-data/
CC-MAIN-2022-40
refinedweb
1,574
57.5
Cloud Management & Usage Monitoring Through Continuous Integration with Quickbuild and Mist.io Cloud Management & Usage Monitoring Through Continuous Integration with Quickbuild and Mist.io Join the DZone community and get the full member experience.Join For Free Insight into the right steps to take for migrating workloads to public cloud and successfully reducing cost as a result. Read the Guide. [This article was written by Barak Merimovich.] private Openstack and Cloudstack accounts. With so many resources, and so many projects, stuff gets dropped once in a while. VMs are left running, forgotten by the developer that was using them or missed by the automation that was supposed to shut them down. And in the cloud, if you forget something, you pay for it. Literally. VMs are billed for the time they are active, whether or not you were actually doing something useful with them. And before you know it, the bills start mounting, and the people from accounting show up at my desk. So I need some way to monitor my cloud usage across multiple clouds and accounts. I spent a while looking online for a good cloud monitoring solution that would give me a quick overview of my current cloud usage. I love dashboards, by the way. Being able to see everything that interests me in one place makes things so much easier. After looking around at a bunch of cloud monitoring options, I finally found mist.io. It had just the right features I needed, and all that was left was to plug it in to my existing dashboard system. So let's start by reviewing the pieces. Mist.io Mist.io is a cool open-source project that monitors VM usage across multiple clouds. The list of supported cloud providers is pretty extensive (see the up to date list here, that at this time includes: EC2, Rackspace, Openstack, Linode, Google Compute Engine, SoftLayer, Digital Ocean, Nephoscale, HP Cloud, Bare metal servers, Docker containers and KVM hypervisors. There is also a mist.io website, which basically offers the same product with some additional premium additions. I'll be using this service for my purposes, though you can always install the open source version locally. Mist.io also offers a Python SDK which makes it a very scriptable system – I’ll be using the client SDK shortly. Mist.io includes a console for your current cloud usage which is pretty useful by itself: But for my project I also need to maintain history and statistics about my usage. Quickbuild The continuous integration (CI) system we use for Cloudify is Quickbuild. We've been using it for a very long time and it has proven to be a rock-solid system. Quickbuild also has a flexible dashboard system, where I can plug in my own custom data sources. While this post deals a lot with the specifics of Quickbuild, the principles should be pretty much the same for any CI/Automation system. The glue The general idea is to define a configuration in Quickbuild that will poll the mist.io API for running VMs, collect historical data and display the latest results on a Quickbuild dashboard. So let’s get to work! Mist.io account First up, you’ll need to set up your account on . It’s free. Cloud credentials For each cloud account that you want to monitor, create a dedicated user and give it the minimal permissions required to view the currently running instances. This is a good best practice for all integrations – use a dedicated account for each integration, using something like Openstack keystone or AWS IAM, and give it only the permissions it MUST have. Configure mist.io backends In mist.io, a backend is a monitorable target that can host compute instances. These can be Openstack tenants and AWS regions, for instance. You will need to set up a backend for each one of these. If, like me, you work across a lot of AWS regions and Openstack tenants, this part can get a bit tedious. So I wrote a couple of scripts using the mist client SDK to speed things up a bit. Set up HP Cloud Backends: from mistclient import MistClient client = MistClient(email="MY_MIST_EMAIL", password="MY_MIST_PASSWORD") hp_username="HP_CLOUD_USERNAME" hp_password="HP_CLOUD_PASSWORD" hp_regions = [ ["hpcloud:region-a.geo-1", "HP - US West"], ["hpcloud:region-b.geo-1", "HP - US East"] ] # list of HP tenants to monitor hp_tenants = ["my-first-tenant", "my-other-tenant"] def create_hp_backends(): for region, region_name in hp_regions: for tenant in hp_tenants: print "Creating HP backend for tenant %s in region %s" % (tenant, region) try: client.add_backend(title= "%s - %s" % (region_name, tenant), provider=region, key=hp_username,secret=hp_password,tenant_name=tenant) except Exception as e: print "Failed to create backend: %s" % e.message create_hp_backends() Set up AWS Backends: from mistclient import MistClient client = MistClient(email="MY_MIST_EMAIL", password="MY_MIST_PASSWORD") ec2_demo_access_key ="AWS_ACCESS_KEY" ec2_demo_secret_key = "AWS_SECRET_KEY" ec2_account_name = "AWS_ACCOUNT_NAME" def create_ec2_backends(): # creates backends for all ec2 regions for provider in client.supported_providers: if "EC2" in provider["title"]: title = "%s - %s" % (provider["title"], ec2_account_name) print "Creating backend: %s" % title try: client.add_backend(title = title, provider = provider["provider"], key=ec2_demo_access_key, secret=ec2_demo_secret_key) except Exception as e: print "Failed to create backend: %s" % e.message create_ec2_backends() Just grab the scripts and tweak the credentials and tenants to match what you need. BTW: I do wish mist.io would make this bit a little easier. There really should be an easier way to just give them the credentials say ‘Monitor everything’ Create a script to collect the current compute instance details I wrote another quick script using the mist SDK to do this. The whole thing is on github: This is the interesting bit: Note how the python script generates an XML file with the details of the compute instances. Quickbuild likes XML files as input. Configure Quickbuild First thing we need to do is set up Quickbuild to accept the XML file format our script generates. This is a one-time operation, but you need to be an administrator of the Quickbuild server to be able to do this. - As a Quickbuild administrator, go to Administration -> Plugin Management -> Custom Statistics Report -> Configure - Click “Add New Category” - Give your category a name, like “Running Cloud Instances” and an appropriate description - Add two ‘indicators’ (fields in the report) - running – This gives us the total number of running machines, and is usually the most interesting value. Set the XPath expression to – count(//machine[@state=’running’]). - all – This gives us the total number of machines, so it includes machines that are shut-down or deleted. Not as interesting, but can be useful. Set the XPath expression to – count(//machine) It should look something like this: Set up the recurring task With the custom Quickbuild category all set up, we can create the task that actually polls the mist.io API. This can and should be done with a regular Quickbuild user, not an administrator. I have made the configuration available as a gist. You can import it from: Or you can create it manually using the following instructions: - Create a new Quickbuild configuration somewhere in the build tree. I called mine ‘CloudNodeMonitor’ - In the configuration definitions screen, go to Settings->Repositories - Click the ‘+’ icon to add a new repository and choose a git repo - Set the git repository URL to (you can always fork this repo if you want to add something). Make sure to give your Quickbuild repository a name you will remember. - In the Quickbuild configuration screen, go to settings->steps - Add a new step (it’s the ‘+’ icon) and choose repository->checkout. - In the step editing screen, make sure to choose the repository you created previously - Add a new step, and choose build->shell/batch command - Set the command field to: ./mist_monitor_runner.sh ${vars.getValue(“mistUsername”)} ${vars.getValue(“mistPassword”)} Note how we are passing the mist.io credentials as Quickbuild variables – we will configure them later. - Set the Working Directory field to: mist_monitor - Add a new step, and choose Publish -> Custom Statistics Report - Set the Statistics Category to the name of the custom statistics category you created previously (something like “Running Cloud Instances”) - Set the Files to Process field to: mist_monitor/output.xml - Set the Report Set Name to: All_Machines - In the Configuration editing screen, go to Settings->Variables - Add a new variable. Call it mistUsername, and set its value to the username of your mist.io account. - Add a new variable. Name it mistPassword (you may want to set the value to be displayed as a secret value, not a cleartext one) and set its value to the password of your mist.io account. - Set the task execution schedule. Go to: Settings->General Settings->Edit and schedule the periodic execution of the task. Once an hour works out fine for me. Your new Quickbuild configuration should look something like this: Run the task a couple of times from the Quickbuild console to make sure it works as expected. Have a look at the ‘Latest Build’ tab to see the results. Set up the dashboard widget Quickbuild has a built-in dashboard system that is pretty straightforward. Choose the dashboard you want to use (or create a new one) Select Add Gadget -> Others -> Custom Statistics Choose a relevant title and set the configuration to the task you created Set the Build field to: Latest Successful Build Set the Category Name field to the Custom Category you created (“Running Cloud Instances”) Select the “All_Machines” Report set and click Save. You should see the latest results from your cloud monitor show up on the dashboard. Click ‘View Report’ and choose the ‘Statistics’ tab, and you can see statistics on your cloud usage: Now you have yourself a Quickbuild dashboard showing you the number of compute instances running on all of your clouds, courtesy of mist.io, plus some nice historical data as well. }}
https://dzone.com/articles/cloud-management-usage
CC-MAIN-2018-43
refinedweb
1,639
53.21
ONTAP Discussions Hi, I am using snapmirror to backup from a number of primary cDOT clusters to a secondary cDOT cluster. There are 130 mirrors completing successfully. In one case however, the initilisation starts and the updates begin, but after approx 1 hour the initilisation fails with the error 'Transfer failed.'. Last Transfer Error Was 'Transfer failed. (Volume access error (Invalid argument))'. Primary Vserver Volume State Type Size Available Used% abc x1 online RW 2.30TB 566.2GB 75% Seconadry def a_x1 online DP 3.50TB 3.08TB 12% The event log only repears the same error. Vol sizes are appropiate. Language settings are the same. How do I discover which is the Invalid Argument, and resolve the issue Regrads, Mick Make sure your aggregate has enough space. If the others finished you may not have enough room in the aggregrate. I'm not sure if you are using thin provisioning or not.
https://community.netapp.com/t5/ONTAP-Discussions/cDOT-Snapmirror-Transfer-failed-Volume-access-error-Invalid-argument/td-p/90695
CC-MAIN-2021-04
refinedweb
153
68.36
$79.20. Premium members get this course for $31.25. Premium members get this course for $299.99. Premium members get this course for $349.00. Premium members get this course for $37.50. thats the ext directory for the jdk. you also need to put it in the 'ext' directory for your JRE. probably somewhere under program files With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you. Both Bea WebLogic and DataDirect Drivers are not freely available. Thats why I was looking into integrating JTDS into my application as it supposed to be fast, reliable and stable. Can you please suggest on how to use Jtds?? Thanks, PC MENIAC Not much needed to use thejtds driver, just drop the jar in your 'ext' directory and away you go. Heres some background with jdbc if you need it: Sorry, for not mentioning it before that I was after a freebei. Anyways, I still am not able to compile my program and I think the reason is that I am not doing something right with the "jtds-0.8-rc1.jar" file. CAn you please help me in this matter. I have this jar file in the same folder as my Java program but I think I need to specify its full path somewhere in my java program. CAn you tell me where to set its class path. I'll really appreciate if you can give me a piece of code as well to connect to SQL SERVER 6.5 using JTDS driver. Thanks!! Regards, PCMENIAC <jdk>/jre/lib/ext jdbc:jtds:<server_type>:// Connection connection = null; try { // Load the JDBC driver String driverName = "net.sourceforge.jtds.jdbc Class.forName(driverName); // Create a connection to the database String serverName = "localhost"; String mydatabase = "mydatabase"; String url = "jdbc:jtds://" + serverName + "/" + mydatabase; // a JDBC url String username = "username"; String password = "password"; connection = DriverManager.getConnectio } catch (ClassNotFoundException e) { // Could not find the database driver } catch (SQLException e) { // Could not connect to the database } windows: javac -classpath %classpath%;jtds-0.8-rc1.j unix: javac -classpath $CLASSPATH:jtds-0.8-rc1.ja I completely agree with you and that was the sort of help/answer I was looking for, but even after placing the jar file in the ext directory, I still have the following message: "Exception in thread "main" java.lang.NoClassDefFoundE Can you please suggest something?? Also, do you know what the Connection URL would be if the SQL Server6.5 is located on my local machine?? Would we be using localhost:1433 as our server name?? And what if it resides on a server (server name = newct04). Thanks very much for answering both parts!! Regards, PCMENIAC there are multiple ext dirs. I complete disagree on using ext dir. you'll have a lot problem in future if you use that. just use what I showed you to compile, to see if it works firts. once you get it works, we can easily simplify your compile process further. >> Would we be using localhost:1433 yes. >> And what if it resides on a server (server name = newct04). newct04:1433 make sure you can ping newct04 from command line. above assumes your sql server setup to listen on the default port 1443. I am able to compile my program, it when I am executing the program that I get the above mentioned error. I even tried executing my program by: java -cp x:/paragchauhan/java/jtds- It does'nt look like that its even entering the program and try to establish a connection. Help Please, so we can start rewarding!! KENNETHXU, Yes, I can ping the server from cmd. And Thanks for letting me know that difference in URL for accessing SQL SERVER 6.5 locally or from a server. Regards, PCMENIAC java -cp x:/paragchauhan/java/jtds- if it is unix(linux), try this: java -cp x:/paragchauhan/java/jtds- if you still have problem, then 1. is connectdb the class name? FYI, class name is case sensitive. 2. did you put your class in any package? if you do then you need to do something diff. let me know. 3. is your class public? it must be public. X is the drive and X:/parag chauhan/java/ is where the jar file and my java program are stored. >> is connectdb the class name? ConnectDB.java is the name of my java program which I have compiled. (Assuming, that after compiling, a class file with the same name gets created.) >> Did you put your class in any package? NO, my class is not in any package. I have just written a java program in the above mentioned folder and compiled it. >> 3. is your class public? it must be public. Yes, it is public. (I assume u mean the main class in the java program.) Let me know if there is any other information that I can provide you to facilitate things. Thanks a lot for your help and advice!! PCMENAIC x: cd "\parag chauhan\java\" javac -classpath %classpath%;jtds-0.8-rc1.j java -cp %classpath%;jtds-0.8-rc1.j also, make sure this is you class definition: public class ConnectDB { again **case sensitive** let me know. Don't bother stuffing around with classpaths in this case, put your jar also in your jre's 'ext' directory (probably under Program File/Java/...). > Would we be using localhost:1433 as our server name?? No remove the port part, unless you are using a non standard port. localhost would be used if database was running on same machine. > And what if it resides on a server (server name = newct04). then use that server name: String serverName = "newct04"; String url = "jdbc:jtds://" + serverName + "/" + mydatabase; // a JDBC url why remove the port part. the port part works no problem at all! Just a quick note on your code: // Create a connection to the database String serverName = "localhost"; String mydatabase = "mydatabase"; String url = "jdbc:jtds://" + serverName + "/" + mydatabase; // a JDBC url String username = "username"; String password = "password"; connection = DriverManager.getConnectio AS yousaid earlier that the connection string for jtds looks like: jdbc:jtds:<server_type>:// So, we have to specifically define in property about the TDS version we intend to use Bcos the default value is 7.0 (valid only for SQL SERVER7 and 2000) but it is 4.2 for SQL SERVER 6.5. So, the URL would be something like: conn = DriverManager.getConnectio ATC is the database in SQL SERVER 6.5 which I want to connect. I am able run the program now but its giving me a new error: java.sql.SQLException: Connection Refused HElp Please guys, Regards, PC MENIAC Check that the database is listeneing for connections and the TCP/IP protocol is enabled. How can we check that database is listening for connections and that TCP/IP protocol is enabled for it. And if nto enabled, how can we enable it. Once again, it an oldie SQL SERVER 6.5 that I'm using. Thanks for your help!! PCMENIAC I have given up on 6.5 now and am looking into SQL SERVER 2K but with 2000 as well, I am having the following error: java.sql.SQLException: No Suitable Driver at java.sql.DriverManager.get at java.sql.DriverManager.get at ConnectDB2000.getConnectio at ConnectDB2000.main<Connect Now, according to the FORUM at JTDS website, the only reason that "No suitable driver" exception is thrown by the DriverManager when none of the registered Driver implementations recognizes the supplied URL. This means that you either did not register jTDS with the DriverManager first (by calling Class.forName("net.sourcef Inorder to make sure that the JTDS Driver is registered with DriverManager, I got a message displayed if whether driver was loaded properly or not. The code for this is: try { Class.forName("net.sourcef } catch (ClassNotFoundException e) { System.out.println ("Could not load the Driver!!"); e.printStackTrace(); } System.out.println("Driver ************************** The second reason could be that I might have mistyped the URL, so here is the URL as well: String uname = "ATCConnect"; String pwd = "ATC"; try { conn = DriverManager.getConnectio } catch (SQLException e) { System.out.println ("Could not create the connection!!"); e.printStackTrace(); } ************************** Any suggestions?? Regards, Parag Chauhan atleast you and kennethxu managed to answer my original question correctly (although couldnt solve the problem completely). So, do you think give me the solution of the I'm trying From the bottom of that support page: The information in this article applies to: Microsoft SQL Server 4.2x Microsoft SQL Server 6.0 Microsoft SQL Server 6.5 > I have given up on 6.5 now and am looking into SQL SERVER 2K but with 2000 as well You might want to also try M$'s JDBC driver then. > conn = DriverManager.getConnectio uname;pwd doesn't look right to me. conn = DriverManager.getConnectio if you use sql server 2k, there is a free jdbc driver released by Microsoft: (search for the work jdbc) more info:;en-us;313100 You were right there!! The connection URL that I had:- conn = DriverManager.getConnectio was not correct. It needs to be:- conn = DriverManager.getConnectio So, everything is sorted hopefully!! KENNETHXU, OBJECTS But it was actually Kennethxu's answer that got the Jtds Driver fixed and enabled me to use it in my java program but it was your answer that got the URL corrected. So, I think its only fair to share the points between you and Kennethxu. Please let me know what you think!!! Thanks, Parag Chauhan Looks like I was a bit too hasty in my judgement regarding the results. I still have the error, which is: Also, I was thinking about giving Microsoft Driver for JDBC a go, but while looking at the documentation (KENNETHXU's Link for More Info!!), I realized that it requires me to list the .jar file in my CLASSPATH variable and I dont know how to do that. IS it the same as : Control Panels-----> System (or System Properties)-----> advanced---> Environment Variables And then add a new Variable with variable name as = CLASSPATH and its value = CLASSPATH=.;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\msbase.jar;c:\pro Please advice!! I would really appreciate your help!! Thanks, PCMENIAC Does that user exist on your database? > I realized that it requires me to list the .jar file in my CLASSPATH variable Easier to copy the jar's to the relevant 'ext' directories as I mentioned above for the tds driver. Yup, I created the username in the database ATC my self by following these steps: SQL SERVER ENTERPRISE MANAGER ----> SQL Server Group -----> Security ---> Logins ----> (Right Click) New Login ---> (General Tab) Name = ATCConnect ---> Select SQL SERVER Authentification ---> Password = ATC ---> Default Database = ATC ---> (Database Access Tab) Select Database ATC for Permit ---> (Database Roles for ATC) tick public, DB_owner, DB_Datareader, DB_Datawriter ---> click OK. Did I do Anything wrong?? Let me know!! Also, I have put my jtds-0.8-rc.jar file in ext directory (D:\J2sdk1.4.0\jre\lib\ext CAn you please help?? Regards, PCMENAIC Regards, Parag Chauhan
https://www.experts-exchange.com/questions/20943592/Connecting-SQL-SERVER-6-5-with-JAVA.html
CC-MAIN-2018-09
refinedweb
1,866
67.55
New to OpenCV, can't load an image Hi! I am new to OpenCV and trying to follow the tutorial to load an image. However, Mat image, namedWindow, imshow, WINDOW_AUTOSIZE, and waitKey are not found in the cv namespace. I have #included opencv\core.hpp, opencv2\imgcodecs.hpp, opencv2\highgui.hpp, opencv2\opencv.hpp, and opencv2\cv.hpp. So far I have tried linking $(OPENCV_DIR)\lib, using namespace cv, and adding " CV_ ", " cv:: " and " cv_ " before each command. The tutorial says to use this code: Mat image; image = imread(imageName.c_str(), IMREAD_COLOR); if( image.empty() ) { cout << "Could not open or find the image" << std::endl ; return -1; } namedWindow( "Display window", WINDOW_AUTOSIZE ); imshow( "Display window", image ); waitKey(0); //I have found that this code will fix all but the " image " problem: Mat image = imread(imageName.c_str(), IMREAD_COLOR);// " Mat " must be on the same line as " imread " if( image.empty() ) // " image " is underlined here { cout << "Could not open or find the image" << std::endl ; return -1; } const std::string& windowName("Display Window"); // Must be declared first to work void namedWindow(int windowName, int WINDOW_AUTOSIZE );// Must have the "void" and "int" types defined void imshow(int windowName, int image ); // Also must have types, and " image " is ok here int waitKey(0); // Must have int type I am using OpenCV 3.2 on a clean Windows 10 computer with VS 2017 Enterprise. Thanks for your help!! Do you build opencv using cmake ? Thank you! Yes I did, I used cmake and VS 2017 Have you build opencv with sample? I think your VS project is wrong. You should use cmake to build your project too like in this sample are there even vs2017 prebuilt packages ? I did build opencv with samples, and most of them don't work. How does cmake affect VS recognizing what functions are a part of the cv namespace? I can't even get my program to compile. @berak: I'm pretty sure there aren't any VS 2017 prebuilt packages, I wish there were!! :) "most of them don't work" don't try your own project. You have to solve this first. Go back to opencv project and clean solution and build. Give first error. I can build opencv and opencv_contrib with VS 2017 (without Eigen) : "========== Build: 350 succeeded, 0 failed, 7 up-to-date, 5 skipped ==========" And I go back to VS 2015 waiting VS 2017 update 1
https://answers.opencv.org/question/147501/new-to-opencv-cant-load-an-image/
CC-MAIN-2022-40
refinedweb
400
74.19
Nss compat ossl From FedoraProject Revision as of 21:46, 16 June 2008 NSS compatibility for Open SSL apps The the following packages were converted using nss_compat_ossl: - stunnel - wget - libcurl Each is lacking something, perhaps something important, but basic SSL support is done. Currently Supports - Creating an SSL server listener and accepting requests - Creating an SSL client socket and making requests - Ciphers that should be compatible with OpenSSL - Client certificate authentication - Token password prompting/handling Things to be done - We should import referenced certificates on the fly into our NSS database. A PKCS#11 module to do this has been started but requires NSS 3.12 so it is of limited use in the short-term. - Many missing pieces of the API How To Use the Library For the short term (see nss_compat_ossl#Reading PEM files) applications will need to use an NSS database. This consists of 3 files: cert8.db, key3.db and secmod.db located in the same directory. In order for the target to find the right database the environment variable SSL_DIR needs to be set to the location of your NSS database (unless an appropriate cert is You can find more examples of the NSS command-line tools here: [1] The library currently lack nice, importable autoconf rules. Developers will need to tell their application where to find the NSPR and NSS include and libraries. pkg-config with the package names of nss and nspr can be used to determine this. The variables HAVE_NSS and HAVE_OPENSSL can be used to differentiate between NSS and openSSL in that 20% of cases not handled by nss_compat_ossl. The include file "nss_compat_ossl.h" must be included, be careful to not include any openSSL header files. Some specific things to watch out for: - OpenSSL CRL handling is very different from NSS so any OpenSSL CRL handling code should be ifdef'd out. NSS handles CRLs directly. Users can use the crlutil tool to load them into the NSS database. - The callbacks for info_callback and verify_callback are made but often those functions use very diverse OpenSSL calls that aren't supported yet (and may never be). These callbacks will likely all need to be rewritten for NSS. - Few of the BIO_ calls are implemented. If these are used extensively in the target application then some major rewriting may be needed. Best to request some assistance before proceeding. - nss_compate_ossl doesn't use OpenSSL structures in most cases so any programs trying to access specific elements may need to change, possibly to use accessor functions. - NSS supports two modes for its SSL cache: threaded and multi-process. The nss_compat_ossl code currently initializes the cache for multi-threaded operation. If you need multi-process you will need to call these in your application: SSL_CTX_set_timeout(ctx, timeout); SSL_ShutdownServerSessionIDCache(); SSL_ConfigMPServerSIDCache(0, timeout, timeout, NULL); Where Can I get the Source? svn co A tarball is available at [2] The write-able repo is at svn+ssh://user@svn.fedorahosted.org//svn/hosted/identity/common/ Reading PEM files Work on a PKCS#11 module that can load file-based certificates on-the-fly is in development. This module will let use more closely emulate OpenSSL with little-to-no changes on deployment. It currently supports: - 8 slots. Slot 0 is designed to store all CA certificates and slots 1-7 will hold one certificate and one key pair. The choice of 8 slots is arbitrary and will likely be increased before shipping. - Can load encrypted private keys and prompt the user for a PIN (and verify the PIN) - Can handle SSL client and server encryption - On-par performance as the existing NSS built-in token What it requires: - The API that this module uses, CKFW, is missing some features in the current version of NSS in Fedora 8 (3.11.x). NSS 3.12 will be needed to build this module. Do applications automatically inherit FIPS 140-2 Compliance simply by linking with NSS? No, as with using any FIPS validated module, all applications must comply with the security policy of that module document to claim FIPS conformance. The NSS security policy was written so that apps can easily comply with the requirements. The main NSS FIPS site is The security policy page starts at The policy document can be found at Most requirements are met simply by turning on FIPS mode in NSS. The FIPS module automatically prevents most illegal operations with respect to FIPS compliance. The security policy points out those areas where it does not. Sample Application When learning something new there is little better than a concrete example to ease things along. I'll use stunnel 4.15 as a starting point. It is what I used to help develop nss_compat_ossl. The first thing we have to do is tell autoconf about nss_compat_ossl and possibly override any default OpenSSL settings. This includes any include directories, libraries and any definitions (like HAVE_OPENSSL). Here is a diff of the stunnel configure.ac. I'll go into the details of what and why after the fold. --- configure.ac.orig 2007-07-20 10:45:57.000000000 -0400 +++ configure.ac 2007-07-20 13:52:44.000000000 -0400 @@ -101,6 +101,9 @@ AC_MSG_NOTICE([**************************************** SSL] ) checkssldir() { : + if ! test -z "$nss_compat"; then + return 0 + fi if test -f "$1/include/openssl/ssl.h" then AC_DEFINE(HAVE_OPENSSL) ssldir="$1" @@ -113,8 +116,30 @@ return 1 } +OPT_NSS_COMPAT=no AC_MSG_CHECKING([for SSL directory] ) +AC_ARG_WITH(nss_compat, +[ --with-nss_compat=DIR location of installed NSS compatibility SSL libraries/include files] , OPT_NSS_COMPAT=$withval) + +if test X"$OPT_NSS_COMPAT" != Xno; then + if test "x$OPT_NSS_COMPAT" = "xyes"; then + check=<code>pkg-config --version 2>/dev/null</code> + if test -n "$check"; then + addlib=<code>pkg-config --libs nss</code> + addcflags=<code>pkg-config --cflags nss</code> + fi + else + # Without pkg-config, we'll kludge in some defaults + addlib="-L$OPT_NSS_COMPAT/lib -lssl3 -lsmime3 -lnss3 -lplds4 -lplc4 -lnspr4 -lpthread -ldl" + addcflags="-I$OPT_NSS_COMPAT/include" + fi + CFLAGS="$CFLAGS $addcflags" + LIBS="$LIBS $addlib -lnss_compat_ossl" + nss_compat="yes" + AC_DEFINE(HAVE_NSS_COMPAT) + echo "Using nss_compat_ossl instead of OpenSSL" +fi AC_ARG_WITH(ssl, [ --with-ssl=DIR location of installed SSL libraries/include files] , [ ]@@ -130,7 +155,7 @@ done ) -if test -z "$ssldir" +if test -z "$ssldir" -a -z "$nss_compat" then AC_MSG_RESULT([Not found] ) echo echo "Couldn't find your SSL library installation dir" The stunnel configure.ac does things a little differently than others I've seen. They declare a separate function to try to find OpenSSL then set things up from there. What we need to do is short circuit this. There is no AC_UNDEFINE so our stuff has to come first. The first change in the file is in checkssldir(). This bails out if nss_compat_ossl has been selected. We check for a global variable. The interesting stuff comes next. The meat is in the --with-nss_compat field. If it it gets set to a directory then we use that path (like --with-nss_compat=/usr/local) and we set CFLAGS and LIBS as best we can. If it is set without a DIR (e.g --with-nss_compat) then we use pkg-config to get things setup for us which is more likely to produce the results we want. The important things to set are: AC_DEFINE(HAVE_NSS_COMPAT) LIBS to include the NSS and NSPR libraries and potentially the path they are installed in (if not in /usr/lib) CFLAGS or INCLUDES to include the NSS and NSPR include file locations The change of "if test -z "$ssldir -a -z "$nss_compat" we want to crap out if neither OpenSSL nor nss_compat_ossl are set. Now that we can configure things properly you would run something like: % autoconf % ./configure --with-nss_compat You should probably verify that the Makefiles define -DHAVE_NSS_COMPAT=1 and that LIBS and CFLAGS are sane. Next we move onto the code changes. You can tackle it either as an iterative or analytical process. I tend to use the iterative approach myself. This involves trying to build and tackling errors as they come up. In the stunnel case we run into a problem quite early. common.h is trying to include some OpenSSL headers which it can't find. We need it to use our header instead: --- common.h.orig 2007-07-20 12:21:27.000000000 -0400 +++ common.h 2007-07-20 12:23:23.000000000 -0400 @@ -287,6 +287,7 @@ /**************************************** OpenSSL headers */ +#ifndef HAVE_NSS_COMPAT @@ -302,6 +303,9 @@ #endif +#else +#include <nss_compat_ossl/nss_compat_ossl.h> +#endif /**************************************** Other defines */ When using an iterative approach errors tend to appear as undeclared defines and functions such as this in ssl.c: ssl.c: In function ‘init_compression’: ssl.c:63: error: ‘COMP_METHOD’ undeclared (first use in this function) ssl.c:63: error: (Each undeclared identifier is reported only once ssl.c:63: error: for each function it appears in.) ssl.c:63: error: ‘cm’ undeclared (first use in this function) ssl.c:69: warning: implicit declaration of function ‘COMP_zlib’ ssl.c:74: warning: implicit declaration of function ‘COMP_rle’ ssl.c:81: error: ‘NID_undef’ undeclared (first use in this function) ssl.c:85: warning: implicit declaration of function ‘SSL_COMP_add_compression_method’ gmake: *** [ssl.o] Error 1 nss_compat_ossl doesn't support SSL compression so we need to skip this function. One way to do it is with: --- ssl.c.orig 2007-07-20 14:09:42.000000000 -0400 +++ ssl.c 2007-07-20 14:11:06.000000000 -0400 @@ -59,6 +59,7 @@ } static void init_compression(void) { +#ifdef HAVE_OPENSSL int id=0; COMP_METHOD *cm=NULL; char *name="unknown"; @@ -87,6 +88,7 @@ exit(1); } s_log(LOG_INFO, "Compression enabled using %s method", name); +#endif } static int init_prng(void) { You could easily use the reverse of this and use #ifndef HAVE_NSS_COMPAT. The choice is yours. Our next obstacle is in options.c. A slew of missing BIO_ errors are reported, way to many to include here. A further investigation reveals that the function generates a base64 value from a string passed in. In this case NSS provides a single function to do this so we can patch this with: --- options.c.orig 2007-07-20 13:40:24.000000000 -0400 +++ options.c 2007-07-20 13:48:19.000000000 -0400 @@ -1263,6 +1263,9 @@ } static char *base64(char *str) { /* Allocate base64-encoded string */ +#ifdef HAVE_NSS_COMPAT + return BTOA_DataToAscii(str, strlen(str)); +#else BIO *bio, *b64; char *retval; int len; @@ -1284,6 +1287,7 @@ BIO_read(bio, retval, len); BIO_free(bio); return retval; +#endif } The last set of problems is a bit more challenging. Lets break down each change in the diff. The first change is in verify_init(): --- ctx.c.orig 2007-07-20 13:51:00.000000000 -0400 +++ ctx.c 2007-07-20 13:52:10.000000000 -0400 @@ -304,6 +304,7 @@ } if(section->crl_file || section->crl_dir) { /* setup CRL store */ +#ifdef HAVE_OPENSSL revocation_store=X509_STORE_new(); if(!revocation_store) { sslerror("X509_STORE_new"); @@ -341,6 +342,7 @@ } s_log(LOG_DEBUG, "CRL directory set to %s", section->crl_dir); } +#endif } SSL_CTX_set_verify(ctx, section->verify_level==SSL_VERIFY_NONE ? NSS handles CRLs via its database. OpenSSL imports them from flat files on startup. So we can #ifdef around a fairly large block of code as NSS will handle all this for us. It does mean though that the user that runs the program will need to preload the CRL into the NSS database using /usr/bin/crlutil before starting stunnel. So this should be documented somewhere. @@ -352,6 +354,7 @@ static int verify_callback(int preverify_ok, X509_STORE_CTX *callback_ctx) { /* our verify callback function */ +#ifdef HAVE_OPENSSL char txt[STRLEN] ; X509_OBJECT ret; SSL *ssl; @@ -389,11 +392,13 @@ /* errnum=X509_STORE_CTX_get_error(ctx); */ s_log(LOG_NOTICE, "VERIFY OK: depth=%d, %s", callback_ctx->error_depth, txt); +#endif return 1; /* Accept connection */ } This change is also very significant. In both OpenSSL and NSS you can write your own callback to verify certificates, CRLs, etc. nss_compat_ossl does a lot of this for the user so we can #ifdef around this code. It is possible to go ahead and define a verify_callback that does real work in both but the nss_compat_ossl API is missing a lot of functions typically found in this verification so you will have to proceed cautiously. nss_compat_ossl automatically checks for certificate trust and valid dates. If there are other things you require you can continue to do them in a verify_callback() but it may be tricky. NSS handles CRL checking automatically so we can ignore all of the following code: /* Based on BSD-style licensed code of mod_ssl */ static int crl_callback(X509_STORE_CTX *callback_ctx) { +#ifdef HAVE_OPENSSL X509_STORE_CTX store_ctx; X509_OBJECT obj; X509_NAME *subject; @@ -506,6 +511,7 @@ } X509_OBJECT_free_contents(&obj); } +#endif return 1; /* Accept connection */ } And finally a very important change. nss_compat_ossl does not necessarily mimic the data structures of OpenSSL so any attempts to directly access parts of a structure will probably fail. In nss_compat_ossl there is only a logical difference between an SSL structure and a SSL context structure. So we can't pass in s->ctx. But we can pass in s to get what we want. This doesn't actually do much since we aren't calculating this data. I included this to demonstrate one possible workaround. @@ -525,7 +531,11 @@ SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); else if(where==SSL_CB_HANDSHAKE_DONE) +#ifdef HAVE_NSS_COMPAT + print_stats(s); +#else print_stats(s->ctx); +#endif } static void print_stats(SSL_CTX *ctx) { /* print statistics */ Now stunnel should build but it isn't quite ready to run yet. With NSS you have to tell it where it can find the key and certificate databases. We use the environment variable SSL_DIR to specify one (the default is /etc/pki/nssdb). Congratulations. You've ported your first application with just a handful of changes to the code.
https://fedoraproject.org/w/index.php?title=Nss_compat_ossl&diff=35101&oldid=6357
CC-MAIN-2016-40
refinedweb
2,244
56.66
Now that we’ve practiced defining a function, let’s learn about calling a function to execute the code within its body. The process of executing the code inside the body of a function is known as calling it (This is also known as “executing a function”). To call a function in Python, type out its name followed by parentheses ( ). Let’s revisit our directions_to_timesSq() function : def directions_to_timesSq(): print("Walk 4 mins to 34th St Herald Square train station.") print("Take the Northbound N, Q, R, or W train 1 stop.") print("Get off the Times Square 42nd Street stop.") To call our function, we must type out the function’s name followed by a pair of parentheses and no indentation: directions_to_timesSq() Calling the function will execute the Walk 4 mins to 34th St Herald Square train station. Take the Northbound N, Q, R, or W train 1 stop. Get off the Times Square 42nd Street stop. Now it’s your turn to call a function! Instructions Call the directions_to_timesSq() function. Click Run to see it execute and print out. Add an additional print statement to our directions_to_timesSq() function. Have the statement print "Take lots of pictures!" Run your code again and see how your output changes.
https://www.codecademy.com/courses/cs-101-livestream-series/lessons/intro-to-functions/exercises/calling-a-function
CC-MAIN-2021-39
refinedweb
207
74.9
This is the third installment in a five-part series, looking at the changes and opportunities Salesforce DX offers app developers today. Over the course of this series, we’ll talk about: The content in this series is a collaboration between the Salesforce DX and Salesforce Evangelism teams. Salesforce DX is often referred to as SFDX or sfdx. One reason is because the executable command for the Salesforce CLI is sfdx (another is that we humans like abbreviations). And with that in mind people often think that the Salesforce CLI can only be used with Salesforce DX projects – which isn’t true. The Salesforce CLI is, as the name says, a command line interface that enables you to run numerous tasks on your Salesforce environments. A major portion of the current functionality is targeted at elements that were introduced with Salesforce DX, like source-driven development using scratch orgs or IDE integration and ALM. However, there’s a lot more going on and available across any type of org. For example, you can use the CLI to run a SOQL query against a production org. As you can see, this isn’t dependent on scratch orgs or other new functionalities at all. It’s a standardized— and Salesforce-supported— way of working with any org. Think of it like using Ant with the Force.com Migration Tool, but as a modern tooling. Yes, you can! By design, not all commands work with every org type. For example, you can’t pull source data from a non-scratch org. But first things first. When you run sfdx force:org:list you get a list of all your orgs, that you authenticated against using the CLI. === Orgs ALIAS USERNAME ORG ID CONNECTED STATUS ─── ──────────── ─────────────────────────────────────── ────────────────── ──────────────── (D) DevHubDF17 rene@df17hub.org 00D1I000001frNvUAI Connected GS0 Hub rene@gs0hub.org 00DB00000005F5JMAU Connected SFDX1 Org rene@sfdx.test 00D0Y000000ZDFzUAO Connected ALIAS SCRATCH ORG NAME USERNAME ORG ID EXPIRATION DATE ───────── ─────────────────────────────── ───────────────────────────────────────────────────── ────────────────── ─────────────── einstein2 einstein-ai test-73n9c1exkpdq@einstein-ai.net 00D0R000000Ct3BUAS 2018-01-13 This abbreviated list of my current orgs shows that I have authenticated the CLI against three non-scratch orgs (lines 4-6). This can be, for example, your production org, a Sandbox org or a Developer Edition org. Check out the last column for the scratch org, which shows the expiration date of that org. ➜ ~ sfdx force:auth:web:login -a weather Successfully authorized rene@weather.tdx with org ID 00D0Y000002EzZbUAK You may now close the browser The command above demonstrates how to use the CLI to authenticate into a non-scratch org and give it the convenient alias “weather” that can be used to refer to that org later (aliases are great so you don’t have to remember usernames). The CLI opens a new browser tab where you can enter your credentials to authenticate the desired org. Upon successful authentication the CLI automatically stores OAuth credentials on the local machine. Boom! Done. With that, you can now run CLI commands against that org, like getting the list of all custom objects (snippet 1) or create a new record (snippet 2). The previously set alias “weather” makes it easy to select the org that we want to use. ➜ ~ sfdx force:schema:sobject:list -c custom -u weather Fitting_Appointment__c Nature_Test__x Watson_Discovery__x ➜ ~ sfdx force:data:record:create -s Account -v "Name=SuperDemoCompany" -u weather Successfully created record: 0010Y000013cwW5QAI. There are many more commands available that you can run against any org, like running Apex tests, retrieving metadata or assigning permission sets. This is possible because the CLI uses the Tooling API or the Metadata API under the hood. You can get the full list of available commands using sfdx force:doc:commands:list. I highly encourage you to check them out and use the CLI as much as possible. It makes you more productive because you don’t have to switch windows and contexts. We’re updating the CLI frequently, so bookmark and keep checking the CLI Release Notes. One of the biggest features of Salesforce DX is the introduction of “scratch orgs.” These ephemeral orgs can (and should) be part of your development workflow. But before you can use this type of org you’ll have to set up a Salesforce DX project using the Salesforce CLI. Also, make sure that you have enabled the Dev Hub as explained in the previous post. ➜ sfdx force:project:create -n MyNewProject target dir = /Users/rwinkelmeyer/blog create MyNewProject/sfdx-project.json create MyNewProject/README.md create MyNewProject/.forceignore create MyNewProject/config/project-scratch-def.json The sfdx force:project:create -n MyNewProject command (line 1) creates within the current folder a new subfolder with the name MyNewProject. It then automatically creates a couple of files and folders within that sub folder as you can see on the output (lines 2-6). The sfdx-project.json file controls the main elements of the project and how the CLI behaves for this project (not globally, more on that later). The following snippet showcases the default contents for a new project definition file. { "packageDirectories": [ { "path": "force-app", "default": true } ], "namespace": "", "sfdcLoginUrl": "", "sourceApiVersion": "42.0" } packageDirectories: This parameter defines where the CLI should look for your source elements. This also means that you can change the location from force-app to something else if it’s more appropriate for your environment. You can add multiple directories here for a modular structure when you want to break up your app into multiple packages. namespace: If your package uses a dedicated namespace you can (or should) configure it here. sfdcLoginUrl: This parameter tells the CLI where it should point to for authentication. Why is this configurable? Well, you may want to connect to a sandbox and change the login url to. sourceApiVersion: The CLI has the capability of creating new code elements, like Apex classes, Lightning components etc. This parameter is used to automatically set the API version for the new components. The default value will match the API version of your Dev Hub org. You find the full description of the configuration options here. The second file type controls the “shape” of a newly created scratch org. In a new project an example configuration (project-scratch-def.json in the config folder) is created. You can have multiple configuration files, depending on your needs of developing and testing with different org preferences. { "orgName": "rwinkelmeyer Company", "edition": "Developer", "orgPreferences" : { "enabled": ["S1DesktopEnabled"] } } To use it with the CLI, you run the command (from the root folder of the project) sfdx force:org:create -f config/project-scratch-def.json -a MyScratchOrg. This kind of configuration file allows for tremendous flexibility for testing your projects against a variety of orgs. For example, you could have a scratch org shape for an Enterprise org with Service Cloud licenses, with Lightning and multi-currency enabled, and another for an Unlimited org with Communities, Einstein Analytics and ETM 2.0 enabled. All of these JSON files can be bundled into the same projects for your team to use while building and testing. You can check out the documentation for scratch org shapes here. One of my personal highlights is the capability to disable the Lightning session cache in a scratch org by disabling the S1EncryptedStoragePref2 preference. { "orgName": "rwinkelmeyer Company", "edition": "Developer", "orgPreferences" : { "enabled": ["S1DesktopEnabled"], "disabled": ["S1EncryptedStoragePref2"] } } If you’re struggling to create a scratch org shape that perfectly mimics your production org, keep a couple things in mind: First, your scratch org, even when ‘correctly’ configured, will not perfectly mirror production. You’ll still want a full copy sandbox if you need a mirror of production. Second, the usefulness of a scratch org isn’t tied to how perfectly it mirrors production (and the fact that it can be different can be very useful). Scratch orgs are there to help with the initial stages of development. If you want to test out impacts of turning on new features (like multi-currency or ETM 2.0), you can use a scratch org to do that. Once you’ve got the basics of what you’re building together in a scratch org, you’ll move changes into your regular app development lifecycle. Your sandboxes, which do more closely match production, can help you then perform more robust testing and refactoring before you release to production. The Salesforce CLI relies on a couple of variables when communicating with the Salesforce org of your choice. You can set these variables globally (for all commands) or locally for a specific project. These variables can be the alias or the username (both are interchangeable) for your DevHub, the API version that the CLI should use, or the default username for your project. ➜ salesforce-einstein-platform-apex git:(develop) sfdx force:config:list === Config NAME VALUE LOCATION ───────────────────── ────────── ──────── apiVersion 42.0 Local defaultdevhubusername DevHubDF17 Global defaultusername einstein1 Local Per definition, local variables override global variables. Using the command sfdx force:config:set you can set project-specific variables. When you append the -g parameter you’ll set the value globally for all projects. Another example where the CLI is using a local configuration is the -s parameter in sfdx force:org:create. When you use this parameter, the command fetches the default username for the created scratch org (or the alias if you set one) and sets it as a local variable for the current project. One of my favorite features of the Salesforce CLI is to use it with scratch orgs for my daily development flow. These are the most common steps (which you likely already learned in the Trailhead module “App Development with Salesforce DX”). We have modified the source representation for some of our more cumbersome Metadata API .xml files, such as custom object, static resources, and custom object translations. The force:source:push and force:source:pull commands work with a new org metadata tracking feature to help keep your project’s source in sync with the changes that you make in the scratch org. These changes make it easier for you to integrate with source control and manage your source files. We all have been in the situation when something doesn’t work. Have you ever changed the same file locally and in the scratch org? What about changing a bunch of things in the org the day before and forgetting which files have been touched? That’s where sfdx force:source:status will be your savior. ➜ salesforce-einstein-platform-apex git:(develop) ✗ sfdx force:source:status -u einstein1 === Source Status STATE FULL NAME TYPE PROJECT PATH ────────────── ──────────────────────────────────────────────────────── ──────────────────── ──────────────────────────────────────────────────────────────────────────────────── Local Changed EinsteinDatasetCreation/EinsteinDatasetCreationHelper.js AuraDefinitionBundle force-app/main/default/aura/EinsteinDatasetCreation/EinsteinDatasetCreationHelper.js Local Changed EinsteinModelSelect/EinsteinModelSelectController.js AuraDefinitionBundle force-app/main/default/aura/EinsteinModelSelect/EinsteinModelSelectController.js Remote Changed Einstein_PlaygroundController ApexClass force-app/main/default/classes/Einstein_PlaygroundController.cls Remote Changed Einstein_PlaygroundController ApexClass force-app/main/default/classes/Einstein_PlaygroundController.cls-meta.xml Remote Changed Einstein_PredictionService ApexClass force-app/main/default/classes/Einstein_PredictionService.cls Remote Changed Einstein_PredictionService ApexClass force-app/main/default/classes/Einstein_PredictionService.cls-meta.xml Once you run this. So what do you do when you have a remote file that you want to “reset” to the status of the local file, but the local file hasn’t changed? The Salesforce CLI uses a fingerprint hash to track local changes, so you have to change the content of the local file. Just change it a bit, like by adding a space somewhere, then run the push command and then undo the change. Done. Last, but not least, you can exclude files from any of the force:source commands. The .forceignore file, which works like gits .gitignore, gives you granular control over that. Read more about how to use it here in the docs. And don’t forget to commit that file to version control, so that it is shared with your team. The CLI is a powerful tool that simplifies your interaction with any Salesforce org. You can find numerous examples on how to use it with scratch orgs and source controlled code on this site, like in this blog post. In the next post of this series we’ll dive into techniques for automating the CLI for an even better development workflow. Also check out the Salesforce DX Trail on Trailhead to learn more about the standard flows when using the CLI like converting existing code, working with scratch orgs, or how to deploy metadata using the CLI. You should also be sure to register for the upcoming Ask Me Anything (AMA) with the Salesforce DX Product Management team, coming up on February 27! If you’re looking to get more hands on with Salesforce DX at TrailheaDX, check out the Emerging Tech for Developers Bootcamp. René Winkelmeyer works as Principal Developer Evangelist at Salesforce. He focuses on enterprise integrations, mobile, and security with the Salesforce Platform. You can follow him on Twitter @muenzpraeger.
https://developer.salesforce.com/blogs/2018/02/getting-started-salesforce-dx-part-3-5.html
CC-MAIN-2018-39
refinedweb
2,140
55.64
An AtoZ The Ultimate Guide to your summer weekend getaways MAY 2018 COMPLIMENTARY STORE MERGING SALE Fargo-Moorhead-and company -- we are excited to announce joining two of our brands into one beautiful, boldly inspirational lifestyle boutique! we will be closing our doors to LOT 2029 at the end of may, and in june you will come to know us only as mint + basil (apparel + home). adding women’s apparel and accessories to the kitchen + home items you love, will blend the lifestyle brand of our (and hopefully your) dreams! our mission has always been to provide a unique product at a great price yet, there’s more. as life evolves, so must we. the goal: connecting us, our staff, and neighboring business’s to provide our customers a magical experience worth sharing with friends and family. 21 8th st s the change will happen much like life gradually...like your grandmother’s pie recipe. a pinch here, dusting there, a little patience - the perfect memory created. We invite you to join in our journey by following along on instagram: @lot2029 + @mint_and_basil. $5 off $25+ *exp 04.30.18 • limit one use onyx + pearl mint + basil lot 2029 lot2029 7 1 4 main ave 25%-75% OFF sale + store updates: Instagram : @lot2029 new spring decor *mergehas does not apply to bismarck or sioux falls* arrived! insta -> @mint_and_basil 612 main ave @lot2029 @onyx.and.pearl TABLEOFCONTENTS COVER STORY 23 AN A TO Z ADVENTURE Do you need to get out of Fargo-Moorhead for a few days? Is your 9 to 5 wearing you down? Then take a look at our A to Z list of weekend getaways that are within driving distance of our area. We take you to different parts of North Dakota, South Dakota, Minnesota and even Canada to give you plenty of options if you are in need of a vacation! FEATURES 42 A DOWNTOWN RIVERFRONT HOME 44 SOMETHING SWEET IN DOWNTOWN 54 DRUG COURT: STIFLING ADDICTIONS RECURRING RESOURCES 59 Event Calendar Editor's Letter 5 Things to Eat & Drink 64 Live Music Think Global, Act Local 69 Drink Specials Kilbourne Group Health & Wellness Spotlight 52 Mixologist of the Month 78 The Last Page: Ritchell Aboah: Awake! Jazz and Poetry Lounge 14 39 46 48 50 FARGO MONTHLY | MAY 2018 All your favorite things in one spot. FARGOMONTHLY.COM Extended content, events, drink specials, giveaways, and more. GET WITH IT Spotlight Media 15 Broadway N. Suite 500, Fargo info@spotlightmediafargo.com 701-478-7768 fargomonthly fargomonthly.com @fargomonthly ON THE COVER The cover photo was taken in collaboration with Nature of the North, a Fargo company started by Jon Walters. Nature of the North aims to unplug and recharge, break down barriers and create experiences through the outdoors. This is done through various outdoors based workshops around town. More than anything, they want to showcase that there are fantastic outdoor adventures to be had in our area. For the photo, Nature of the North provided the people, the vehicle and all the outdoor trimmings (canoe, backpack, etc.). All we had to do was show up and snap the pictures. Find out more about Nature of the North on their Facebook page or on their website natureofthenorth.co. @fargomonthly FROMTHEEDITOR Honor Thy Mother D id you know that Mother's Day is May 13? If you did not, then consider this your informal reminder to get your mother something special this year. Whether that is a card, call or text, I am sure your mom will appreciate it. Why we need to have one day to remind us to honor our mothers seems odd to me. I believe that mothers should be recognized every single day. Not to be crass, but you would not be reading this sentence if it wasn't for your mother birthing you in the first place! I have a special connection to my mother. I'm sure that seems like a clichĂŠ statement, as all of us have some sort of special bond with our mothers. However, I cannot overstate how amazing my mom is. Her influence in my life really knows no bounds and it continues to grow each day. There is no doubt that my mother and I have forged a strong bond over the course of my 24 years. However, our relationship became iron-clad in the wake of a tragedy. My father passed away when I was 20, he was only 56. This forced me to grow up a lot faster than what was perhaps intended. It comes as no surprise that my mother was shaken, as was I, but I felt it was my duty to show strength and do anything for my mother's sake. It was built upon one of the final things I told my dad. I promised him I would do everything in my power to protect my mom. Through this, we have grown closer and together, we are able to honor my father and her husband. We no longer cry over his passing, we just laugh at the memories we had with him. Truthfully, when we can sit down and reminisce, that is when we are at our strongest as a family. For me, growing up as an only child, my mother is now the only person I can go to for those anecdotes. I would give anything to have my father back, as any son would. However, I know that him leaving drew my mother and me closer in a multitude of ways. It also showed me how much I have relied on her my entire life. So, thank you to all the mothers out there! I hope each of you is properly appreciated by your sons or daughters on May 13. More than anything, I want to say thank you to the strongest, kindest, most caring, silliest, most stubborn, brilliant mother of them all, my mother, Lisa Schmidt. I am beyond lucky to have had you raise me the way you did and it has made me who I am today. Love you Ma! Nolan Schmidt Editor nolan@spotlightmediafargo.com 14 | MAY 2018 | FARGOMONTHLY.COM @NolanPSchmidt MAY 2018 Volume 8 / Issue 5 Fargo Monthly Magazine is published 12 times a year and is free. Copies are available at more than 500 Fargo-Moorhead locations and digitally at fargomonthly.com. Publisher Mike Dragosavich drago@spotlightmediafargo.com Chief Operations Officer Steve Kruse steve@spotlightmediafargo.com CREATIVE Editorial Director Andrew Jason andrew@spotlightmediafargo.com Editor Nolan Schmidt nolan@spotlightmediafargo.com Graphic Designers Sarah Geiger, Matt Anderson Photographers Hillary Ehlen, J. Alan Paul Photography Contributors Alex Cyusa, Mike Allmendinger, Kylee Seifert Copy Editors Andrew Jason, Nolan Schmidt Content Strategist Sam Herder Social Media Nolan Schmidt Web Team Huong Tran, Jessica Ballou Advertisingbins Delivery Drivers Bruce Crummy Fargo Monthly is published by Spotlight Media, LLC. Copyright 2018 Fargo Monthly and fargomonthly.com. All rights reserved. No parts of this magazine, LLC 15 Broadway N, Suite 500 Fargo, ND 58102 or info@spotlightmediafargo.com ADVERTISING: 701-478-SPOT (7768) Meet the team MIKE STEVE ANDREW NATE JOE BECCA NOLAN SARAH MATT JENNY DAN SCOTT PAM CHANTELL JESSE HUONG JESSICA RYAN HILLARY LARISSA Learn more about us at spotlightmediafargo.com DARREN Be Sure to Pack Your Weekend Getaway Essentials Sunglasses A Map or Atlas Your Camera Don't Forget Your Driver's License (Because you will need a drink at some point.) A Compass for when you get lost and you don't have cell service. A reliable pair of shoes or boots for long hikes. Swim gear for your day on the lake. AtoZ An Adventure Take a break from your 9 to 5 and escape on your own weekend getaway Do you need to get out of Fargo for a few days? If so, there are several places within driving distance of the FargoMoorhead area you can go. Whether it is North Dakota, South Dakota, Minnesota or even Canada, there is a place or event for everyone to escape to for a weekend. Jump out of the rat race and journey across state (or country) lines as we profile the best weekend getaway spots from A to Z! Well, what are you waiting for? Your trusty companion for outdoor fun (dog). BY Nolan Schmidt A pen and paper to write. Creative inspiration will be all around you! Special thanks to North Dakota Tourism, South Dakota Tourism, Explore Minnesota and Tourism Winnipeg for the photos featured within. 23 Alexandria, MN Distance from Fargo-Moorhead: Approximately 108 miles Why visit Alexandria? It is the perfect place if you are looking for an outdoor excursion. That could mean running or biking the vast amounts of trails that surround Alexandria or taking advantage of the 350 lakes in the area. If you run out of things to do on the lake (which is highly unlikely) you can also enjoy their public beaches. After a long day, sit back and enjoy a meal at one of their many restaurants or a drink at their hometown winery, brewery or distillery. Walk, Bike or Run the Central Lakes Trail The most famous landmark in Alexandria is the 28-foot Viking that stands tall in Big Ole Central Park. Big Ole also serves as the trailhead for the Central Lakes Trail, a 55-mile long trail going through three Minnesota counties. If you are in Alexandria at the right time, the Viking also welcomes guests to the Alexandria Farmer's Market. c Enjoy Alexandria's nightlife at Zorbaz or Bugaboo Located on the Southwest side of Lake Le Homme Dieu are two of Alexandria's biggest nightlife hotspots. Zorbaz, a staple restaurant and bar in Minnesota lakes country is home to a mix of Mexican food and delicious pizzas. Right across the street from Zorbaz is Bugaboo, another lake staple with live music and an atmosphere unlike any other. Spend an afternoon on the lake Alexandria and the surrounding area is home to 350 lakes, so there is plenty to choose from. Whether it is Lake Agnes or Lake Victoria, you will be able to rent either a pontoon or jetskis to use on the lake. If you are not feeling so adventurous, there are plenty of open beaches to occupy as well. Crazy Horse Over 1 million 24 | MAY 2018 | FARGOMONTHLY.COM Surly Brewing Company Minneapolis, MN Quite possibly the Mecca of Minnesota breweries, Surly offers a taste for everyone who comes through the door. You can tour their brewery on Monday, Tuesday, Friday, Saturday or Sunday. Castle Danger Brewing Two Harbors, MN An underrated brewery up in the Northeast corner of Minnesota. Castle Danger has some of the most consistently tasty beers in the state. Tour their brewery on Friday or Saturdays. It was also voted the Best Minnesota Brewery by Minneapolis Star Tribune readers. Laughing Sun Brewing Company Bismarck, ND Though you can grab a Fernson six-pack at your local liquor store here, nothing beats a freshly tapped brew. If you find yourself traveling on I-29 near Sioux Falls, you better check out their tap list! 6,532 feet was a warrior of the Oglala Lakota tribe who fought at Battle of the Little Bighorn. visitors per year which makes it one of the biggest tourist destinations in South Dakota. 5 Breweries to visit on your weekend getaway Fernson Brewing Company Sioux Falls, SD Distance from Fargo-Moorhead: Approximately 530 miles 1948 Brewery Tours If you are traveling down I-94 en route to somewhere special, make sure you stop by Laughing Sons. Their diverse group of beverages is unmatched in the BismarckMandan area. Crazy Horse Memorial The year the mountain carving construction began. B Height of the monument. 16 years The time it took to sculpt Crazy Horse's face. Half Pints Brewing Company Winnipeg, MB Although they lie North of the border, these Canadians really know their beer. This brewery has built itself into one of the best in the entire country. Be sure to take a tour on Saturdays! E Deadwood, SD Distance from Fargo-Moorhead: Approximately 485 miles The True History of Deadwood. Though popular culture has somewhat bent Deadwood's history to its own liking, the foundation of debauchery is very much accurate. Originally a literal gold mine, Deadwood was soon infested with outlaws and gunmen. Perhaps a few of the most famous characters who inhabited Deadwood were Calamity Jane, Wild Bill Hickok and Wyatt Earp. In fact, the legendary Wild Bill met his end in a gunfight in Deadwood. While some of this may sound too wild to believe, it is this nostalgia for the Wild West that keeps Deadwood alive to this day. Why Travel to Deadwood? The first major attraction in Deadwood is the history swirling around the area. There are several museums and places to learn about the town's scandalous past. Along with that, you can go on guided walking tours led by the "original" townspeople. E If tours are not your thing, there are plenty of outdoor activities to take part in too. Deadwood is near Custer State Park and there is also off-road vehicle and horse rentals to take you through the unexplored portions of the town. There are also several shops to pick up souvenirs or you can even have your Wild West picture taken. As they say, "You'll always find something to do in Deadwood." Entertain Yourself! First Avenue in Downtown Minneapolis Guthrie Theater in Minneapolis Belle Mehus Auditorium in Bismarck Paramount Theatre in St. Cloud The Center in Rapid City F Festivals The Top Five Festivals to Plan a Getaway Around WE Fest, August Moondance Jam, Soundset, May 27 2-4 July 19-21 St. Paul, MN The Twin Cities are Detroit Lakes, MN Walker, MN The biggest party in Minnesota commences on Detroit Lakes the first week of August. This year's festival includes Jason Aldean, Carrie Underwood, Florida Georgia Line and country legend Vince Gill. An annual gathering of rock and classic rock enthusiasts. Late July will find rock staples Kid Rock, Poison's Bret Michaels, Def Leppard and former KISS guitarist Ace Frehley performing. Minnesota Renaissance Festival, August one of the premier 18-September 30 areas for great (weekends only) hip-hop. They Shakopee, MN project this legacy with their annual Soundset festival on the Minnesota State Fairgrounds. This one-day festival will feature rap powerhouses Migos, Logic and Tyler, the Creator. They will also welcome hip-hop icons Erykah Badu, Ice-T and the Wu-Tang Clan. North Dakota State Fair, July 20-28 Minot, ND North Dakota's biggest summer get together A Minnesota summer staple, the brought in nearly Renaissance festival 300,000 people in 2017. This brings in roughly 320,000 people per year will yet again year. That number feature the classic deep-fried foods is massive given we all love. The that the festival is Grandstand will only open on the showcase the weekends in late musical stylings summer. Never of Florida Georgia the less, you can Line, Dierks feast like royalty Bentley and while knights joust rock virtuosos as you take in this Nickelback. spectacle of a festival. Gooseberry Falls Distance from Fargo-Moorhead: Approximately 282 miles Why Should You Visit? Minnesota's North Shore is one the most scenic and peaceful areas in the entire state. Those two qualities are married together to create Gooseberry Falls, one of Minnesota's must-sees. The state park has five waterfalls along the Gooseberry River, which eventually empties into Lake Superior. There is no shortage of things to do while at Gooseberry. There are several areas to camp with one even requiring you to kayak down the river. Hiking and mountain biking are also very much encouraged with 20 miles of hiking trails and nearly 11 miles for mountain biking. If you love to fish, you can do so right along the shores of the river. However, you will need a Minnesota fishing license and a trout stamp. H Historic Tour Down I-94 3 Places to Visit While Traveling down Interstate 94 Enchanted Highway near Gladstone Heritage Center in Bismarck Although you need to take a slight diversion from I-94, the Enchanted Highway is certainly worth it. Beginning at exit 72 and ending 32 miles South in Regent, along the county highway, you will see spectacular metal sculptures of grasshoppers, geese and even pheasants. Badlands Dinosaur Museum in Dickinson Within its walls, you will find the largest collection of dinosaur fossils in the state of North Dakota. This includes a complete Triceratops skull along with six full dinosaur skeletons. J The newly renovated center takes you through the various ages of North Dakota history. From the Ice Age to the present day, you will learn about everything that lives or once lived in the state. You will find its beautiful campus on the grounds of the State Capitol. Itasca State Park Distance from Fargo-Moorhead: Approximately 100 miles Why visit Itasca? Located at the headwaters of the Mississippi River, Itasca State Park allows you to experience a getaway that is not terribly far from the FargoMoorhead area. It is this convenience that makes it one of the most popular state parks in Minnesota. Roughly 500,000 people visit the park each year, but that is not to say it lacks exclusivity. Outside of the various camping sites throughout the park, there are 38 indoor lodging units so you can relax in style. There is no shortage of things to do at Itasca either. Whether it's visiting the Mary Gibbs Mississippi Headwaters Center, hiking the 49 miles worth of trails or visiting the 2,000-acre Wilderness Sanctuary, there is something for everyone. With over 32,000 acres in the whole park, you can find your own secluded portion of Itasca for your weekend getaway. Jazzfest 2018 What is Sioux Falls Jazzfest? We're sure South Dakota is one of the last places you would think of when you hear jazz music. Never the less, Sioux Falls plays home to some of the biggest jazz and blues acts in America. The free two-day event welcomes roughly 130,000 people per year. That makes it one of the biggest free music festivals in the country. Since its inception in 1988, Jazzfest has recorded consistent success both with the number of people and the artists they welcome. Who is headlining Jazzfest 2018? Jimmie Vaughan Though he is known as the older brother of blues legend Stevie Ray Vaughan, Jimmie Vaughan has carved out his own place in blues lore. He has opened for Jimi Hendrix and has also shared the stage with Eric Clapton and B.B. King. Taj Mahal Having been around since 1964, Taj Mahal (real name Henry Fredericks) has become one of the more well-known figures in the genre. The self-taught musician plays the guitar, banjo, piano and harmonica. His rendition of the song "Statesboro Blues" has become one the hallmarks of blues music. 27 Keystone, SD Distance from Fargo-Moorhead: 514 miles Mount Rushmore One of the most famous symbols and attractions in America is the Mount Rushmore National Monument. Coincidentally, the monument lies three miles away from Downtown Keystone. It is that attraction alone that has made Keystone such a densely visited area in South Dakota. Originally, it was to depict American West figures like Lewis and Clark, but it was ultimately decided that four presidents would be featured on the monument. Now, George Washington, Thomas Jefferson, Theodore Roosevelt and Abraham Lincoln keep a watchful eye over the city of Keystone. Their presence has also turned that city into a massive tourist destination. Big Thunder Gold Mine The National Presidential Wax Museum Another major attraction to those visiting Keystone is the Big Thunder Gold Mine. Taking place in an original gold mine, a tour is designed to give you the most accurate and comprehensive mining experience in the Black Hills. You will get a hands-on look at the Gold Rush that took place in the Black Hills from 1876 to 1914. Along with this, you will do your own gold panning which will result in you taking home some gold of your own. Would you ever want to see Franklin D. Roosevelt or George W. Bush in the flesh? At the National Presidential Wax Museum, you have that opportunity, kind of. The museum features every President, as well as several other wax figures. In total, the museum features 96 wax figures and with a self-guided tour, you can see them all. Lake Metigoshe Distance from Fargo-Moorhead: Approximately 281 miles The Perfect 12 hours at Lake Metigoshe 8-11 a.m. Canoe Trail You can rent a canoe while at Lake Metigoshe. Then you can canoe throughout the entire park, going in somewhat of a circle. You will be able to canoe around School Section Lake, Eramosh Lake and Rost Lake in the process. 11-1 p.m. Hike the Old Oak Trail This trail is North Dakota's first National Recreation Trail. This interpretive trek has many stops along the way despite it being only about three miles long. Be sure to devote enough time to see all the plants and animals the trail has to offer. 28 | MAY 2018 | FARGOMONTHLY.COM L 4:30-8 p.m. Visit the International Peace Gardens 1-4 p.m. Hike or Mountain Bike the park's other trails Located 20 miles East of Lake Metigoshe State Park is one of the more visited sectors of North Dakota. The International Peace Gardens serve as a sign of peace between the United States and Canada. It welcomes roughly 100,000 people each year. There are several other trails to explore inside the park as well. There are four loops that make up these various trails, which end up totaling close to nine miles. While you're at it, you can do a bird checklist, which is available at the park's office. L Medora Distance from Fargo-Moorhead: Approximately 327 miles The History Behind Medora Much like Deadwood, SD, Medora has been billed as a Wild West town. In fact, that is relatively inaccurate. It was founded by French nobleman Marquis de Mores in 1883. He planned to ship meat to Chicago via the Northern Pacific Railway from Medora. So, originally, Medora was a meatpacking town. Later, Theodore Roosevelt would visit the area and fall in love with it. Since Roosevelt's time in the Medora area, the town has become a total tourist destination thanks to the history behind it. However, the idea that it was once an Old West town like Deadwood is not true. Top Ten Things to Do in Medora Medora Musical The one tradition that will never die in Medora is the nightly musical that runs from June 1 through September 8. A show taking place at a spectacular outdoor amphitheater has been Medora's long-lasting legacy. It is a professionally produced and performed Western show dedicated to Theodore Roosevelt's legacy. Pitchfork Steak Fondue With Medora's acclaimed chefs loading steaks onto pitchforks, you know you are in for a good meal. The most popular dining experience in the town goes unmatched by any other. Along with your steak, you will receive vegetables, fruit, coleslaw, baked potatoes, garlic toast, baked beans, salad, brownies, cinnamon-sugar donuts and a drink of your choice. Talk about a feast. Chateau de Mores Take a step back in time as you peruse this 26 room Chateau built by Medora's founder Marquis de Mores. He built the fantastic premises for his wife, Medora (for which the town is named). The home features its original furnishings and has been restored to what it looked like in 1885. Theodore Roosevelt's Maltese Cross Cabin This historic cabin once lied seven miles from Medora, but has since been moved into Theodore Roosevelt National Park. The 26th President lived there when he first came to the Dakota Territory. There are still several original items which belonged to Roosevelt in the cabin too. Tour the Downtown Shops There is no shortage of places to shop in Downtown Medora. Throughout this area, you will find several souvenir shops to remember your time in Medora by. You will also find several homemade items like honey and bars of soap. Get Your Old Time Photo Taken As with any tourist town, you will be able to dress like they did in the Old West and get your photo taken. You can grab a friend or family member and collect a photo to remember your trip by. Enjoy a Sweet Treat Depending on what you like, there are several places to satisfy your sugar craving in Medora. There is homemade saltwater taffy at Rushmore Mountain Taffy, assorted candies at Cowboy Lyle's and some of the best ice cream around at Marquis de Mores ice cream parlor. Elkhorn Ranch The most notable of Theodore Roosevelt's cattle ranches is the Elkhorn. It lies roughly 35 miles North of Medora but provides an incredible amount of history with it. Roosevelt built the ranch after moving back to the Dakota Territory following the death of his wife and mother, on the same day. It has since remained one of the seminal locations for those interested in Roosevelt's life. Bully Pulpit Golf Course Outside of an incredibly challenging golf course, Bully Pulpit is one of the most scenic in the region. Surrounded by the Badlands, players will be climbing through meadows along the Little Missouri River. It also features a few butte-top tee boxes overlooking the Badlands. Medora Riding Stables There is no greater way to explore Medora and the surrounding landscape than on horseback. You will see the buttes and canyons that the Badlands have to offer while on the back of your trusty steed. Otter Tail Lake N. Otter Tail County, MN Shooting Star Casino For those up for spending a little money and enjoying some nightlife, Shooting Star is the place. The closest casino in proximity to FargoMoorhead is only 70 miles Northeast in Mahnomen. Outside of the gambling, Shooting Star consistently brings high-end musical acts to its stage. Those two put together make for a night out unlike any other in Otter Tail County. National Parks South Dakota Badlands National Park Roughly 500 miles to the Southwest of Fargo-Moorhead lies one of South Dakota's two National Parks. The eroded buttes and grassland make it a premier spot for camping and hiking. You may even see a buffalo or two along the way. Maplewood State Park Wind Cave Nationallongest cave in the world. North Dakota. Minnesota. 30 | MAY 2018 | FARGOMONTHLY.COM P Pembina Gorge Distance from Fargo-Moorhead: Approximately 180 miles 12,500 acres The region is one of the largest areas of untouched woodlands. Ideal Conoeing 61 Rare plants and animals call Pembina Gorge home and are considered to be "rare" in North Dakota. The Pembina Gorge area is a fertile river valley, perfect for this water sport. Unaltered River Valley The largest stretch in the state going into Canada too. Q Rugby, ND Quiet Places Minnesota Boundary Waters With portions of the Boundary Waters connected to Voyageurs National Park, as well as some Canadian parks, it serves as a vast landscape of peacefulness. Serving as the literal boundary between Minnesota and Canada, it provides a harmonious exit or entrance into either location. It is the ideal place in Minnesota to set up a tent and spend the night looking at the stars or even the Aurora Borealis. The Geographical Center of North America North Dakota Coteau des Prairies Lodge Nestled on a prairie hill in small Havana, North Dakota is the Coteau des Prairies Lodge. Overlooking the sweeping Great Plains skyline, you can enjoy an escape from everything. Though it lies close to the South Dakota border, it provides its inhabitants a slice of North Dakota beauty with little chatter involved. South Dakota Sylvan Lake Within Custer State Park in Southwest South Dakota is a lake as tranquil as any in America. Sylvan Lake provides you with a calm environment with a sweeping view of the Badlands around you. It truly is one of South Dakota's most hidden gems. If you are heading for the Canadian border, be sure to take a pit stop in Rugby. This small town is roughly 225 miles Northwest of Fargo-Moorhead. However, despite how small it is, it's known for one very significant landmark. Rugby has long been considered the Geographical Center of North America, meaning where the continent reaches its halfway point. There are American, Canadian and Mexican flags representing this point in geographic lore. Since it gained that title, geographers have been in long discussion as to if Rugby actually is the center of the continent. Some argue that it is 15 miles Southwest of the town. Yet, it still remains a point of pride for the citizens of Rugby and is worth visiting along with your weekend getaway trek. Spirit Tour Vikre Distillery in Duluth, MN 7 Distilleries to Visit on your Getaway Far North Spirits in Hallock, MN If you are on your way up towards Canada for a weekend getaway, consider diverting to Hallock and Far North Spirits. Their small town sensibility certainly plays into their distilling. Badlands Distillery in Kadoka, SD A family tradition of making spirits has spilled over to fullscale operations at Badlands Distillery. Distilling since the prohibition days, this family uses locally sourced ingredients in their liquor. Glacial Lakes Distillery in Watertown, SD This Eastern South Dakota distillery relies heavily on the glacial water produced after winter to make their spirits. From that, they use South Dakota made products to round it all out. Duluth's only distillery is located just a few feet from Duluth's iconic Aerial Lift Bridge. Aside from that, they feature all sorts of spirits. Panther Distillery in Osakis, MN Panther was the first legal whiskey distillery in the state of Minnesota. Opening in 2011, this small distillery has become one of the most popular in Western Minnesota. Skaalvenn Distillery in Brooklyn Park, MN If habanero rum seems like an intriguing combination, it can be found at Skaalvenn. They produce small batches of that plus vodka, regular rum and aquavit. 11 Wells in St. Paul, MN Located in what was formerly a Hamm's Brewery is 11 Wells, a name which stems from, you guessed it, the number of wells they have on site. The distillery currently produces two types of whiskey and rum. Find their products at various places around the Twin Cities. 33 T Twin Cities 12 Hours in the Twin Cities. Hours 7, 8 and 9 Cheer on the Twins at Target Field. Upstream (or downstream) Canoeing Top Canoeing Destinations while on your getaway. Lake. Angostura Sakakawea Recreation This lake lies only about 50 miles Area from Bismarck and is the largest With some the most scenic views, man-made lake in the state. It is the Angostura Recreation Area is also the third largest lake of its kind a hotspot for canoeists. It features in the nation. Thanks to its easygoing roughly 36 miles of shoreline with current, most people can canoe beaches scattered throughout. So if around the lake all day long while you get tired of canoeing on the taking in the fabulous scenery water, hit the shore and enjoy around them. some time in the sun.. Valleyfair Distance from Fargo-Moorhead: Approximately 245 miles Though it features eight roller coasters and 75 total rides, there are some attractions at Valleyfair that cannot be passed up.. W Winnipeg Distance from Fargo-Moorhead: Approximately 222 miles 10 Things to do in Winnipeg The Forks It has been around for decades and follows a theme of unity. Not only is it where the Red and Assiniboine rivers meet, but it also serves as a gathering place for Americans and Canadians alike. The Forks feature a central market, dining accommodations and even a skate park. The meeting of the two rivers has become a sign of peace and inclusion in Winnipeg. Winnipeg Art Gallery Though it looks spectacular from the outside within the walls of the Winnipeg Art Gallery is some of the most stunning art Canada has to offer. Most of the pieces are Canadian or Manitoba centric, but it also features the largest collection of Inuit art. In total, the gallery has roughly 24,000 different pieces. Exchange District One of the trendiest spaces in all of Winnipeg is the Exchange District. It features turn of the century buildings while boasting some the cities hippest eateries and antique shops. The Exchange District aims to preserve the 20th Century buildings in Winnipeg. The Canadian Museum for Human Rights One of Winnipeg's newest attractions is this museum meant to promote discussion and change in the world. The architectural gem features 11 awe-inspiring exhibits with the final one taking place on the top floor of the museum. This provides the visitor with a view of the city that cannot be matched. FortWhyte Alive A vast prairie lies within Winnipeg's city limits. Here you can find various places to canoe, roam and sail. You can even see packs of bison roaming around the prairie. There is also the opportunity to sit and dine and drink at the restaurant patio. Manitoba Museum The Manitoba Museum is one of the most all-encompassing museums around. It features artifacts from almost every era of history in nine permanent galleries. The museum also features a planetarium on one of the most advanced projection systems. For anyone intrigued with Canadian and human history, the Manitoba Museum is the place to be. Royal Canadian Mint A stunning architectural sight, the Royal Canadian Mint produces all of Canada's circulation coins. Tours are available for those interested in the mint process. The Royal Canadian Mint was also tasked with making the medals for the 2010 Vancouver Olympics. Those are on display at the Mint as well. ThermĂŤa Spa If you need a relaxing getaway, Winnipeg has a state of the art spa for you to consider. ThermĂŤa offers thermal pools, Finnish saunas, massage treatment and even dining options. If you feel like being pampered, this is the place for you. Hermetic Code Tour Canada's finest legislative building is filled with hieroglyphics, Masonic symbols and numeric codes on its walls. During the Hermetic Code Tour, you will learn what all of these symbols mean and how they relate to Canadian history. Discover Downtown Winnipeg As is customary with any large city, Winnipeg has a bustling Downtown area. There are plenty of trendy spots to eat, drink and play as well as museums and historical items to take in. Beyond that, the architecture will stun you as you gaze at the Winnipeg skyline. y Yummy Food Stops 5 Dishes Worth Stopping For Xtreme Sports What is Extreme North Dakota Racing? North Dakota is becoming an extreme sports hotspot thanks to a combination of the rugged terrain and weather. Due to that, Extreme North Dakota Racing was spawned to provide the most extreme races for North Dakotans and others around the Tri-state area. For example, their most recent races involved Fatbike only races on a 15 to 20 mile stretch of snowy terrain. That race even had participants riding over the icy Red River. Another recent race had contestants running throughout the Sheyenne National Grasslands. There was a multitude of lengths with the lowest being a 25K and the longest being a 100K race. Still, Extreme North Dakota Racing considered that a warmup. Extreme North Dakota Racing has cultivated a culture of extreme sports that has stretched into Minnesota and South Dakota as well. Zoo Visits Butter Queen Coffee Ice Cream Minnesota State Fair The Famous Juicy Lucy Nook in St. Paul, MN For the animal lover in all of us, here are some tremendous zoos to check out on your getaway: Lola Pizza Pleasant Grove Pizza Farm Waseca, MN Como Zoo in St. Paul Not only is Como a zoo but it is also a conservatory for various plants. That conservatory is also available for private events as well. Animals you can see at Como Zoo include gorillas, giraffes and snow leopards. Minnesota Zoo in Apple Valley, MN The diversity in species at Minnesota Zoo in Apple Valley is almost incomparable to any other zoo in the Tri-state area. Animals that inhabit this zoo are Amur tigers, Komodo dragons and pumas. The "Spicy G" Burger Phillips Avenue Diner in Sioux Falls, SD Dakota Zoo in Bismarck, ND Though it was recently renovated, the Dakota Zoo in Bismarck is still a great attraction thanks to the animals brought in. They are famous for their peacocks, bobcats and Bengal tigers. Assiniboine Park Zoo in Winnipeg Many native Canadian animals among other arctic animals make up the vast animal population at Assiniboine Park Zoo. Some of these species include polar bears, caribou and even yaks. Pasta Carbonara Cru Restaurant and Bar in Nisswa, MN 37 5 Hillary Ehlen EAT & DRINK It's May! Check out these fresh eats and drinks as you dig your shorts and tank tops out from the bottom of your drawer. White Chocolate Chip Waffle A homemade waffle batter mixed with white chocolate chips. It is cooked to perfection before it is topped with strawberries, blackberries, candied pecans and a raspberry sauce. Served with three cheese tater tots too! The Boiler Room 210 Roberts Alley boilerroomfargo.com 39 steak frites Perfectly cooked and marinated steak with a side of fries seasoned with garlic and bacon bits too. It's on their lunch and dinner menus! The Toasted Frog 305 Broadway N. toastedfrog.com pushing daisies chamomile witbier A Belgian Witbier brewed with chamomile flowers, bitter orange peel and Indian coriander. That is what gives this brew its floral and citrus character. A perfect beer for the warmer weather. Drekker Brewing Company 630 1st Ave N. Suite 6 drekkerbrewing.com blackberry lavender white chocolate mocha With house-made whipped creme on top, this hot beverage is packed with blackberry, lavender and white chocolate flavor. Babb's Coffee House 604 Main Ave. babbscoffeehouse.com spicy pickle pizza One of the many delicious new items on Rhombus Guys menu. A jalapeno cream cheese sauce makes up the base. On top of that are Canadian bacon, bacon, pickles with a parmesan, provolone, cheddar and mozzarella cheese blend topping it off. Rhombus Guys 606 Main Ave. rhombuspizza.com A Downtown Riverfront Home City Centre Lofts Condominium project to provide a unique living experience for downtown residents BY Nolan Schmidt RENDERINGS COURTESY OF Team FMI A s part of the ever-growing downtown region, Mike Kelly and Kevin Hall of FMI teamed up many years ago and planned the City Centre Lofts condominiums. The lofts will be located at 200 4th Avenue North, which is just North of the new Fargo City Hall. It lies where the former Howard Johnson Hotel once stood. "The pursuit of perfect balance between nature and contemporary urban lifestyle is at the center of this project," said Kelly, a partner in the City Centre Lofts project. In fact, when the new City Hall was in need of additional parking, team FMI decided to develop the property in two phases. During Phase One, FMI construction is building a separate underground parking lot structure. This lot will support a portion of City Hall's parking needs. That lot is expected to be completed by late summer 2018. In Phase Two, we will see the building of the condominiums. Team FMI will construct four floors of flood protected riverfront condos. The initial framing will commence in June. Kelly, who is the salesman for team FMI, has been preselling units since the beginning of the year. "My partner, Kevin Hall, and his team will handle the build, all of the management and accounting and financials of the project," Kelly said. The building is split into four floors with each receiving its own name. The ground floor, known as the Plaza Vue, will feature a lobby and a community room. Residents on this level will be able to view the river and green space that was formerly 3rd Avenue. As you climb be collected from this property," Kelly said. Kelly believes this has been a selling point for people who are on the fence about buying rather than renting. floors, your view becomes more and more scenic. The second floor River Vue units will have an exercise facility that will support the whole building. A guest suite on the Grand Vue (third floor) can be rented out by owners from the home owner's association. Finally, the Penthouse Vue sees residents enjoying a spectacular view of the river with a loft and a 20-foot vaulted ceiling. Each penthouse also has its own private rooftop deck. All floors have unique floor plans named after gemstones. There are Ruby, Emerald, Diamond, Sapphire, Pearl and Opal plans. This allows potential residents to tailor their wants and needs FOR MORE INFORMATION more minutely. However, the price does vary from level to level. "While all of the units on the top floor are sold, we do have several one, two and three bedroom units with price points to fit most everyone's budget," Kelly said. "We hope the one bedroom units on the first floor will attract young professionals who work downtown or people just looking to downsize." The project also falls inside the Renaissance Zone. This affords buyers some property and North Dakota state income tax incentives. "The RZ incentives are not only a great deal for the buyer, but once the project is complete, it will help generate five times the amount of property taxes for the city that used to citycentrelofts.com CityCentreLofts It is Kelly's belief that potential residents are receiving the best that the urban downtown and rural riverfront has to offer at a very attractive price. "Our features and benefits are the best in all of downtown," Kelly said. "Couple these together and it actually makes a lot of sense to buy rather than rent, simply because of the money you are saving in the long run." Kelly says they plan to start framing the project in June of this year. Then, by October they will be building the exterior of the building with individual unit fit-ups to commence in March of 2019. It is Kelly's hope that buyers will be able to move in by late Summer or early Fall of 2019. As Downtown Fargo continues to grow more and more people will flock to live in and around the area. City Centre Lofts not only provides an affordable option for those interested, but it also provides a spectacular view along with all the big city amenities. This is done while still maintaining the hip, Downtown sensibility. 701-371-2741 43 Something Sweet in Downtown Funfetti edible cookie dough Scoop N' Dough Candy Co. set to open this month in RoCo retail space. BY Nolan Schmidt PHOTO BY Hillary Ehlen 44 | MAY 2018 | FARGOMONTHLY.COM Big Muddy (Dark chocolate ice cream with a caramel swirl and brownie pieces) scoopndoughcandyco Jamocha Joe (Coffee flavored ice cream with diced almonds and a chocolate fudge swirl) S'Mores edible cookie dough Shipwreck (Vanilla ice cream with a sea salt caramel ribbon and candied almond pieces)." THINK GLOBAL ACT LOCAL NoDak World Class Hospitality Mugire Amahoro* faithful readers! *Peace be with you in Kinyarwanda I hope this article finds you enjoying the sight of the melting snow. The weather has been too Midwestern nice and has became a classic long Midwestern goodbye, like you see during parties. The "light coat" weather (aka Spring) has finally arrived, forgive me for not using the adequate seasonal jargon but I do not want to jinx the weather’s timid seasonal transition towards the “no coat” weather (aka Summer). By Alex Cyusa Photo by Hillary Ehlen 46 | MAY 2018 | FARGOMONTHLY.COM The sun smiling at us means a lot of things for many people: outdoor activities, biking to work, going to the lakes, people in better moods and self-motivation for a spring cleaning as well. Soon enough, the Tri-College community will have their summer long break. This leaves the FM area feeling the absence and lower traffic of the 50,000 students who travel elsewhere or go back to their respective hometowns. What are the attributes we have to pitch to our prospective visitors, students, professional transplants and even longtime residents that don’t feel as connected? Where do they all go? Where are the fun destinations people usually go? How can we make them opt for a staycation in the Red River Valley? The hospitality industry is one that is known for creating loyal customers because of their ability to personalize each customer experience with their services. Folkways takes pride in providing world class and memorable experiences to whoever comes to our events. This is not a tangible value added to "memorable experiences," but it is the best kept Fargo secret. I have three propositions to ensure a world class NoDak hospitality to anyone who engages with the FM area: 1 The FRIENDER App or WELCOMINDER App (not too picky on the name) The Convention and Visitors Bureau should, in partnership with the city, make an app for two specific audiences: Transplant workers and young professionals recruited by the major employers of the area in an attempt to pair them with long-time workers of the area The Tri-Colleges paired with high schoolers because usually high schoolers have a better feel of the area than the average incoming freshmen or transfer student. This app would be called FRIENDER/WELCOMINDER (where peeps with mutual interests can connect meaningfully with the sole purpose of getting more involved in the FM area). 2 Adopt a newcomer program The Greater Fargo-Moorhead Economic Development Corporation does an amazing job with welcome parties during the year. However, when there is a group of newly hired employees moving to the area, I would love to see an "adopt a newcomer" program to follow up new Fargoans. Our area and our state have such low unemployment rates, companies cannot afford such high turnovers and attrition rates. We should invite long-time residents to take quarterly turns on “adopting a newcomerâ€? by getting them involved. They would do this with intentional invitations to the numerous public and private events the area has to offer. The adopters would be trained Fargo Ambassadors and would have extensive knowledge on the ins and outs of Fargo. However, it would be nice to see people who have lived here less than three years to be adopters too. This is due to the fact that they would more closely relate to being a Fargo newcomer. Branding Fargo as the "Mecca of Hospitality" Think of some of your most memorable moments you have had in the last few weeks or months. Was it a smell? A pleasant company? An exquisite meal while jamming to some folklore? Or just a feeling of being present in the moment causing a sentiment of belonging? Any of these could be continuously reproduced again here, and now it just takes the efforts of you and you alone to make this happen! 3 Whenever people engage with our community they should look forward to the next time they engage with us and maybe they will eventually think of moving here permanently! I think we have all of the ingredients to be one of the most hospitable towns in the United States because of our blazing warm community balancing out the glacial cold weather! Until our humble paths cross in the community, Murabeho!* *Goodbye in Kinyarwanda WHAT ABOUT A F argo Mike Allmendinger PHOTOS BY J. Alan Paul Photography and Hillary Ehlen 48 | MAY 2018 | FARGOMONTHLY.COM BikeShare. BikeShare. Hotel Donaldson. I’m a particularly big fan of the rooftop garden and lounge on a warm summer night.reddy’s Lefse or treats from Yeobo. HEALTH & WELLNESS SPOTLIGHT Staying Healthy on a Weekend Getaway! BY Kylee Seifert PHOTO BY Hillary Ehlen Weekend getaways are great for the body, mind and soul! Plus, they are a quick commitment, both timewise and financially, and can really improve your health… as long as you don’t over indulge during the entire getaway. Let’s chat about quick and easy tips to keep in mind to ensure you avoid gut rot, exhaustion and end up feeling like you need a vacation from your mini-getaway. Prioritize Movement Research the area you’re heading to and look for something active to do. Maybe some hiking, swimming, biking or kayaking. Make it a priority to schedule this into your weekend. Even just a walk in nature can do wonders for your body. If you’re going somewhere that doesn’t provide some of these opportunities, find a way to pack fitness into your bag. Try packing a resistance band, a couple small weights or even a yoga mat. Then you can get some movement in at least one of the days you are away. Rise & Shine with Exercise You’re on a quick getaway, no need to waste away the day trying to exercise. Get your booty out of bed early and move around before the events of the day start. 50 | MAY 2018 | FARGOMONTHLY.COM This will ensure it doesn’t get missed and you’ll be more apt to make better choices throughout your day. Look for a Kitchen & Grill When you are planning where to stay during your getaway, try to find a spot with a kitchen and a grill. Not only will this save your pocketbook, but it will also save your waistline too. When you have a kitchen and grill, you’ll be able to buy your own groceries and cook the meals yourself. You’ll then be less likely to splurge or eat something that you’ll end up paying for physically, mentally, and financially. Pack the Cooler If you’re driving to your getaway, pack a cooler and stuff it full of healthy meals and snacks. This will take a little pre-prepping and planning but you’ll be glad you did when you feel great and have the energy for enjoy your trip. Go Overboard on Water Drink water like it’s your weekend job. Even if you’re driving, your body will thank you if you chug-a-lug the whole way. Plus, you’ll probably be spending more time outside so it’ll be worth keeping yourself hydrated so you feel amazing during your getaway. Bring a water bottle everywhere with you and if you’re enjoying some adult beverages, have a glass of water alongside. Avoid the Sweets You’ll have a sweet enough time getting away, you shouldn’t need to add any sugar on top. Try to keep the sugar to a minimum. Think of all your getaway meals as if you are eating at home. Of course you can allow yourself to splurge a tad bit here and there. But keep it mindful and avoid letting it roll from breakfast over to lunch and into dinner. Bring the Remedies Pack a bag of natural remedies for things like cuts, burns and germs. A natural salve, a non-toxic hand sanitizer and essential oils like lavender and oregano are must haves when you’re on a weekend getaway. Go with the Flow & Unplug Let the weekend unfold and don’t stress the little details. Allow yourself to be present and enjoy each moment and whatever it brings. Focus on what brings you pleasure and you’ll find the weekend to be rejuvenating and satisfying. Allow yourself to unplug while you’re away. Leave your phone behind and your computer at home. It’s only a weekend and the world will survive without you. MI ST LOG O I X of the Month mauro ramirez @ Crooked Pint Ale House 3340 13th Ave S, Fargo crookedpint.com/fargo Crooked Pint is one the newer restaurants to hit the Fargo-Moorhead area. Taking the space that once belonged to the Green Mill, the restaurant has locations in Minnesota, South Dakota and Grand Forks as well. While it is a smaller scale franchise in the Midwest, the food and drink is far from franchise style. A hand-crafted menu of food and drinks set this new restaurant apart from other new locales in the region. BY Nolan Schmidt PHOTOS BY Hillary Ehlen 52 | MAY 2018 | FARGOMONTHLY.COM Q&A GIVE US YOUR BARTENDING JOURNEY. WHERE DID YOU START AND HOW DID YOU GET HERE? THE WHISKEY SOUR CAN BE DONE SO MANY DIFFERENT WAYS, WHAT IS DIFFERENT ABOUT THE WHISKEY SOUR YOU MADE HERE? I actually didn't start as a bartender. I was a bouncer, I did security for the Pickled Parrot, but then I worked my way up into bartending there. I decided to then branch out here because of the selection available. The wide tap selection we have here, especially the scotches and whiskeys because I love whiskey. So I'm just not as limited on the things I can use in drinks. My spin on it is instead of using a lemon-lime sour mix, mine is just lime sour. From that, I add a little bit of strawberry puree, which isn't common. I combine all of that with a little bit of soda water. You get more of the sour with just the lime which kind of sets mine apart from other ones. It's a nice refreshing drink. WHAT HAS BEEN THE TREND WITH REGULARS IN TERMS OF DRINKS? WHAT DRINKS ARE YOU MAKING THE MOST ON A GIVEN NIGHT? SINCE YOU LOVE WHISKEY, WHAT OTHER EXPERIMENTATIONS ARE YOU DOING WITH THE WHISKEY AT CROOKED PINT? It's actually kind of funny because we are a new place, but the space isn't new. As a matter of fact, a lot of our regulars were regulars when this was still the Green Mill, so that's kind of interesting. As for the most popular drinks, it's actually just a simple scotch neat. I think that is because of how many scotch selections we have compared to other places. WHISKEY SOUR I'm trying to experiment with whiskey and tequila a lot. It goes well with lime flavors because lime compliments both of those so well already. So whenever I am making a whiskey drink (or tequila drink), I always wonder how it'll taste with a little bit of tequila (or whiskey) added in. That is kind of what I have been tinkering with a bit. • 1.5 oz of Templeton Rye Whiskey • 2 oz of Lime Sour • 0.5 oz of Strawberry Syrup 1,372 REPORTED INCIDENTS INVOLVING drugs IN CASS COUNTY. LAST YEAR, THERE WERE Kim Hegvik Mark Hendrickson These three are making an impact in trying to rid 54 | MAY 2018 | FARGOMONTHLY.COM THAT MADE UP NEARLY 20% OF ALL DRUG-RELATED REPORTS IN NORTH DAKOTA. BY Nolan Schmidt PHOTOS BY Hillary Ehlen N ic, 'If. Nicole Burkhartsmeier our community of drug offenses. ." 55 10 quick facts ABOUT DRUG COURT Since Juvenile Court’s inception in 2000, the State of North Dakota has seen 677 juveniles come through the program. As of 2017, Fargo leads the state with 88 juveniles completing the Juvenile Drug Court Program since May of 2000. 56 | MAY 2018 | FARGOMONTHLY.COM. MAYEVENT CALENDAR STAY UP-TO-DATE WITH WHAT’S GOING ON IN THE AREA. 1 Million Cups Every Wednesday from 9:15-10:15 a.m. Join the vibrant entrepreneurial community of Fargo-Moorhead and Emerging Prairie by participating in an event filled with guest speakers, plenty of coffee, ideas and excellent networking opportunities. 1millioncups.com/fargo The Stage at Island 333 4th St. S, Fargo Trans Mentor Program Carrie's Twisted Art. Every Thursday from 7-9 p.m. These public classes are a great place to learn painting techniques of all different types Every Saturday from noon-4 p.m. pridecollective.com Pride Collective and Community Center 314 Broadway N, Fargo 226 Broadway N, Fargo FirstLink's 10th Annual Breakfast Wednesday, May 2 at 7:30 a.m. Join us for a great breakfast to learn how FirstLink is working to end the stigma of mental illness and suicide through community education. myfirstlink.org Hilton Garden Inn Murder Mystery Dinner Theatre: Murder at the Banquet 1701 38th St. S, Fargo jadepresents.com Fargo Theatre jadepresents.com The Aquarium Grief Journeys For Men Support Group hrrv.org Hospice of the Red River Valley In support of their 3rd Public Television special, “Rockin’ Round the Clock,”s–1970s. kids' stolen bikes. 4351 17. May 3 & 4 at 8 p.m. Tuesday, May 1 at 7 p.m. 1105 1st Ave. S, Fargo Every third Tuesday of the month from 10-11:30 a.m. UNDER THE STREET LAMP Froggy Fresh Downtown Dogs Fargo Every Tuesday at 7 Friday Night Salsa at the Radisson Every Friday at 8 p.m. Free Admission. Complimentary 1hr Lesson in Either Salsa or Bachata at 8 p.m. Dance social 9 - 11:30 p.m. (Salsa, Bachata, Merengue, Kizomba). There will be drinks available at the bar (21+). The event is 18+. Come dance, hang out, meet cool people or just drink and watch others dancing. Wednesday, May 2 6:30 p.m. Join us for a night of intrigue, deception and delicious food at Santa Lucia Restaurant.. When the lights go out, a murder takes place. It’s time for Foster and Jenny to team up with an aging British sleuth, a forgetful gumshoe and a hillbilly sheriff to solve this crime. Santa Lucia Restaurant 1109 38th St S, Fargo Seek and You Shall Find: Spiritual Retreat May 4 & 5 at 7 p.m. Joann Nesser, founder and retired director of Christos Center for Spiritual Direction, retreat leader, spiritual formation teacher and author will lead us through short presentations, guided meditations, followed by time for personal prayer and reflection. If you have questions, contact Judy jsiegle@fargohope. org or at 701-235-6629. fargohope.org Hope Lutheran Church 3636 25th St S, Fargo Radisson Hotel 201 N 5th St, Fargo WHAT DOES IT MEAN? SPORTS FAMILY COMMUNITY OUTDOORS A&E 59 Wish Fast 5: Superhero 3, 5 & 10K Walk/Run Saturday, May 5 at 8 a.m. Assemble with other heroes. Come dressed as your favorite hero as we save the day from dastardly villains scattered throughout Urban Plains Park right next to Scheels Arena. Beat all the villains and help us grant more wishes FASTER for Make-A-Wish ND. Tons of great prizes. Stay tuned to the Facebook, Twitter and Instagram pages for more information. Mark your calendars. northdakota.wish.org Urban Plains Park 5050 30th Ave S, Fargo Mother's Day Art Market Saturday, May 5 at 10 a.m. The Arts Partnership is hosting another art market at APT, a Creative Incubator just in time for Mother's Day. From 10 a.m. – 2 p.m. Saturday, May 5, come shop from local artists and enjoy ‘mom’osas while the kids enjoy an art activity called “Mosses to Magnolias: The Evolution of Flowering Plants” with NDSU Geosciences. theartspartnership.net APT, a Creative Incubator 225 4th Ave N, Fargo "I Am, He Said" A Celebration of Neil Diamond Saturday, May 5 at 7 p.m. “I Am, He Said” A Celebration of the Music of Neil Diamond Starring Matt Vee showcases the songbook from a musical legend. Matt Vee is the nephew of 60’s pop star and Fargo’s own, the late Bobby Vee. With songs like “Cracklin’ Rosie,” “Song Sung Blue” and “Sweet Caroline,” Neil Diamond has sold over 100 million records worldwide and produced musical hits spanning five decades. jadepresents.com The Fargo Theatre 314 Broadway N, Fargo Rising Above Saturday, May 5 at 6:30 p.m. Dance recital of the McDonald School of Irish and International Dance. Featuring traditional dances of Ireland, creative Irish dance, dance from Eastern Europe, and special performance by CastleIsland musicians. fargocc.com Fargo Country Club 509 26th Ave S, Fargo Brewing Up Laughs Thursday, May 10 at 7:30 p.m. Fargo Brewing Company’s finest bi-weekly open mic has been a great time with local comics ranging from seasoned to beginners trying out there material. This is a great environment to watch comedy open mic or to even give it a try yourself and it’s totally free to attend. fargobrewing.com Fargo Brewing Company 610 University Dr. N, Fargo Jazz Nickel Combo Thursday, May 10 at 7 p.m. Enjoy classic and contemporary jazz standards featuring vocals, tenor sax, trombone, guitar, bass and drums. Free for all ages. urban42fargo.com Urban 42 1635 42nd St S, Fargo HOME FREE: TIMELESS WORLD TOUR Saturday, May 12 at 6:30 p.m. The all-vocal country sensation Home Free is bringing Nashville country standards and country-dipped pop hits back to Fargo. The band returns on the heels of their most recent full-length album release, Timeless, bringing with them new music, new jokes and new production. jadepresents.com Fargo Civic Center 207 4th St N, Fargo Bootcamp on Tap Friday, May 11 at 6 p.m. Jenny with Fargo FITLIFE will be on location at Fargo Brewing Company hosting a 30-minute bodyweight boot camp. No previous fitness experience needed. Get your sweat on and enjoy a local brew, all for only $10. Please bring a mat. fargofitlife.com Fargo Brewing Company 610 University Dr. N, Fargo Fabulously Female Saturday, May 12 at 9 a.m. It's time to treat those fabulous ladies in your life to a day of pampering. Fabulously Female is a day of fashion, fun and all-around fabulousness. Enjoy shopping, food & wine, free makeup applications, free hair styling, free massages and so much more. Avalon Events Center 2525 9th Ave S, Fargo MDA Muscle Walk Saturday, May 12 at 9 a.m. The Muscular Dystrophy Association is bringing strength to life for kids and adults in the North Dakota/Northern Minnesota community with muscular dystrophy, ALS and related muscle-debilitating diseases at the 2018 MDA Muscle Walk of FargoMoorhead. mda.org Moorhead Center Mall 510 Center Ave, Moorhead Cofresi Saturday, May 12 at 9 p.m. Cofresi pushes the boundaries of modern performance and production with a hybrid style and refreshingly versatile live dj/digital drum setup. In the studio he creates a unique sound that is provocative, melodic & rhythmic at its core. Live, his sets are full of energy as he showcases a unique ability to incorporate multidimensional digital and acoustic percussion into modern electronic music. of motorcyclists from the Midwest and beyond. Activities include fun runs, motorcycle games, free street dances and more. 226 Broadway N, Fargo The World in Fargo-Moorhead Monthly Meeting aquariumfargo.com The Aquarium Fargo Birding Festival Saturday, May 12 at 7 a.m See a variety of birds in a beautiful setting in South Fargo. Forest River is county owned land that birders can use. This festival is for all skill levels. If you are a beginner and plan on coming, consider taking Birding 101. fargoparks.com Forest River Property 76th Ave S & Red River, Fargo Junk Market May 12 & 13 at 10 a.m. A fun event that offers the best in repurposed furniture and vintage pieces—a wonderfully unique shopping opportunity that sparks creativity. fargojunkmarket.com Scheels Arena 5225 31st Ave S, Fargo Great Strides Fundraiser for the Cystic Fibrosis Foundation Saturday, May 12 at 10 Fargo-Moorhead. cff.org Oak Grove Park 170 Maple St Fargo Arc West Central Dances Monday, May 14th at 7:15 p.m. Join your friends for twice-monthly dances with a DJ. All are welcome. Sponsored by Arc West Central. arcwestcentral.org Ellen Hopkins Elementary 2020 11th St S, Moorhead Caroline Smith with Eric Mayson Tuesday, May 15 at 7 p.m. After. aquariumfargo.com The Aquarium 226 Broadway N, Fargo The Cavalier Motorcycle Ride-In Tuesday, May 15 & 16 at 8 a.m. The Cavalier Motorcycle Ride-In is a two-day event occurring every year. It attracts thousands cavaliermotorcycleridein.com Cavalier, North Dakota Wednesday, May 16 at 7 p.m. Current and new volunteers are invited to come together to discuss ways to get more stories for our social media. Photographers, story lovers and anyone who enjoys meeting community members are welcome to talk about ways that we can all share more stories and connect with a diverse community in FM. Fargo Public Library 102 3rd Street N, Fargo Nerd Nite Fargo Wednesday, May 16 at 7 p.m. Nerd Nite is a monthly lecture event that strives for a humorous, salacious, yet deeply academic vibe. It’s often about science or technology, but by no means is it limited to such topics. And it’s definitely entertaining. fargo.nerdnite.com Fargo Billiards & Gastropub 3234 43rd St S, Fargo River Paddling Excursion with Red River Trivia Wednesday, May 16 at 6 p.m. If you like to canoe or kayak and would like to learn more about the Red River, join us this summer as Moorhead Parks and Recreation and River Keepers host Red River Paddling Excursions from 6-8 p.m. at the Hjemkomst Landing. With Red River Trivia present, put a team together and play River related trivia. The team with the most correct answers will win a prize. People can also play individually. Hjemkomst Landing 202 1st Ave N, Moorhead The Used with Red Sun Rising Thursday, May 17 at 7 p.m. everlasting nature of the band’s music. jadepresents.com Sanctuary Events Center 670 4th Ave N. Fargo Outlet: Open Mic Poetry Night Thursday, May 17 at 7:30 p.m. Open Mic Slam Poetry night is the Third Thursday of Every Month at Fargo Brewing Company. This is a free event for the public. We are an inclusive and supportive group, so everyone is welcome, and after the lineup, there’s an open mic. fargobrewing.com Fargo Brewing Company 610 University Dr. N, Fargo America Friday, May 18 at 8 p.m. The year 2015 marked.” jadepresents.com The Fargo Theatre 314 Broadway N, Fargo FM Kicks Band Spring Concert Friday, May 18 at 7:30 p.m. FM Kicks Band presents classic and contemporary big band charts of Bill Potts, Woody Herman, Buddy Rich, Thad Jones, Allen Carter and more. Performing at the Stage in Island Park (FMCT). Tickets at the door $15 adults, $5 students, 10 and under free. fmct.org The Stage at Island Park 333 4th St S, Fargo FARGO MARATHON Saturday, May 19 Run fast, run friendly, run Fargo at this exciting annual Boston Marathon qualifier event. fargomarathon.com FARGODOME 1800 N University Dr, Fargo Nature Adventure Saturday, May 19 at 12 p.m. Bring the family out for National Kids to Parks Day for some outdoor fun. There will be food, crafts, games and nature activities. Rabanus Park 4315 18th Ave SW, Fargo Corb Lund with David Allen Saturday, May 19 at 8 p.m.. jadepresents.com Sanctuary Events Center 670 4th Ave N, Fargo The Black Dahlia Murder with Homewrecker Sunday, May 20 at 9 p.m. Any band that has earned an army of devout followers through dropping seven killer fulllengths could perhaps be forgiven for thinking they could take it easy as they wade into their eighth release. But that’s just not The Black Dahlia Murder’s style, and Nightbringers is testament to that. jadepresents.com The Aquarium 226 Broadway, Fargo PJ Masks Live! Time to Be a Hero Sunday, May 20 at 12 p.m. and 3 p.m. Entertainment One (eOne) and Round Room are proud to announce that ‘PJ Masks Live! Time to Be a Hero,’ the hit musical production, will head back to the stage, touring across North America starting in April 2018.. jadepresents.com Scheels Arena 5225 31st Ave S, Fargo FM Welcome Party Tuesday, May 22 at 6 p.m. We want to be the first ones. gfmedc.com Sanctuary Events Center 670 4th Ave N Fargo Fargo Brewing and Jade Presents: Nikki Lane with Carl Anderson Wednesday, May 23 at 7 p.m. Nikki Lane’s stunning third album Highway Queen, out February 17th, 2017, sees the young Nashville singer emerge as one of country and rock’s most gifted songwriters. Co-produced by Lane and fellow singersong. jadepresents.com Fargo Brewing Company 610 N University Fargo Anthrax & Testament Wednesday, May 23 at 7:15 p.m.. jadepresents.com Sanctuary Events Center 670 4th Ave N, Fargo Fargo CoreCon May 24-27 The very first CoreCon in 2009 began with a super theme: Heroes vs. Villains. As we approach our tenth anniversary, it seemed appropriate to bring that theme back with CoreCon X: Return of the Heroes, Revenge of the Villains. That’s right. We’re doing the same theme twice, but now we’re doing it better. Ten years of running conventions have taught us so much about what we did wrong in the first nine years. It’s also taught us just how much we did right. The area that we have always succeeded in is making CoreCon a convention by the fans, for the fans. We will continue to do that for the next ten years and on. fargocorecon.org Holiday Inn 3803 13th Ave S, Fargo Fargo-Moorhead RedHawks vs Lincoln Friday, May 25 at 7 p.m. 2018 opening night. Magnetic schedule giveaway and Post-Game fireworks brought to you by Shooting Star Casino. Inflatables in the playground brought to you by Games Galore. Series with Lincoln continues on May 26 & 27. fmredhawks.com Newman Outdoor Field 1515 15th Ave N, Fargo Post-Traumatic Funk Syndrome performs "Soul Train" Saturday, May 26 at 8 p.m. Post-Traumatic Funk Syndrome, Jade Presents and Sanctuary Events Center Present “Soul Train” – a tribute to the popular 1970s dance show, “Soul Train,” featuring selections from the bands that performed live on the show including: Earth Wind and Fire, War, Sly and the Family Stone, The Ohio Players, Commodores and more. jadepresents.com Sanctuary Events Center DOWN THE ROAD Daniel O' Donnell: Back Home Again Tour Saturday, June 2 at 6:30 p.m. jadepresents.com The Fargo Theatre 314 Broadway N, Fargo "Weird Al" Yankovoic at The Fargo Theatre Wednesday, June 6 at 7 p.m. jadepresents.com The Fargo Theatre 314 Broadway N, Fargo Book Fest Thursday, June 7 at 5 p.m. North Elmwood Park 500 13th Ave W, Fargo Bark in the Park Tuesday, June 12 at 5 p.m. wfparks.org North Elmwood Park 500 13th Ave W, Fargo 670 4th Ave N, Fargo Big Screen Movie Matinee Fargo-Moorhead RedHawks vs Sioux Falls wfparks.org Veterans Memorial Arena Monday, May 28 at 6 p.m. El Zagal Shriners Night. Special 6 pm start time for Memorial Day. $1 Cloverdale hot dog night. Series with Sioux Falls continues on May 29 & 30. fmredhawks.com Newman Outdoor Field 1515 15th Ave N, Fargo Diplo Thursday, May 31 at 9. jadepresents.com Sanctuary Events Center 670 4th Ave N, Fargo Thursday, June 13 at 1 p.m. 1201 7th Ave E, West Fargo Burgers, Brews & BBQ Festival Thursday, June 21 at 5 p.m. burgerfestfargo.com Moorhead Center Mall Parking Ramp 510 Center Ave, Moorhead The Everly Brothers Experience Friday, June 22 at 7 p.m. jadepresents.com The Fargo Theatre 314 Broadway N, Fargo Brian Regan Sunday, June 24 at 7 p.m. jadepresents.com The Fargo Theatre 314 Broadway N, Fargo Jonny Lang Thursday, June 28 at 7 p.m. jadepresents.com The Fargo Theatre 314 Broadway N, Fargo LISTEN TO THE MUSIC STAY ON THE SCENE WITH OUR GUIDE TO FARGO-MOORHEAD’S LOCAL MUSIC. MAY 1ST - 5TH TUESDAY, MAY 1 Froggy Fresh - The Aquarium The Cropdusters - Junkyard WEDNESDAY, MAY 2 Escape From the Zoo - The Aquarium Jan Severson - Junkyard THURSDAY, MAY 3 Chameleon Moonflower - HoDo Dylan Boehmer - Front Street Taproom Kathie Brekke and 42nd Street Band Delta by Marriott October Road - The Windbreak Rob Black Band - Junkyard FRIDAY, MAY 4 Portland Junction - Spirits Lounge Poitin - Dempsey's Deadbeats - Lucky's 13 64 | MAY 2018 | FARGOMONTHLY.COM Brothers Bertrand - Front Street Taproom Blue English - Alibi Lounger Downtown Sound - Pickled Parrot Some Shitty Cover Band - The Windbreak GC & The Kruse - Junkyard 24 Seven - Shotgun Sally's Pretty Tricky - Rick's Confusion - Speck's Jon Walters - Drekker SATURDAY, MAY 5 Portland Junction - Spirits Lounge The Fattening Frogs - Dempsey's Rage Against The Machine Tribute The Aquarium Blue Tonic - Lucky's 13 DJ AP - Front Street Taproom Downtown Sound - Pickled Parrot The Front Fenders - Delta by Marriott 32 Below - The Windbreak Redline - J.C. Chumley's Jesse Eugene - Junkyard Judd Hoos - Shotgun Sally's Pretty Tricky - Rick's Confusion - Speck's Bobby Peterson - Drekker MAY 6TH - 12TH SUNDAY, MAY 6 Phobophillic, Brutalur and Triple Deke - The Aquarium Open Mic Night w/ Jam band - The Windbreak Sixth Annual Acoustic Fest - Bar Nine Hot Lunch - Junkyard MONDAY, MAY 7 Pleasures, Electric Blankets - The Aquarium Jessica Vines & Connor Lee - Junkyard TUESDAY, MAY 8 The Dead South - The Aquarium Charlie Young - Junkyard WEDNESDAY, MAY 9 Sub:Culture - The Aquarium Fargo-Moorhead Jazz Orchestra Dempsey's Bolder Shades of Blue - Junkyard Step Rockets with special guest Face for Radio - Shotgun Sally's Electric Eye “ Judas Priest Tribute” with Rokken - The Garage Bar Presents Matt Johnson - Drekker THURSDAY, MAY 10 Wayne McArthur - blvd Pub Raspberry Jam: A Tribute to Carole King - HoDo Afroman - The Aquarium Jack and Kitty - Front Street Taproom The Jazz Nickel - Delta by Marriott Tripwire - The Windbreak Rick Adams - J.C. Chumley's Tristan Larson - Junkyard SUNDAY, MAY 13 By the Thousands - The Aquarium Open Mic Night w/ Jam Band - The Windbreak Beer & Hymns w/ Olivet Lutheran Church - Junkyard FRIDAY, MAY 11 Uptown - Dempsey's Secret Recipie - The Aquarium John Janousek - Lucky's 13 Treo'Soul - Front Street Taproom Quick 56 - Alibi Lounge Contention - Pickled Parrot Kathie Brekke - Rosey's Tripwire w/ Special Guest At The Emporium - The Windbreak Tate McClane - Junkyard Redline - Shotgun Sally's Liquored Up - Speck's Ali Rood - Drekker SATURDAY, MAY 12 The Low Standards - Dempsey's Confresi - The Aquarium Cropdusters - Lucky's 13 Charlie Young - Front Street Taproom Quick 56 - Alibi Lounge Contention - Pickled Parrot The Dead Beats - Delta by Marriott Rock Godz - The Windbreak Nathan Pitcher - Junkyard Wicked Garden - Shotgun Sally's Liquored Up - Speck's MAY 13TH - 19TH MONDAY, MAY 14 Amanda Standalone - Junkyard TUESDAY, MAY 15 Caroline Smith - The Aquarium The Cropdusters - Junkyard WEDNESDAY, MAY 16 Sub:Culture - The Aquarium Dose Amigos - Junkyard THURSDAY, MAY 17 The Blue Wailers - HoDo Sons of Mars - The Aquarium Dose Amigos - Front Street Taproom Kathie Brekke and 42nd Street Band Delta by Marriott Two Way Crossing - The Windbreak Sista Otis - Junkyard FRIDAY, MAY 18 Dakota Dirt - Spirits Lounge Kapeesh - Dempsey's Big Wu - The Aquarium Paul Seeba - Lucky's 13 Sista Otis - Front Street Taproom Someday Heroes - Alibi Lounge FM Allstars - Pickled Parrot Two Way Crossing - The Windbreak Anthony Chaput - Junkyard October Road - Shotgun Sally's Brutalar - Rick's Social Disorder - Speck's Dearly Departed with Know Signal, Barnaby Jones & Grime - The Garage Bar Presents Ciro de la Garza - Drekker SATURDAY, MAY 19 Dakota Dirt - Spirits Lounge Confusion - Dempsey's Dead Larry - The Aquarium Cropdusters - Lucky's 13 Lacey Guck - Front Street Taproom Mick $ Rich - Alibi Lounge FM Allstars - Pickled Parrot The Front Fenders - Delta by Marriott Slamabama - The Windbreak Robert Hunter - Junkyard The Roosters - Shotgun Sally's StoneShifter & High Gear (2 Bands) Rick's Social Disorder - Speck's Fixated with License To Kill, Sons Of Mars & Ashes From Stone - The Garage Bar Presents MAY 20TH - 26TH SUNDAY, MAY 20 The Black Dahlia Murder - The Aquarium Open Mic Night w/ Jam Band - The Windbreak Beer & Hymns w/ Good Shepherd Lutheran Church - Junkyard MONDAY, MAY 21 Senses Fail - The Aquarium Matty J - Junkyard TUESDAY, MAY 22 Al Scorch - The Aquarium The Cropdusters - Junkyard 65 WEDNESDAY, MAY 23 Sub:Culture - The Aquarium Pat Lenertz Duo - Junkyard THURSDAY, MAY 24 The Human Element - HoDo Todd Sisson - Front Street Taproom Harley Sommerfeld Quintet - Delta by Marriott Rhyme or Reason - The Windbreak Patrick Murphy - J.C. Chumley's Megan Johnson - Junkyard FRIDAY, MAY 25 DJ Shawn Who - Dempsey's Sub:Culture Two-year Anniversary - The Aquarium Big and Hungry - Lucky's 13 John and Sean - Front Street Taproom Joe Dretsch - Alibi Lounge Dance Party - Pickled Parrot Rhyme or Reason - The Windbreak Tucker'd Out Duo - Junkyard Dirty Word - Shotgun Sally's Sidewinder - Speck's Future Leaders Of The World with VIA, Gravity Zero, JAG & The Everyday Losers - The Garage Bar Presents Jacob Ingamar - Drekker SATURDAY, MAY 26 DJ Duster - Dempsey's John Janousek - Lucky's 13 Falcon's Flight - Front Street Taproom Dance Party - Pickled Parrot The Dead Beats - Delta by Marriott Roosters - The Windbreak Dan Christianson - Junkyard Brat Pack Radio - Shotgun Sally's Sidewinder - Speck's Ditching Delmer - Drekker MAY 27TH - 31ST MONDAY, MAY 28 Jackie Rae Daniels - Junkyard TUESDAY, MAY 29 Rockin' Johnny Burgin - Junkyard WEDNESDAY, MAY 30 Sub:Culture - The Aquarium Kwaician - Junkyard THURSDAY, MAY 31 Post Traumatic Funk Syndrome - HoDo A Tribute to John Prine w/Matty J and Pat Lenertz - Front Street Taproom Kathie Brekke and 42nd Street Band Delta by Marriott Tyler Hammond - The Windbreak Gina Powers - Junkyard Blacklite District - The Garage Bar Presents SUNDAY, MAY 27 Open Mic Night w/ Jame Band - The Windbreak Beer & Hymns w/ Trinity Lutheran Church - 1340 21st Ave. S, Fargo 226 Broadway N, 2nd Floor, Fargo 1405 Prairie Pkwy, West Fargo 3147 Bluestem Dr, West Fargo 1635 42nd St S, Fargo 226 Broadway N, Fargo DREKKER BREWING COMPANY 630 1st Ave. N, Fargo 66 | MAY, ND 1515 42nd St. S, Fargo 2611 Main Ave, Fargo 3803 13th Ave. S, Fargo THE WINDBREAK 3150 39th St. S, Fargo DRINKSPECIALS, 8-11pm: $2 domestic bottles for everyone 8-11pm: $2 tall taps, wells & teas 50¢ taps, $1 Captain Morgan and teas 8pmmidnight 2-for-1 domestic bottles, Jack & Jack Honey 8pm-midnight 7-9pm: $7 all you can drink, 9-11pm: $2.50 tall taps, teas, Morgans & bomb shots 7-9pm: 79-cent teas, 9-11pm: $2.50 tall taps, teas, Morgans & bomb shots The Bowler 2630 University Drive S, Fargo Happy Hour 4-7pm, Patron shots $3.50 all day Happy Hour 4-7pm, $3.00 domestic pounders from 9 to 11pm. Ice Hole shots $3.50 all day Happy Hour 4-7pm: drinks as low as 50¢, pull tab Happy Hour replay 9-11pm. Goldschlager shots $3.50 all day Happy Hour 4-7pm, Captain Morgan at $3.00 from 9-11pm. Jagermeister shots $3.50 all day Happy Hour 4-7pm, Windsor at $3.00 from 9-11pm. Romana Sambuca shots $3.50 all day Happy Hour 4-7pm, Titos Vodka $3.50 from 9-11pm. Jose Cuervo shots $3.50 all day Happy Hour 4-7pm, $6.00 pitchers from 9-11pm. Rumpleminze shots $3.50 all day. Service Industry Sundayonday 8pmclose: $5.95 new mug, $3.95 refills 8pm-close: $1 off taps & wells (including craft beers) Big Mug Wednesday 8pm-close: $5.95 new mug, $3.95 refills, $1 off Captain Morgan 8pm-close: 50¢ Busch Light Taps, $2.95 Ice Hole & Fireball Beer & A Bump Night 8pmclose: domestic beer & a shot for $7, $2.95 Old School Long Island Teas & Stumplifters 8am-noon: $2.95 Bloody Mary’s & Caesars, 8pm-close: $3.95 Crown Royal, $2.95 PBR & Busch Light pounders Sunday Funday 12pm-2am: $1 Off all drinks in your Chub's gear Acapulco 1150 36th St. S, Fargo The Bismarck Tavern * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. The Box 1025 38th St. SW, Fargo (Inside the Fargo Inn & Suites) 69 MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY Dempsey’s 226 Broadway N, Fargo $3.50 Bacardi, Malibu and Morgan starting at 9pm $2.50 domestic taps and well drinks starting at 9pm Old School Night starting at 9pm: $3 Old Style, High Life and Hamms $4 specialty or import bottled/ tap beer starting at 9pm $3.50 Old Style and $5.25 Jameson starting at 9pm $3.50 Old Style and $5.25 Jameson starting at 9pm Happy Hour prices 4-7pm, employee prices for all 7pmclose D’Woods Lounge 3333 13th Ave. S, Fargo $2.75 domestic bottles, $3 Bacardi $2.75 domestic bottles, $1 off Martinis $3.50 Stoli and domestic taps $3.50 Crown Royal and taps $3.75 teas, $3 Windsor $3 Smirnoff and Captain Morgan ½ off all bottles of: $1 off tap and bottled beer, cocktails and wine by the glass $3 off wine flights 3-9pm, Happy Hour 3-6pm and 9pm-close: $1 off Happy Hour All Day ($1 off all Taps, Wells, and Domestic Bottled Beer). 3 for 1’s from 7-10pm Domestic Taps and Well Drinks (made in plastic cups) Happy Hour 4-7pm: $1 off all Taps, Wells & Domestic Bottles. $3.50 Stoli Flavors (adding some juices and energy drinks is an up charge). $3.50 Icehole Flavors and Fireball shots. $2 Well Drinks & Domestic Bottles (8-10pm) $4 Bloody Mary’s and Caesar’s (26pm). $3.50 Chuck Norris & Jag Bomb Shots. $3.50 Select Rums (Morgan, Bacardi Flavors, Don Q, Sailor Jerry and Malibu). $2 Well Drinks & Domestic Bottles (8-10pm) All Specials from the week apply (excludes $2 wells and Domestics) . Fort Noks Bar of Gold 52 Broadway N, Fargo Happy Hour 4-7pm: $1 off all Taps, Wells & Domestic Bottles. Bucket of Beers $15 (Any 5 Beers). $4.50 Long Islands & Margaritas Happy Hour 4-7pm: $1 off all Taps, Wells & Domestic Bottles. $3.50 Tap Beers all day (Pint glasses) Happy Hour 4-7pm: $1 off all Taps, Wells & Domestic Bottles. $3 Select Whiskeys and $3 Import and Domestic Microbrew bottles all day. 1/2 price bottles of wine Frank’s Lounge 2640 52nd Ave. S, Fargo Happy Hour 4-6pm and 9pmmidnight: $1 off spirits, wine and beer Happy Hour 4-6pm and 9pmmidnight: $1 off spirits, wine and beer and half price wine glasses and bottles Happy Hour 4-6pm and 9pmmidnight: Mulligan Monday: 2-for-1 taps Twosday: $2 domestic bottles Apple Winesday: Half price appetizers and | MAY 3pm-close: $2.95 U-Call Its, Happy Hour 3-7pm: $2.95 premium well drinks, domestic taps & bottled beer All day: $3.50 jumbo teas, $5.25 top shelf, Happy Hour 3-7pm: $2.95 premium well drinks, domestic taps & bottled beer 8pm-close: 32oz mugs $3.95, Happy Hour 3-7pm: $2.95 premium well drinks, domestic taps & bottled beer F&F Poor Boy Pounders $2.95/$3.25, Happy Hour 3-7pm: $2.95 premium well drinks, domestic taps & bottled beer 9pm-close: $1 off domestic bottled beer & premium well, Happy Hour 3-7pm: $2.95 premium well drinks, domestic taps & bottled beer 11am-3pm: $3.95 mimosas, screwdrivers & bloodies, 9pm-close: $1 off domestic bottles & premium well drinks, Happy Hour 3-7pm Lucky’s 13 Pub 4301 17th Ave. S, Fargo $2.50 short domestic beers $3 Coronas, Corona Lights and Dos Equis Amber 3pmclose glass or bottle of any wine and get the 2nd for a penny Bucket Special 4-10pm: U-Pay-The-Day tap beer 8-10pm, 9-11pm: $2.75 OB Beers, Booze & Bombs 1-U-Call-It on tap beer, bottles and drinks 7-9pm, 9-11pm: $2.75 OB Beers, Booze & Bombs O’Kelly’s 3800 Main Ave., Fargo Old Broadway City Club 22 Broadway N, Fargo Old Broadway Grill 22 Broadway N, Fargo OB Sport Zone 22 Broadway N, Fargo Pickled Parrot 505 3rd Ave. N, Fargo 72 | MAY 2018 | FARGOMONTHLY.COM Happy Hour 3-6pm: $2 rail & call drinks, select tap & bottled beer, $4 house wines Happy Hour all day $2.95 Bloody Marys, Mimosas, Skip-N-Go Naked 11am-2pm Wine Night from 4-9pm Happy Hour 3-6pm: $2 rail & call drinks, select tap & bottled beer, $4 house wines, 6-10pm $5.95 domestic pitchers Happy Hour all day, $1.25 off all drinks and $3 Mimosas Happy Hour 3-6pm: $2 rail & call drinks, select tap & bottled beer, $4 house wines. Extended Happy Hour from 6-10pm Happy Hour 3-6pm: $2 rail & call drinks, select tap & bottled beer, $4 house wines Happy Hour 3-6pm: $2 rail & call drinks, select tap & bottled beer, $4 house wines, 9-11pm $2.75 beers, booze & bombs 11am-2pm $2.95 Bloody Marys & mimosas, 9-11pm $2.75 beers, booze & bombs $5 Domestic Jars, $3 Captain Morgan & Tootsie Pops $2 Domestic Taps (7-10pm), $3 Domestic Bottles & Ice Hole, $8 Well Jars $5 Domestic Jars, $3.50 Fireball, $4 Crown Royal until 10pm $5 Domestic Jars, $4 Jack Daniels, Long Island Teas & Chuck Norris until 10pm 11am-2pm $2.95 Bloody Marys & mimosas Porter Creek Hardwood Grill 1 555 44th St. S, Fargo MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY Happy Hour 3-6pm and 9pm-close: $1 off cocktails, beer and wine Happy Hour Specials, 3-6pm & 9-Close; $4 Moscow Mules, $5 40oz beers, $6 32oz Frutopias Fargo's Best Build Your Own Bloody Mary & Mimosa bar! $9 Fargo's Best Build Your Own Bloody Mary & Mimosa bar! $9 $2 off Mimosas, Bloody Marys and Caesars $2 off Mimosas, Bloody Marys and Caesars $3 Deep Eddy Vodka starting at 8pm, Happy Hour 3-6pm and 10pmclose $4 craft beer pints and 2-for-1 wells starting at 9pm Bloody Mary Bar 11am-4 pm, $5 well vodka, $6 premium vodka, $3 you-call-its for service industry all day $3.35 tall domestic taps all day $2.75 well drinks 4:30pm-close Happy Hour Happy Hour Happy Hour Happy Hour 3-6pm and 9pm3-6pm and 9pm3-6pm and 9pmPounds 3-6pm and 9pmclose: $4 signature close: $4 signature close: $4 signature close: $4 signature 6 12 1st Ave. N, Mules, $5 40oz Mules, $5 40oz Mules, $5 40oz Mules, $5 40oz Fargo bottle beers and $6 bottle beers and $6 bottle beers and $6 bottle beers and $6 32oz Fruitopias 32oz Fruitopias 32oz Fruitopias 32oz Fruitopias $2 off Margaritas $2 off all top shelf liquors $2 off all glasses of wine and half price bottles $3 craft and import beers, $2 domestics and $1 off taps Rhombus Guys 606 Main Ave., Fargo Happy Hour 3-6pm and 10pmclose: close $4 pints of Rhombus beer starting at 9pm, Happy Hour 3-6pm and 10pmclose Rooter’s Bar 107 Broadway N, Fargo $2 12oz. domestic Sickie's Garage 3431 Fiechtner Drive S, Fargo Happy Hour 3-6 pm. and 9-close: : $1 off domestic pints, wells, and wine, $2 off domestic talls, $2 off featured craft brews. Radisson 201 5th St. N. Fargo The Round Up Saloon 4501 Urban Plains Drive, Fargo 74 | MAY 2018 | FARGOMONTHLY.COM MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY .25 Happy Hour bottles, $3 Captain Morga 6-10pm: $8.50 domestic pitchers, $3 wells and Ice Hole shots 6-10pm: $2.75 Schnapps shots, $3.75 Gator Teas and import bottles 6-10pm: $3 Bacardi and Windsor, $3.50 Chuck Norris or Jag Bombs Noon-10pm: $3.25 Happy Hour pints and bottles, $1 off whiskeys, $4.25 Bloody Marys Noon-10pm: $3.25 Happy Hour pints and bottles, $1 off whiskeys, $4.25 Bloody Marys -5pm $2 off jumbo 32oz. Margaritas $2 off PBR pounders, $1 off Mojitos $1 off Proud Mary Pina Colada $2 off all tequila shots $1 off Cadillac Margaritas, $2 Margaritas 9pmclose $1 Let's Get It On Lemonades, $1 Sangria, $2 off Margaritas 9pmclose 9-10pm: everybody drinks free, 1011pm: $2 drinks, 9-11 pm: $2 bomb shots 9-11pm: $2 drinks and bomb shots 9pm-midnight: $3 drinks and 2-for-1 shots Slammer’s Sports Bar & Grill 707 28th Ave. N, Fargo Twist 220 Broadway N, Fargo VFW: Downtown 202 Broadway N, Fargo * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. Vinyl Taco 520 1st Ave. N, Fargo Happy Hour all day, Stoli and Jack Daniel's $1 off all taps and bottled beers Mug Night: $5 purchase and $4 refills on domestics and wells WEST FARGO Bar Nine 1405 Prairie Pkwy., West Fargo 75 MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY Blarney Stone 1910 9th St. E, West Fargo. $4.50 Irish Trash Cans. Late Happy Hour from 9-close: $2.00 off drafts, $2.50 Bar Pours, $1.00 House Wine. All Day: $1.00 off Drafts, $2.50 Bar Pours, $1.00 off House Wine. Blvd Pub 3147 Bluestem Drive, West Fargo Happy Hour 3-6 8am-noon: Bloody Bar, $4 Bloodys, $3.50 mimosas, 7-close: $3.50 shots of Fireball and Icehole including flavors Happy Hour all day: $1 off talls, wells, and glasses of wine, Server Industry Day: $1 off all drinks with Server Training card, blvd Apparel Day: $1 off all drinks while wearing blvd Gear (max of $2 off) Hooligans 3330 Sheyenne St, West Fargo Mug Night: $7 mug and fill, $3 domestic and $5 non-domestic refills $4 tall domestic taps, half-price bottles of wine $2.50 domestic bottles Tea Night: $5 colossal teas $3.50 well drinks all day $2 pounders, domestic pitcher and a large pizza for $20 $8 pitchers of beer, $8.99 ultimate Bloody Marys, $3 Mimosas Pub West 3140 Bluestem Drive, West Fargo $3.50 tall domestic beer, $4.50 tall craft beer Happy Hour 3-6:30pm, 8pmmidnight: $7.50 Coors Light pitchers and $3.75 Crown Royal Happy Hour 3-6:30pm, 8pm-midnight: $7.50 Miller Lite pitchers, $3 Jack Daniels and Jag, $3.75 Long Island Teas Happy Hour 3-6:30pm, 8pmmidnight: $7.50 Bud Light pitchers, $3.50 Windsor and Smirnoff 8pm-midnight: $3 Fireball, $3.50 Tito's Vodka, $5 Vodka Red Bulls, $3.50 Chuck Norris, Ninja Turtles and Jag Bombs Happy Hour noon-6:30pm, 8pm-midnight: $3 import bottles and Tarantula Tequila, $3.50 Captain Morgan, Bacardi and Jameson Happy Hour all day, Service Industry Night 10pm-close: $3 well drinks Silver Dollar Flying Pig 221 Sheyenne St, West Fargo Happy Hour 4-6:30pm Happy Hour 4-6:30pm Happy Hour 4-6:30pm Happy Hour 4-6:30pm Happy Hour 4-6:30pm Happy Hour 4-6:30pm Happy Hour 4-6:30pm Three Lyons Pub 675 13th Ave. E, West Fargo Mug Night: $2 32oz. mug, fill for the price of a pint 7pm-close $3 you-call-its on domestic pints and wells 7pm-close Tall beers for the price of short 7pm-close $3 glasses of house wine, all Martinis $5 7pm-close $3.50 Jameson and $1 off bottled beer 8pm-close $4 Milagro Margaritas 8pm-close, $3.50 Bloody Marys, Caesars and Mimosas until 6pm Happy Hour All Day Town Hall Bar 103 Main Ave. W, West Fargo $3 Captain Morgan, $3.50 Crown Royal & Washington Apples 7-11pm $3 32oz. domestic Mongo Mugs, Ladies night $1 off drinks, $3 shots 7-11pm Happy Hour 3-7pm, $3 Windsor and Wu Tang shots 7-11pm $3 Cristal & Limon, domestic pitchers $6 7-11pm Tru Blu Social Club 915 19th Ave. E, West Fargo $5 Tru Tap Mules, 3-6 p.m. and 10 p.m.-1am: $1.25 off all liquor, wine and beer $3 off all Martinis, 3-6pm and 10pm-1am: $1.25 off all liquor, wine and beer Half price bottles of wine, 3-6pm and 10pm-1am: $1.25 off all liquor, wine and beer $2.75 16oz. domestic taps, 3-6pm and 10pm-1am: $1.25 off all liquor, wine and beer 3-6pm: $1.25 off all liquor, wine and beer 11am-4pm: $6 Deviled Bloody Mary's, $2.50 Mimosa Flutes, $9 Mimosa carafes 11am-4pm: $6 Deviled Bloody Mary's, $2.50 Mimosa Flutes, $9 Mimosa carafes Rookies 715 13th Ave. E, West Fargo * This is not a full list of specials. Specials subject to change. For updated and entire list of specials, go fargomonthly.com. 76 | MAY 2018 | FARGOMONTHLY.COM Happy Hour 3-6:30pm, 8pmmidnight: $3 domestic pitchers and Shiner Bock bottles, $3.50 Deep Eddys, $4 Angry Balls shot MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY VFW: West Fargo 308 Sheyenne St., West Fargo $2.50 regular domestic beers and Windsor 12 inch pizza and a pitcher of beer for $11 $3 Bacardi,-6:30pm: $2.50 domestic taps, bottles & wells, 8-10pm: strawberry or lime margaritas, $3 well or $5 premium, 8pmmidnight: $4 Busch mugs, $5 all other domestic mugs Happy Hour all day, 11ammidnight: $2.50 domestic bottles, taps & wells Happy Hour 4-6:30pm: $2.50 domestic taps, bottles & wells, 8pm-midnight: $4 Busch mugs, $5 all other domestic mugs, $5 premium long island teas Happy Hour 4-6:30pm: $2.50 domestic taps, bottles & wells, 8pm-midnight: $3.50 taps of Bud & Bud Light, $1 off import pints Happy Hour 4-6:30pm: $2.50 domestic taps, bottles & wells, Fireball Friday 5 p.m.-midnight: $3.50 Fireballs, 8-10 pm: $3 domestic bottles & Morgan 11am-4pm: $2 Mimosas and $5 Bloody Mary's & Caesars Game Day! $5 Bloody Mary's & Caesars Jerry's Original Music Club 1500 11th St. N, Moorhead 7pm-midnight: $3 Captain Morgan, $4 Jack Fire shots, $3 Fireball shots, Happy Hour 4pm-7pm: $3.25 16oz taps, $3.25 single-shot rails 7pm-midnight: $1 12 oz domestic taps, $4 Jack Fire shots, $3 Fireball shots, Happy Hour 4pm-7pm: $3.25 16oz taps, $3.25 single-shot rails 7pm-midnight: $4 Jack Fire shots, $3 Fireball shots, ladies get free domestic taps and wells with $10 cover, Happy Hour 4pm-7pm: $3.25 16oz taps, $3.25 single-shot rails 7pm-midnight: $5 domestic pitchers, Mick’s Office 10 8th St. S, Moorhead $2.50 Captain Morgan, $4 domestic mug fills, $4 bomb shots 8pm-midnight $3 domestic pints, $3.50 select import pints 8pmmidnight Ladies Night 8pm-midnight: $2.50 pounders and you-call-its $2.75 wells, $4 domestic mugs, $3 Busch Light and Old Style mugs, jell-o shot raffle 10pm-close $2.75 pounders, $3 Ice Hole 8pm-midnight $5 endless Mimosas 11am4pm, $8 pitchers 11am-4pm 1-7pm, $4 scratch teas Happy Hour 1pm-midnight Happy Hour 1-7pm, $5 all-you-can-drink for ladies 9pmmidnight, $3 pounders (all day) $2 Captain Morgan & $3 bomb shots 9pm-midnight Happy Hour 1-7pm, $3 perfect pint of Guinness and Irish car bombs 9pmmidnight Happy Hour 1-7 pm, 11am-2pm: $10 all-you-can) Happy hour all day till 7/ ladies night 9-midnight Late night Happy Hour 9pm-midnight $8.50 pitchers all day Bloody Mary specialpm-midnight 2-for-1s 4-6pm $5.25 pitchers of Budweiser, Mich, Amber Boch, Bud Light, Miller Light and Foster, drink specials 4-6pm $3.25 Morgan 2 for 1's 9-midnight $1.00 off All Whiskey Vic’s Bar & Grill 427 Center Ave, Moorhead Happy Hour all day: 50¢ off all drinks, $4 Bloody Marys and Caesars 77 THELASTPAGE Awake! Jazz & Poetry Lounge R itchell Aboah was dying for a slice of East coast culture when she moved to Fargo. She recalled the vibrant music and nightlife she had once experienced and noticed there was a problem. Not only did Fargo lack a creative space for people to showcase their work, but there was no place to listen to live jazz. That was when she realized that Fargo needed a jazz and poetry club. Now, a building has been found in West Fargo and it has a name, “Awake! Jazz and Poetry Lounge.” Aboah says she surveyed several students on the campus of NDSU, gauging their interest in a space of this sort. The results were surprising, “People were saying how great of an idea this was and how they would totally come to a place like this,” Aboah said. “I never thought many people my age were interested in this kind of environment. I always thought they enjoyed the music of our generation, not classical jazz and poetry.” The younger generation is the demographic Aboah is trying to reach. “My target market is young adults and “I want musicians, artists and anyone who is fascinated by this idea to contact me and join me on this journey.” urban youth," she said. Aboah's plan is to have the club be a cafe during the day with a coffee bar. It would turn into a nightclub in the evenings as the space already has a full service bar (from the previous tenants) which Aboah says she would hate to waste. Other amenities will include a fireplace, a private room and possibly a full kitchen. However, Aboah has not made a decision regarding the kitchen, but the building does have space set aside for it. INTERESTED IN HEARING MORE? Contact Ritchell Aboah. ? PHOTO COURTESY OF Ritchell Aboah You can find the club at 1410 9th St West in West Fargo which is where the Pickled Parrot West used to be. Although renovations and updates need to occur, Aboah foresees a June opening for the club. If not June, expect to see the blue fluorescent lights out front to be turned on sometime this summer. Regardless, there will soon be a live jazz club opening in a budding corner of West Fargo. awake.llc@yahoo.com aboah25@gmail.com. 78 | MAY 2018 | FARGOMONTHLY.COM Do you ever feel like you need to get out of Fargo-Moorhead for a few days? Maybe your 9 to 5 is running you into the ground? If so, you're... Published on May 1, 2018 Do you ever feel like you need to get out of Fargo-Moorhead for a few days? Maybe your 9 to 5 is running you into the ground? If so, you're...
https://issuu.com/fmspotlight/docs/fm_may18_final
CC-MAIN-2021-31
refinedweb
16,401
71.85
Details - Type: Wish - Status: Closed - Priority: Major - Resolution: Won't Fix - Affects Version/s: None - Fix Version/s: None - Component/s: None - Labels:None Description I like groovy but the groovy-all*.jar is too big. sth should do now. there are so many source code is for java1.4, we can rewrite them in java 1.5 to make groovy slim. for example: src/main/org/codehaus/groovy/runtime/ArrayUtil.java (ArrayUtil.class 1,093,546B) src/main/org/codehaus/groovy/reflection/MethodHandle.java src/main/org/codehaus/groovy/runtime/callsite/AbstractCallSite.java we can reduce ArrayUtil.class to 909B!!! if we rewrite like this: public class ArrayUtil { private static final Object[] EMPTY = new Object[0]; public static Object[] createArray() { return EMPTY; } public static Object[] createArray(Object... args) { return args; } } 1,759 KB groovy-all-1.0-JSR-06.jar 2,238 KB groovy-all-1.0.jar 2,762 KB groovy-all-1.5.4.jar 2,775 KB groovy-all-1.5.5.jar 2,784 KB groovy-all-1.5.6.jar 4,536 KB groovy-all-1.6.3.jar 4,399 KB groovy-all-1.6.4.jar 4,448 KB groovy-all-1.6.7.jar 4,054 KB groovy-all-1.6.jar 4,922 KB groovy-all-1.7-beta-2.jar 5,119 KB groovy-all-1.7.1.jar 5,165 KB groovy-all-1.7.2.jar Issue Links - depends upon GROOVY-3968 Use Pack200 for further streamlining the Groovy JARs - Closed GROOVY-4160 Gradle build - Closed GROOVY-1712 Source and test reorganization and Groovy core / gdk artifacts - Closed - relates to GROOVY-3366 reduce method variants in org.codehaus.groovy.runtime.ArrayUtil - Closed Activity - All - Work Log - History - Activity - Transitions I made a test, use "ArrayUtil.createArray" and "Variable Arguments" to process 5 int , 5 string , 17string for 100,000,000 times。It shows when argument count little ArrayUtil is faster than "Variable Arguments"(but only very little). when count becomes big, VA is more faster. Here is result( ArrayUtil2 Use VA): 5 int ArrayUtil use 2984 5 int ArrayUtil2 use 3016 5 string ArrayUtil use 2453 5 string ArrayUtil2 use 2703 17 string ArrayUtil use 8000 17 string ArrayUtil2 use 6875 test for ArrayUtil and VA(ArrayUtil.java not in it) compile them and run "java -cp . ArrayTest" we decided to keep the class till Groovy 3. The purpose is actually only partially the maybe higher speed you can directly see in a microbenchmark. It is to reduce the bytecode size, since you save using all the index entries to create the array. Anyway... Groovy 3 will go a different way here and won't need this class anymore. Se also GROOVY-5483 one more word on the size. Yes, it is a big class, but it is well compressed and thus makes only a minimal difference for the size of the jar This ArrayUtil class was generated in that way for some performance reasons. Sometimes there are tradeoffs. Anyway, we're planning to change our build and make Groovy more modular, so that users can pickup just what they need. We could also use Pack200 for better packing the JAR(s), to diminish its(/their) overal size(s). JAR size is less of a concern nowadays, with our huge hard drives, unless perhaps you're on some mobile device, in applets/web start apps, or in embedded systems with strong space/memory constraints?
https://issues.apache.org/jira/browse/GROOVY-4157?focusedCommentId=217303&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-48
refinedweb
577
59.9
Quantitative financial timeseries analysis Project description A Domain Specific Language for Timeseries Analysis. – – Timeseries analysis and a timeseries domain specific language written in Python. Timeserie Object To create a timeseries object directly: >>> from dynts import timeseries >>> ts = timeseries('test') >>> ts.type 'zoo' >>> ts.name 'test' >>> ts TimeSeries:zoo:test >>> str(ts) 'test' DSL At the core of the library there is a Domain-Specific-Language (DSL) dedicated to timeserie analysis and manipulation. DynTS makes timeserie manipulation easy and fun. This is a simple multiplication: >>> import dynts >>> e = dynts.parse('2*GOOG') >>> e 2.0 * goog >>> len(e) 2 >>> list(e) [2.0, goog] >>> ts = dynts.evaluate(e).unwind() >>> ts TimeSeries:zoo:2.0 * goog >>> len(ts) 251 Requirements There are several requirements that must be met: - python 2.5 or later. Note that Python 3 series are not supported yet. - numpy for arrays and matrices. - ply the building block of the DSL. - rpy2 if an R TimeSeries back-end is used (default). - ccy for date and currency manipulation. Depending on the back-end used, additional dependencies need to be met. For example, there are back-ends depending on the following R packages: - zoo and PerformanceAnlytics for the zoo back-end (currently the default one) - timeSeries for the rmetrics back-end Installing rpy2 on Linux is straightforward, on windows it requires the python for windows extension library. Optional Requirements - xlwt to create spreadsheet from timeseries. - simplejson if python version is less then 2.6 - matplotlib for plotting. - djpcms for the web.views module. Running Tests Form the package directory: python runtests.py or, once installed: from dynts import runtests runtests() If you are behind a proxy, some tests will fail unless you write a little script which looks like this: from dynts.conf import settings from dynts import runtests settings.proxies['http'] = '' if __name__ == '__main__': runtests() Community Trying to use an IRC channel #dynts on irc.freenode.net (you can use the webchat at). If you find a bug or would like to request a feature, please submit an issue. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/dynts/0.3.3/
CC-MAIN-2019-26
refinedweb
362
61.12
Created on 2001-11-05 19:34 by anonymous, last changed 2007-09-21 09:11 by jafo. This issue is now closed. NTFS has (always?) had hard link support. This functionality is now exposed in Win32 starting with Windows 2000 [see CreateHardLink()]. I've added Windows support to os.link(). I've tried to support FAT, NT, 95 by doing a CopyFile(). 2000 support is enabled by defining _WIN32_WINNT=0x500 in pythoncore.dsp. When this is done, the redundant #include <windows.h> in errnomodule.c gives compilation errors. Logged In: NO I think that I forgot to add my email address: bcox@semio.com Logged In: YES user_id=39274 Also one can create os.symlink() and os.readlink() for all windows versions after 95 - using shell links (like cygwin do for symlink emulation). Logged In: YES user_id=357491 If you would like this to actually be looked at it would be best to create a patch against CVS and upload a diff file instead of a zip file. This feature request has been superseded by #1578269, which includes several references on the subject.
https://bugs.python.org/issue478407
CC-MAIN-2019-39
refinedweb
184
78.55
Convolutional Neural Networks in Python with Keras You might have already heard of image or facial recognition or self-driving cars. These are real-life implementations of Convolutional Neural Networks (CNNs). In this blog post, you will learn and understand how to implement these deep, feed-forward artificial neural networks in Keras and also learn how to overcome overfitting with the regularization technique called "dropout". More specifically, you'll tackle the following topics in today's tutorial: - You will be introduced to convolutional neural networks; - Then, you'll first try to understand the data. You'll use Python and its libraries to load, explore and analyze your data, - After that, you'll preprocess your data: you'll learn how to resize, rescale, convert your labels into one-hot encoding vectors and split up your data in training and validation sets; - With all of this done, you can construct the neural network model: you'll learn how to model the data and form the network. Next, you'll compile, train and evaluate the model, visualizing the accuracy and loss plots; - Then, you will learn about the concept of overfitting and how you can overcome it by adding a dropout layer; - With this information, you can revisit your original model and re-train the model. You'll also re-evaluate your new model and compare the results of both the models; - Next, you'll make predictions on the test data, convert the probabilities into class labels and plot few test samples that your model correctly classified and incorrectly classified; - Finally, you will visualize the classification report which will give you more in-depth intuition about which class was (in)correctly classified by your model. Would you like to take a course on Keras and deep learning in Python? Consider taking DataCamp's Deep Learning in Python course!. A specific kind of such a deep neural network is the convolutional network, which is commonly referred to as CNN or ConvNet. It's a deep, feed-forward artificial neural network. Remember that feed-forward neural networks are also called multi-layer perceptrons(MLPs), which are the quintessential deep learning models. The models are called "feed-forward" because information fl�ows right through the model. There are no feedback connections in which outputs of the model are fed back into itself. CNNs specifically are inspired by the biological visual cortex. The cortex has small regions of cells that are sensitive to the specific areas of the visual field. This idea was expanded by a captivating experiment done by Hubel and Wiesel in 1962 (if you want to know more, here's a video). In this experiment, the researchers showed that some individual neurons in the brain activated or fired only in the presence of edges of a particular orientation like vertical or horizontal edges. For example, some neurons fired when exposed to vertical sides and some when shown a horizontal edge. Hubel and Wiesel found that all of these neurons were well ordered in a columnar fashion and that together they were able to produce visual perception. This idea of specialized components inside of a system having specific tasks is one that machines use as well and one that you can also find back in CNNs. Convolutional neural networks have been one of the most influential innovations in the field of computer vision. They have performed a lot better than traditional computer vision and have produced state-of-the-art results. These neural networks have proven to be successful in many different real-life case studies and applications, like: - Image classification, object detection, segmentation, face recognition; - Self driving cars that leverage CNN based vision systems; - Classification of crystal structure using a convolutional neural network; - And many more, of course! To understand this success, you'll have to go back to 2012, the year in which Alex Krizhevsky used convolutional neural networks to win that year's ImageNet Competition, reducing the classification error from 26% to 15%. Note that ImageNet Large Scale Visual Recognition Challenge (ILSVRC) began in the year 2010 is an annual competition where research teams assess their algorithms on the given data set and compete to achieve higher accuracy on several visual recognition tasks. This was the time when neural networks regained prominence after quite some time. This is often called the "third wave of neural networks". The other two waves were in the 1940s until the 1960s and in the 1970s to 1980s. Alright, you know that you'll be working with feed-forward networks that are inspired by the biological visual cortex, but what does that actually mean? Take a look at the picture below: The image shows you that you feed an image as an input to the network, which goes through multiple convolutions, subsampling, a fully connected layer and finally outputs something. But what are all these concepts? - The convolution layer computes the output of neurons that are connected to local regions or receptive fields in the input, each computing a dot product between their weights and a small receptive field to which they are connected to in the input volume. Each computation leads to extraction of a feature map from the input image. In other words, imagine you have an image represented as a 5x5 matrix of values, and you take a 3x3 matrix and slide that 3x3 window or kernel around the image. At each position of that matrix, you multiply the values of your 3x3 window by the values in the image that are currently being covered by the window. As a result, you'll get a single number that represents all the values in that window of the images. You use this layer to filtering: as the window moves over the image, you check for patterns in that section of the image. This works because of filters, which are multiplied by the values outputted by the convolution. - The objective of subsampling is to get an input representation by reducing its dimensions, which helps in reducing overfitting. One of the techniques of subsampling is max pooling. With this technique, you select the highest pixel value from a region depending on its size. In other words, max pooling takes the largest value from the window of the image currently covered by the kernel. For example, you can have a max-pooling layer of size 2 x 2 will select the maximum pixel intensity value from 2 x 2 region. You're right to think that the pooling layer then works a lot like the convolution layer! You also take a kernel or a window and move it over the image; The only difference is the function that is applied to the kernel and the image window isn't linear. - The objective of the fully connected layer is to flatten the high-level features that are learned by convolutional layers and combining all the features. It passes the flattened output to the output layer where you use a softmax classifier or a sigmoid to predict the input class label. For more information, you can go here. The Fashion-MNIST Data Set Before you go ahead and load in the data, it's good to take a look at what you'll exactly be working with! The Fashion-MNIST dataset is a dataset of Zalando's article images, with 28x28 grayscale images of 70,000 fashion products from 10 categories, and 7,000 images per category. The training set has 60 to the MNIST dataset. Tip: if you want to learn how to implement an Multi-Layer Perceptron (MLP) for classification tasks with this latter dataset, go to this tutorial. You can find the Fashion-MNIST dataset here, but you can also load it with the help of specific TensorFlow and Keras modules. You'll see how this works in the next section! Load the Data Keras comes with a library called datasets, which you can use to load datasets out of the box: you download the data from the server and speeds up the process since you no longer have to download the data to your computer. The train and test images along with the labels are loaded and stored in variables train_X, train_Y, test_X, test_Y, respectively. from keras.datasets import fashion_mnist (train_X,train_Y), (test_X,test_Y) = fashion_mnist.load_data() Using TensorFlow backend. Great! That was pretty simple, wasn't it? You have probably done this a million times by now, but it's always an essential step to get started. Now you're completely set to start analyzing, processing and modeling your data! Analyze the Data Let's now analyze how images in the dataset look like. Even though you know the dimension of the images by now, it's still worth the effort to analyze it programmatically: you might have to rescale the image pixels and resize the images. import numpy as np from keras.utils import to_categorical import matplotlib.pyplot as plt %matplotlib inline print('Training data shape : ', train_X.shape, train_Y.shape) print('Testing data shape : ', test_X.shape, test_Y.shape) ('Training data shape : ', (60000, 28, 28), (60000,)) ('Testing data shape : ', (10000, 28, 28), (10000,)) From the above output, you can see that the training data has a shape of 60000 x 28 x 28 since there are 60,000 training samples each of 28 x 28 dimension. Similarly, the test data has a shape of 10000 x 28 x 28 since there are 10,000 testing samples. # Find the unique numbers from the train labels classes = np.unique(train_Y) nClasses = len(classes) print('Total number of outputs : ', nClasses) print('Output classes : ', classes) ('Total number of outputs : ', 10) ('Output classes : ', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)) There's also a total of ten output classes that range from 0 to 9. Also, don't forget to take a look at what the images in your dataset: plt.figure(figsize=[5,5]) # Display the first image in training data plt.subplot(121) plt.imshow(train_X[0,:,:], cmap='gray') plt.title("Ground Truth : {}".format(train_Y[0])) # Display the first image in testing data plt.subplot(122) plt.imshow(test_X[0,:,:], cmap='gray') plt.title("Ground Truth : {}".format(test_Y[0])) Text(0.5,1,u'Ground Truth : 9') The output of above two plots looks like an ankle boot, and this class is assigned a class label of 9. Similarly, other fashion products will have different labels, but similar products will have same labels. This means that all the 7,000 ankle boot images will have a class label of 9. Data Preprocessing As you could see in the above plot, the images are grayscale images have pixel values that range from 0 to 255. Also, these images have a dimension of 28 x 28. As a result, you'll need to preprocess the data before you feed it into the model. - As a first step, convert each 28 x 28 image of the train and test set into a matrix of size 28 x 28 x 1 which is fed into the network. train_X = train_X.reshape(-1, 28,28, 1) test_X = test_X.reshape(-1, 28,28, 1) train_X.shape, test_X.shape ((60000, 28, 28, 1), (10000, 28, 28, 1)) - The data right now is in an int8 format, so before you feed it into the network you need to convert its type to float32, and you also have to rescale the pixel values in range 0 - 1 inclusive. So let's do that! train_X = train_X.astype('float32') test_X = test_X.astype('float32') train_X = train_X / 255. test_X = test_X / 255. - Now you need to convert the class labels into a one-hot encoding vector. In one-hot encoding, you convert the categorical data into a vector of numbers. The reason why you convert the categorical data in one hot encoding is that machine learning algorithms cannot work with categorical data directly. You generate one boolean column for each category or class. Only one of these columns could take on the value 1 for each sample. Hence, the term one-hot encoding. For your problem statement, the one hot encoding will be a row vector, and for each image, it will have a dimension of 1 x 10. The important thing to note here is that the vector consists of all zeros except for the class that it represents, and for that, it is 1. For example, the ankle boot image that you plotted above has a label of 9, so for all the ankle boot images, the one hot encoding vector would be [0 0 0 0 0 0 0 0 1 0]. So let's convert the training and testing labels into one-hot encoding vectors: # Change the labels from categorical to one-hot encoding train_Y_one_hot = to_categorical(train_Y) test_Y_one_hot = to_categorical(test_Y) # Display the change for category label using one-hot encoding print('Original label:', train_Y[0]) print('After conversion to one-hot:', train_Y_one_hot[0]) ('Original label:', 9) ('After conversion to one-hot:', array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.])) That's pretty clear, right? Note that you can also print the train_Y_one_hot, which will display a matrix of size 60000 x 10 in which each row depicts one-hot encoding of an image. - This last step is a crucial one. In machine learning or any data specific task, you should partition the data correctly. For the model to generalize well, you split the training data into two parts, one designed for training and another one for validation. In this case, you will train the model on 80\% of the training data and validate it on 20\% of the remaining training data. This will also help to reduce overfitting since you will be validating the model on the data it would not have seen in training phase, which will help in boosting the test performance. from sklearn.model_selection import train_test_split train_X,valid_X,train_label,valid_label = train_test_split(train_X, train_Y_one_hot, test_size=0.2, random_state=13) For one last time let's check the shape of training and validation set. train_X.shape,valid_X.shape,train_label.shape,valid_label.shape ((48000, 28, 28, 1), (12000, 28, 28, 1), (48000, 10), (12000, 10)) The Network The images are of size 28 x 28. You convert the image matrix to an array, rescale it between 0 and 1, reshape it so that it's of size 28 x 28 x 1, and feed this as an input to the size 2 x 2. Model the Data First, let's import all the necessary modules required to train the model. You will use a batch size of 64 using a higher batch size of 128 or 256 is also preferable it all depends on the memory. It contributes massively to determining the learning parameters and affects the prediction accuracy. You will train the network for 20 epochs. batch_size = 64 epochs = 20 num_classes = 10 Neural Network Architecture In Keras, you can just stack up layers by adding the desired layer one by one. That's exactly what you'll do here: you'll first add a first convolutional layer with Conv2D(). Note that you use this function because you're working with images! Next, you add the Leaky ReLU activation function which helps the network learn non-linear decision boundaries. Since you have ten different classes, you'll need a non-linear decision boundary that could separate these ten classes which are not linearly separable. More specifically, you add Leaky ReLUs because they attempt to fix the problem of dying Rectified Linear Units (ReLUs). The ReLU activation function is used a lot in neural network architectures and more specifically in convolutional networks, where it has proven to be more effective than the widely used logistic sigmoid function. As of 2017, this activation function is the most popular one for deep neural networks. The ReLU function allows the activation to be thresholded at zero. However, during the training, ReLU units can "die". This can happen when a large gradient flows through a ReLU neuron: it can cause the weights to update in such a way that the neuron will never activate on any data point again. If this happens, then the gradient flowing through the unit will forever be zero from that point on. Leaky ReLUs attempt to solve this: the function will not be zero but will instead have a small negative slope. Next, you'll add the max-pooling layer with MaxPooling2D() and so on. The last layer is a Dense layer that has a softmax activation function with 10 units, which is needed for this multi-class classification problem. fashion_model = Sequential() fashion_model.add(Conv2D(32, kernel_size=(3, 3),activation='linear',input_shape=(28,28,1),padding='same')) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(MaxPooling2D((2, 2),padding='same')) fashion_model.add(Conv2D(64, (3, 3), activation='linear',padding='same')) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same')) fashion_model.add(Conv2D(128, (3, 3), activation='linear',padding='same')) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same')) fashion_model.add(Flatten()) fashion_model.add(Dense(128, activation='linear')) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(Dense(num_classes, activation='softmax')) Compile the Model After the model is created, you compile it using the Adam optimizer, one of the most popular optimization algorithms. You can read more about this optimizer here. Additionally, you specify the loss type which is categorical cross entropy which is used for multi-class classification, you can also use binary cross-entropy as the loss function. Lastly, you specify the metrics as accuracy which you want to analyze while the model is training. fashion_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(),metrics=['accuracy']) Let's visualize the layers that you created in the above step by using the summary function. This will show some parameters (weights and biases) in each layer and also the total parameters in your model. fashion_model.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_51 (Conv2D) (None, 28, 28, 32) 320 _________________________________________________________________ leaky_re_lu_57 (LeakyReLU) (None, 28, 28, 32) 0 _________________________________________________________________ max_pooling2d_49 (MaxPooling (None, 14, 14, 32) 0 _________________________________________________________________ conv2d_52 (Conv2D) (None, 14, 14, 64) 18496 _________________________________________________________________ leaky_re_lu_58 (LeakyReLU) (None, 14, 14, 64) 0 _________________________________________________________________ max_pooling2d_50 (MaxPooling (None, 7, 7, 64) 0 _________________________________________________________________ conv2d_53 (Conv2D) (None, 7, 7, 128) 73856 _________________________________________________________________ leaky_re_lu_59 (LeakyReLU) (None, 7, 7, 128) 0 _________________________________________________________________ max_pooling2d_51 (MaxPooling (None, 4, 4, 128) 0 _________________________________________________________________ flatten_17 (Flatten) (None, 2048) 0 _________________________________________________________________ dense_33 (Dense) (None, 128) 262272 _________________________________________________________________ leaky_re_lu_60 (LeakyReLU) (None, 128) 0 _________________________________________________________________ dense_34 (Dense) (None, 10) 1290 ================================================================= Total params: 356,234 Trainable params: 356,234 Non-trainable params: 0 _________________________________________________________________ Train the Model It's finally time to train the model with Keras' fit() function! The model trains for 20 epochs. The fit() function will return a history object; By storying the result of this function in fashion_train, you can use it later to plot the accuracy and loss function plots between training and validation which will help you to analyze your model's performance visually. fashion_train = fashion_model.fit(train_X, train_label, batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(valid_X, valid_label)) Train on 48000 samples, validate on 12000 samples Epoch 1/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.4661 - acc: 0.8311 - val_loss: 0.3320 - val_acc: 0.8809 Epoch 2/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.2874 - acc: 0.8951 - val_loss: 0.2781 - val_acc: 0.8963 Epoch 3/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.2420 - acc: 0.9111 - val_loss: 0.2501 - val_acc: 0.9077 Epoch 4/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.2088 - acc: 0.9226 - val_loss: 0.2369 - val_acc: 0.9147 Epoch 5/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.1838 - acc: 0.9324 - val_loss: 0.2602 - val_acc: 0.9070 Epoch 6/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.1605 - acc: 0.9396 - val_loss: 0.2264 - val_acc: 0.9193 Epoch 7/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.1356 - acc: 0.9488 - val_loss: 0.2566 - val_acc: 0.9180 Epoch 8/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.1186 - acc: 0.9553 - val_loss: 0.2556 - val_acc: 0.9149 Epoch 9/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.0985 - acc: 0.9634 - val_loss: 0.2681 - val_acc: 0.9204 Epoch 10/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.0873 - acc: 0.9670 - val_loss: 0.2712 - val_acc: 0.9221 Epoch 11/20 48000/48000 [==============================] - 59s 1ms/step - loss: 0.0739 - acc: 0.9721 - val_loss: 0.2757 - val_acc: 0.9202 Epoch 12/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.0628 - acc: 0.9767 - val_loss: 0.3126 - val_acc: 0.9132 Epoch 13/20 48000/48000 [==============================] - 61s 1ms/step - loss: 0.0569 - acc: 0.9789 - val_loss: 0.3556 - val_acc: 0.9081 Epoch 14/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.0452 - acc: 0.9833 - val_loss: 0.3441 - val_acc: 0.9189 Epoch 15/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.0421 - acc: 0.9847 - val_loss: 0.3400 - val_acc: 0.9165 Epoch 16/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.0379 - acc: 0.9861 - val_loss: 0.3876 - val_acc: 0.9195 Epoch 17/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.0405 - acc: 0.9855 - val_loss: 0.4112 - val_acc: 0.9164 Epoch 18/20 48000/48000 [==============================] - 60s 1ms/step - loss: 0.0285 - acc: 0.9897 - val_loss: 0.4150 - val_acc: 0.9181 Epoch 19/20 48000/48000 [==============================] - 61s 1ms/step - loss: 0.0322 - acc: 0.9877 - val_loss: 0.4584 - val_acc: 0.9196 Epoch 20/20 48000/48000 [==============================] - 61s 1ms/step - loss: 0.0262 - acc: 0.9906 - val_loss: 0.4396 - val_acc: 0.9205 Finally! You trained the model on fashion-MNIST for 20 epochs, and by observing the training accuracy and loss, you can say that the model did a good job since after 20 epochs the training accuracy is 99% and the training loss is quite low. However, it looks like the model is overfitting, as the validation loss is 0.4396 and the validation accuracy is 92%. Overfitting gives an intuition that the network has memorized the training data very well but is not guaranteed to work on unseen data, and that is why there is a difference in the training and validation accuracy. You probably need to handle this. In next sections, you'll learn how you can make your model perform much better by adding a Dropout layer into the network and keeping all the other layers unchanged. But first, let's evaluate the performance of your model on the test set before you come on to a conclusion. Model Evaluation on the Test Set test_eval = fashion_model.evaluate(test_X, test_Y_one_hot, verbose=0) print('Test loss:', test_eval[0]) print('Test accuracy:', test_eval[1]) ('Test loss:', 0.46366268818555401) ('Test accuracy:', 0.91839999999999999) The test accuracy looks impressive. It turns out that your classifier does better than the benchmark that was reported here, which is an SVM classifier with mean accuracy of 0.897. Also, the model does well compared to some of the deep learning models mentioned on the GitHub profile of the creators of fashion-MNIST dataset. However, you saw that the model looked like it was overfitting. Are these results really all that good? Let's put your model evaluation into perspective and plot the accuracy and loss plots between training and validation data: accuracy = fashion_train.history['acc'] val_accuracy = fashion_train.history['val_acc'] loss = fashion_train.history['loss'] val_loss = fashion_train_3<< From the above two plots, you can see that the validation accuracy almost became stagnant after 4-5 epochs and rarely increased at certain epochs. In the beginning, the validation accuracy was linearly increasing with loss, but then it did not increase much. The validation loss shows that this is the sign of overfitting, similar to validation accuracy it linearly decreased but after 4-5 epochs, it started to increase. This means that the model tried to memorize the data and succeeded. With this in mind, it's time to introduce some dropout into our model and see if it helps in reducing overfitting. Adding Dropout into the Network You can add a dropout layer to overcome the problem of overfitting to some extent. Dropout randomly turns off a fraction of neurons during the training process, reducing the dependency on the training set by some amount. How many fractions of neurons you want to turn off is decided by a hyperparameter, which can be tuned accordingly. This way, turning off some neurons will not allow the network to memorize the training data since not all the neurons will be active at the same time and the inactive neurons will not be able to learn anything. So let's create, compile and train the network again but this time with dropout. And run it for 20 epochs with a batch size of 64. batch_size = 64 epochs = 20 num_classes = 10 fashion_model = Sequential() fashion_model.add(Conv2D(32, kernel_size=(3, 3),activation='linear',padding='same',input_shape=(28,28,1))) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(MaxPooling2D((2, 2),padding='same')) fashion_model.add(Dropout(0.25)) fashion_model.add(Conv2D(64, (3, 3), activation='linear',padding='same')) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same')) fashion_model.add(Dropout(0.25)) fashion_model.add(Conv2D(128, (3, 3), activation='linear',padding='same')) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(MaxPooling2D(pool_size=(2, 2),padding='same')) fashion_model.add(Dropout(0.4)) fashion_model.add(Flatten()) fashion_model.add(Dense(128, activation='linear')) fashion_model.add(LeakyReLU(alpha=0.1)) fashion_model.add(Dropout(0.3)) fashion_model.add(Dense(num_classes, activation='softmax')) fashion_model.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_54 (Conv2D) (None, 28, 28, 32) 320 _________________________________________________________________ leaky_re_lu_61 (LeakyReLU) (None, 28, 28, 32) 0 _________________________________________________________________ max_pooling2d_52 (MaxPooling (None, 14, 14, 32) 0 _________________________________________________________________ dropout_29 (Dropout) (None, 14, 14, 32) 0 _________________________________________________________________ conv2d_55 (Conv2D) (None, 14, 14, 64) 18496 _________________________________________________________________ leaky_re_lu_62 (LeakyReLU) (None, 14, 14, 64) 0 _________________________________________________________________ max_pooling2d_53 (MaxPooling (None, 7, 7, 64) 0 _________________________________________________________________ dropout_30 (Dropout) (None, 7, 7, 64) 0 _________________________________________________________________ conv2d_56 (Conv2D) (None, 7, 7, 128) 73856 _________________________________________________________________ leaky_re_lu_63 (LeakyReLU) (None, 7, 7, 128) 0 _________________________________________________________________ max_pooling2d_54 (MaxPooling (None, 4, 4, 128) 0 _________________________________________________________________ dropout_31 (Dropout) (None, 4, 4, 128) 0 _________________________________________________________________ flatten_18 (Flatten) (None, 2048) 0 _________________________________________________________________ dense_35 (Dense) (None, 128) 262272 _________________________________________________________________ leaky_re_lu_64 (LeakyReLU) (None, 128) 0 _________________________________________________________________ dropout_32 (Dropout) (None, 128) 0 _________________________________________________________________ dense_36 (Dense) (None, 10) 1290 ================================================================= Total params: 356,234 Trainable params: 356,234 Non-trainable params: 0 _________________________________________________________________ fashion_model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(),metrics=['accuracy']) fashion_train_dropout = fashion_model.fit(train_X, train_label, batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(valid_X, valid_label)) Train on 48000 samples, validate on 12000 samples Epoch 1/20 48000/48000 [==============================] - 66s 1ms/step - loss: 0.5954 - acc: 0.7789 - val_loss: 0.3788 - val_acc: 0.8586 Epoch 2/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.3797 - acc: 0.8591 - val_loss: 0.3150 - val_acc: 0.8832 Epoch 3/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.3302 - acc: 0.8787 - val_loss: 0.2836 - val_acc: 0.8961 Epoch 4/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.3034 - acc: 0.8868 - val_loss: 0.2663 - val_acc: 0.9002 Epoch 5/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.2843 - acc: 0.8936 - val_loss: 0.2481 - val_acc: 0.9083 Epoch 6/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.2699 - acc: 0.9002 - val_loss: 0.2469 - val_acc: 0.9032 Epoch 7/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2561 - acc: 0.9049 - val_loss: 0.2422 - val_acc: 0.9095 Epoch 8/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2503 - acc: 0.9068 - val_loss: 0.2429 - val_acc: 0.9098 Epoch 9/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2437 - acc: 0.9096 - val_loss: 0.2230 - val_acc: 0.9173 Epoch 10/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2307 - acc: 0.9126 - val_loss: 0.2170 - val_acc: 0.9187 Epoch 11/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2307 - acc: 0.9135 - val_loss: 0.2265 - val_acc: 0.9193 Epoch 12/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2229 - acc: 0.9160 - val_loss: 0.2136 - val_acc: 0.9229 Epoch 13/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2202 - acc: 0.9162 - val_loss: 0.2173 - val_acc: 0.9187 Epoch 14/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.2161 - acc: 0.9188 - val_loss: 0.2142 - val_acc: 0.9211 Epoch 15/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2119 - acc: 0.9196 - val_loss: 0.2133 - val_acc: 0.9233 Epoch 16/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2073 - acc: 0.9222 - val_loss: 0.2159 - val_acc: 0.9213 Epoch 17/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2050 - acc: 0.9231 - val_loss: 0.2123 - val_acc: 0.9233 Epoch 18/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.2016 - acc: 0.9238 - val_loss: 0.2191 - val_acc: 0.9235 Epoch 19/20 48000/48000 [==============================] - 65s 1ms/step - loss: 0.2001 - acc: 0.9244 - val_loss: 0.2110 - val_acc: 0.9258 Epoch 20/20 48000/48000 [==============================] - 64s 1ms/step - loss: 0.1972 - acc: 0.9255 - val_loss: 0.2092 - val_acc: 0.9269 Let's save the model so that you can directly load it and not have to train it again for 20 epochs. This way, you can load the model later on if you need it and modify the architecture; Alternatively, you can start the training process on this saved model. It is always a good idea to save the model -and even the model's weights!- because it saves you time. Note that you can also save the model after every epoch so that, if some issue occurs that stops the training at an epoch, you will not have to start the training from the beginning. fashion_model.save("fashion_model_dropout.h5py") Model Evaluation on the Test Set Finally, let's also evaluate your new model and see how it performs! test_eval = fashion_model.evaluate(test_X, test_Y_one_hot, verbose=1) 10000/10000 [==============================] - 5s 461us/step print('Test loss:', test_eval[0]) print('Test accuracy:', test_eval[1]) ('Test loss:', 0.21460009642243386) ('Test accuracy:', 0.92300000000000004) Wow! Looks like adding Dropout in our model worked, even though the test accuracy did not improve significantly but the test loss decreased compared to the previous results. Now, let's plot the accuracy and loss plots between training and validation data for the one last time. accuracy = fashion_train_dropout.history['acc'] val_accuracy = fashion_train_dropout.history['val_acc'] loss = fashion_train_dropout.history['loss'] val_loss = fashion_train_dropout_5<< Finally, you can see that the validation loss and validation accuracy both are in sync with the training loss and training accuracy. Even though the validation loss and accuracy line are not linear, but it shows that your model is not overfitting: the validation loss is decreasing and not increasing, and there is not much gap between training and validation accuracy. Therefore, you can say that your model's generalization capability became much better since the loss on both test set and validation set was only slightly more compared to the training loss. Predict Labels predicted_classes = fashion_model.predict(test_X) Since the predictions you get are floating point values, it will not be feasible to compare the predicted labels with true test labels. So, you will round off the output which will convert the float values into an integer. Further, you will use np.argmax() to select the index number which has a higher value in a row. For example, let's assume a prediction for one test image to be 0 1 0 0 0 0 0 0 0 0, the output for this should be a class label 1. predicted_classes = np.argmax(np.round(predicted_classes),axis=1) predicted_classes.shape, test_Y.shape ((10000,), (10000,)) correct = np.where(predicted_classes==test_Y)[0] print "Found %d correct labels" % len(correct) for i, correct in enumerate(correct[:9]): plt.subplot(3,3,i+1) plt.imshow(test_X[correct].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[correct], test_Y[correct])) plt.tight_layout() Found 9188 correct labels incorrect = np.where(predicted_classes!=test_Y)[0] print "Found %d incorrect labels" % len(incorrect) for i, incorrect in enumerate(incorrect[:9]): plt.subplot(3,3,i+1) plt.imshow(test_X[incorrect].reshape(28,28), cmap='gray', interpolation='none') plt.title("Predicted {}, Class {}".format(predicted_classes[incorrect], test_Y[incorrect])) plt.tight_layout() Found 812 incorrect labels By looking at a few images, you cannot be sure as to why your model is not able to classify the above images correctly, but it seems like a variety of the similar patterns present on multiple classes affect the performance of the classifier although CNN is a robust architecture. For example, images 5 and 6 both belong to different classes but look kind of similar maybe a jacket or perhaps a long sleeve shirt. Classification Report Classification report will help us in identifying the misclassified classes in more detail. You will be able to observe for which class the model performed bad out of the given ten classes. from sklearn.metrics import classification_report target_names = ["Class {}".format(i) for i in range(num_classes)] print(classification_report(test_Y, predicted_classes, target_names=target_names)) precision recall f1-score support Class 0 0.77 0.90 0.83 1000 Class 1 0.99 0.98 0.99 1000 Class 2 0.88 0.88 0.88 1000 Class 3 0.94 0.92 0.93 1000 Class 4 0.88 0.87 0.88 1000 Class 5 0.99 0.98 0.98 1000 Class 6 0.82 0.72 0.77 1000 Class 7 0.94 0.99 0.97 1000 Class 8 0.99 0.98 0.99 1000 Class 9 0.98 0.96 0.97 1000 avg / total 0.92 0.92 0.92 10000 You can see that the classifier is underperforming for class 6 regarding both precision and recall. For class 0 and class 2, the classifier is lacking precision. Also, for class 4, the classifier is slightly lacking both precision and recall. Go Further! This tutorial was good start to convolutional neural networks in Python with Keras. If you were able to follow along easily or even with little more efforts, well done! Try doing some experiments maybe with same model architecture but using different types of public datasets available. There is still a lot to cover, so why not take DataCamp's Deep Learning in Python course? In the meantime, also make sure to check out the Keras documentation, if you haven't done so already. You will find more examples and information on all functions, arguments, more layers, etc. It will undoubtedly be an indispensable resource when you're learning how to work with neural networks in Python! If you rather feel like reading a book that explains the fundamentals of deep learning (with Keras) together with how it's used in practice, you should definitely read François Chollet's Deep Learning in Python book.
https://www.datacamp.com/community/tutorials/convolutional-neural-networks-python
CC-MAIN-2019-35
refinedweb
5,778
67.45
Don't know if this is in the right section if not please direct me and I will repost in section. First I want to start off by saying Hi! I'm new to these forums and I'm currently studying computer technologies : System Analyst at Sheridan College Davis Campus. Currently writing code for class. The following allows users to input 4 marks and it changes the grade to percentage to see the weighting on the following: Mark 1 Worth 20% Mark 2 Worth 25% Mark 3 Worth 20% Mark 4 Worth 35% Code is as the following <\code>import java.util.*; public class GradingSystem { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean valid = true; // Ask user for input of first lab System.out.println("Please enter mark for lab1 i.e. 80: "); double lab1 = input.nextInt(); //Asks user for input of Test mark System.out.println("Please enter mark for test i.e. 80: "); double test = input.nextInt(); //Asks user for Assignment marks System.out.println("Please enter mark for Assignment i.e. 80: "); double assignment = input.nextInt(); //Asks users for Final Exam mark System.out.println("Please enter mark for final exam i.e 80: "); double fexam = input.nextInt(); //Checking to see if mark inputed is valid if (lab1 < 0 || lab1 > 100) { valid = false; } if (test < 0 || test > 100) valid = false; if (assignment < 0 || assignment > 100) valid = false; if (fexam < 0 || fexam > 100) valid = false; //If False shows message saying Mark is not valid. if (valid == false) System.out.println("Mark is not valid."); //Converting marks to percentages double lab1p = lab1 * 0.20; double testp = test * 0.25; double assignmentp = assignment * 0.20; double fexamp = fexam * 0.35; //Calculating what the average is for student. double averageGrade = (lab1 + test + assignment + fexam ) / 4 ; // Adding all marks together to divide to get average. double passOrFailure = (lab1p + testp + assignmentp + fexamp); //Checks to see if grade is over 49 or equal to if (passOrFailure <= 49) System.out.println("You have failed"); if (passOrFailure >= 50) System.out.println("You have passed!"); //Displaying results to student. If Value is false Value for test is false will display System.out.println("The total for your Lab #1 is: " + lab1p + "% outta 20%"); System.out.println("The total for your Test is: " + testp + "% outta 25%"); System.out.println("The total for your Assignment is: " + assignmentp + "% outta 20%"); System.out.println("The total for your Final Exam is: " + fexamp + "% outta 35%"); if (valid == false) System.out.println("Average cannot be computed."); else System.out.println("Average is: " + averageGrade); } } </code> Now the problem I'm getting is I want to take the line System.out.println("The total for your Lab #1 is: + lab1q + "% outta 20%"); and I want to change it to the following if (valid == false) System.out.println("The Mark inputted was not valid, Program will not display mark"); else System.out.println("The total for your Lab #1 is: + lab1q + "% outta 20%"); But I want to do it for the rest of the code... Would I follow that same aspect... So if a user inputs a WRONG value ( -1 and under or 101+) the Programs outputs that line the mark inputted was not valid. Please help!
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/5344-help-printingthethread.html
CC-MAIN-2015-32
refinedweb
536
60.41
One of the most common operations in EJB is "getting" data from entity beans. Consider a "User" entity bean, which models all the information of a user of a website. A User has a first name, last name, street address, telephone number, etc. The problem is that When trying to get this data from the entity bean, each call to a "getter" (ie: getFirstName(), getLastName(),...) involves a network round trip, transactional overhead on the part of the app. server, serialization, etc. Too many queries of this sort will make your transactions longer and your system less scalable. The solution to this problem is to make a plain java class (a details object) that contains all the attributes of the User Entity Bean. That is, create a UserDetailsBean that contains a first name, last name, phone number, etc, as well as getters and setters. Example: A User Entity Bean and Details Bean The method implementations are left out for brevity public class UserBean implements EntityBean { Note that the UserDetailsBean contains all the same attributes and getters and setters as the Entity Bean. Now when the client wants to get at the User's data, instead of calling a large number of "getter" methods, one must only call "getUserDetails", which will create a UserDetailsBean with a copy of the internal state of the User Entity Bean, and pass that to the client. Using this strategy will decrease network roundtrips associated with "getting" attributes of an entity bean from n (limited by the number of attributes of the entity bean) down to just one (the call to get the details object). Details Objects can also be used across "tiers" (ie: you can use details objects in JSP's to list entity bean contents). Once you have written details objects for all your entity beans, I have found that making your entity beans inherit from your details objects will clean up your code considerable because you can now move your attributes and getters/setters out of your entity beans (into the details objects). Your entity beans will now contain only business methods and ejb specific methods: public class UserBean implements EntityBean { / Details Object (49 messages) - Posted by: Floyd Marinescu - Posted on: June 23 2000 20:49 EDT Threaded Messages (49) - Details Object by Anuj Goswami on June 24 2000 18:26 EDT - Details Object by Floyd Marinescu on June 26 2000 11:12 EDT - Details Object by Shriram Mogallapalli on June 28 2000 03:19 EDT - Details Object by Chandrasekaran V on June 29 2000 12:22 EDT - Details Object by Dan Steenblik on October 17 2000 17:30 EDT - Details Object by Timothy Fry on November 22 2000 10:32 EST - Details Object by Robert Nicholson on April 24 2001 18:38 EDT - Details Object by Timothy Fry on June 08 2001 04:30 EDT - Details Object by Chandrasekaran V on June 29 2000 00:11 EDT - Details Object by Floyd Marinescu on June 29 2000 01:08 EDT - To make it clearer by Jean-Baptiste Nizet on June 30 2000 12:00 EDT - To make it clearer by Floyd Marinescu on July 02 2000 23:57 EDT - To make it clearer by Jean-Baptiste Nizet on July 03 2000 04:25 EDT - To make it clearer by Tom Anderson on July 06 2000 10:11 EDT - great ideas, why not post them as patterns? by Floyd Marinescu on July 06 2000 12:08 EDT - To make it clearer by Jean-Baptiste Nizet on July 07 2000 11:18 EDT - How about Aggregate details objects by Jeff anderson on July 10 2000 12:35 EDT - How about Aggregate details objects by Floyd Marinescu on July 13 2000 03:25 EDT - To make it clearer by Ivan Mitrovic on July 19 2000 01:43 EDT - To make it clearer by Matt Staples on July 24 2000 01:58 EDT - To make it clearer by Floyd Marinescu on July 27 2000 09:13 EDT - To make it clearer by Jeff anderson on August 15 2000 11:53 EDT - Detail - Entity Bean Synchronization by Bill Smith on November 06 2000 10:42 EST - To make it clearer by Ash Hassib on August 29 2000 08:14 EDT - To make it clearer by Bill Smith on September 11 2000 09:16 EDT - To make it clearer by callum wallach on December 12 2000 07:09 EST - To make it clearer by Benjamin Jiang on March 13 2001 01:14 EST - To make it clearer by Eron Wright on July 24 2000 02:30 EDT - Problem with Details Pattern by Kaja Mohaideen on September 14 2000 12:10 EDT - Clarification by Daniel MacDonald on September 19 2000 10:51 EDT - Clarification by Floyd Marinescu on September 21 2000 12:10 EDT - Over All Design Pattern by Parikshit Pol on September 25 2000 07:52 EDT - Article online by Jeremy Chan on July 03 2000 07:05 EDT - Article online by Henri Chen on February 15 2001 04:58 EST - To make it clearer by Jianming Wang on April 04 2002 11:41 EST - Details Object by Mikael Nyberg on July 13 2000 07:59 EDT - Details Object - Problems in Weblogic 5.1 by Julian Khoo on July 25 2000 09:03 EDT - Details Object - Problems in Weblogic 5.1 by Julian Khoo on July 25 2000 09:28 EDT - Details Object - Problems in Weblogic 5.1 by Ozzie Gurkan on July 26 2000 00:37 EDT - Details Object by Bartek Kiepuszewski on August 17 2000 02:10 EDT - Details Object by Floyd Marinescu on August 17 2000 12:04 EDT - Details Object by Bartek Kiepuszewski on August 21 2000 04:27 EDT - Details Object by Amie Alousis on April 02 2001 12:10 EDT - Details Object by Pradeep Jaligama on September 25 2000 16:48 EDT - Details Object by Timothy Fry on September 26 2000 21:38 EDT - Details Object by Timothy Fry on September 26 2000 09:41 EDT - Details Object by Farhan Alam on May 08 2001 14:21 EDT - Details Object by SELVA S on October 21 2001 12:04 EDT - Details Object by SELVA S on October 21 2001 12:06 EDT Details Object[ Go to top ] Another important issue while considering performance of entity beans while loading them from the database is "references".When an entity bean is loaded,the whole graph of entity beans or java classes is loaded which are referenced by the entity bean.This certainly leads to performance bottlenecks.One of the solutions that we implemented in our projects was to use TopLink's indirection,while generating object to relational mapping for our persistent objects.TopLinks indirection loads the references,only if needed or specified in the code as marked "to be loaded" - Posted by: Anuj Goswami - Posted on: June 24 2000 18:26 EDT - in response to Floyd Marinescu Details Object[ Go to top ] For people not using TopLink or other advanced entity bean containers, you can avoid loading the whole object graph by lazy loading your references, which will be the subject of pattern I will post here soon. :) - Posted by: Floyd Marinescu - Posted on: June 26 2000 11:12 EDT - in response to Anuj Goswami Floyd Details Object[ Go to top ] I liked the idea to get the details object by making only one call. If the data underneth changes the remote method call could still fetch the current values, but how do we handle such situations? - Posted by: Shriram Mogallapalli - Posted on: June 28 2000 15:19 EDT - in response to Floyd Marinescu Details Object[ Go to top ] In the getter set the Details objects values to the current beans feild values like - Posted by: Chandrasekaran V - Posted on: June 29 2000 00:22 EDT - in response to Shriram Mogallapalli public DetailsObject getDetObjects()throws RemoteException{ DetailsObject myDetails = new DetailsObject(); myDetails.name = this.name; myDetails.age = this.age; return myDetails; } this object will have the current values each time u call the getter as it is the containers responsibility to update the field values of the EJB. Details Object[ Go to top ] We are also using ejb with toplink, and our basecode api is strongly tied to toplink. We have been debating recently the approach to take with entitybeans and toplink -- did you use toplink to replace entitybeans, or did you use entitybeans to wrap toplink objects, or did you find another solution? - Posted by: Dan Steenblik - Posted on: October 17 2000 17:30 EDT - in response to Anuj Goswami Thanks, Dan Details Object[ Go to top ] We use TOPLink to persist our domain (business data) objects. These are just regular java objects that happen to be mapped to the RDB using TOPLink. These plain classes are then manipulated by session beans on behalf of client interactions, just as if they were entity beans. So in a sense, we are using TOPLink to replace entity beans. Using TOPLink also largely solves one of the issues that a subsequent poster raised -- that of knowing what has changed in a object graph as TOPLink keeps track of such things and will only persist the dirtied parts of a graph at commit time. - Posted by: Timothy Fry - Posted on: November 22 2000 22:32 EST - in response to Dan Steenblik Tim Details Object[ Go to top ] In Java how does Toplink does this? - Posted by: Robert Nicholson - Posted on: April 24 2001 18:38 EDT - in response to Anuj Goswami In Apple's EOF they use Faulting and in the good old days of Objective-C they did a point swizzle withever the object at the end of the relationship was touched. ie. the lazily loaded the data but maintained the same reference pointer to keep existing associations valid. This was done using Objective-C's forwarding mechanism. But how is this done in Java? Presumably there are "holder" objects that are always referenced and they either contain the data or the details necessary to obtain the data but I'm interested in exactly how they implement their lazily loaded. What kind of operation triggers a lazy load? Details Object[ Go to top ] Presumably there are "holder" - Posted by: Timothy Fry - Posted on: June 08 2001 16:30 EDT - in response to Robert Nicholson Yes, TOPLink has a ValueHolder class that acts as a 'smart' reference. You use it in place of the real reference and TOPLink will not actually read the data at the end of the ValueHolder relationship until you dereference it. For example, lets say that the object of type Dog has a logical relationship to an object of type Tail. Using indirection in TOPLink (the term used for lazy-loading), the reference to Tail looks like: ValueHolder tailHolder; and the accessor for Tail looks like: public Tail getTail ( ) { return (Tail)tailHolder.getValue( ); } while the mutator looks like: public void setTail ( Tail tail ) { tailHolder.setValue ( tail ); } So, the loading is triggered when the value holder is 'dereferenced' via the getValue( )method. This makes the fact that there is some TOPLink magic providing lazy loading of Tails transparent to users of Dog. You also have to provide a couple of helper methods to set and get the holder -- these are used internally by TL. You must also specify in the TL O/R mapping tool that you are using indirection for this relationship. Hope this helps. Tim Details Object[ Go to top ] Hi, - Posted by: Chandrasekaran V - Posted on: June 29 2000 00:11 EDT - in response to Floyd Marinescu The article abt passing a object back and forth is a good idea we followed the same thing but implemented it as a container object for the sake of ease .One clarification though why would ur setters require a return type. thanx Chandrasekaran.V Details Object[ Go to top ] What do you mean by "implemented it as a container object"? - Posted by: Floyd Marinescu - Posted on: June 29 2000 01:08 EDT - in response to Chandrasekaran V >One clarification though why would ur setters require a > return type. That was my mistake, and has since been fixed. Thanks. Floyd To make it clearer[ Go to top ] I fully agree with this pattern. However, at the end of the message, you mention that the entity bean class should inherit the Details object class. Why don't you make it clear in the example: - Posted by: Jean-Baptiste Nizet - Posted on: June 30 2000 12:00 EDT - in response to Floyd Marinescu public class UserBean extends UserDetailsBean implements EntityBean { //ejb specific methods and business methods } Also, it's worth mentioning that the getUserDetails() method will be far easier to implement in this case : public class UserDetailsBean implements Serializable { public UserDetailsBean getUserDetails() { return this; } //... } Also, note that this inheritance has a disadvantage : it forces you to declare "throws RemoteException" for each method of the Details class. The example thus becomes: public class UserDetailsBean implements Serializable{ public String getUserName() throws RemoteException; public setUserName(String name) throws RemoteException; //... } Finally, the last problem with this is that if you want to use CMP, the fields in the Details class must be made public, which allow anyone to bypass the accessors (and thus the validation in these accessors). JB. To make it clearer[ Go to top ] Jean-Baptiste, - Posted by: Floyd Marinescu - Posted on: July 02 2000 23:57 EDT - in response to Jean-Baptiste Nizet Actually, even if you do inherit from your details object, in getUserDetails, you CANNOT return a reference to this (or even (UserDetailsBean)this). I have tried and this generates errors (in Weblogic anyway). You are right that IF you inherit from your bean, you will have to throw RemoteException from each method. Infact, if you use an isModified pattern, you will also have to move this logic into the details bean, or you could (my preferred solution) actually implement all the setters of the details bean, and delegate all calls to super.setXXXX(). In this case you would no longer need to put any EJB specifc exceptions/etc in the details bean, since you are delegating calls to it from the entity bean. Although it may seem like extra code, this still allows you to keep you validation data in your details object and encapsulate ejb specifc semantics into your entity bean. thanks! Floyd To make it clearer[ Go to top ] Floyd wrote: - Posted by: Jean-Baptiste Nizet - Posted on: July 03 2000 04:25 EDT - in response to Floyd Marinescu Actually, even if you do inherit from your details object, in getUserDetails, you CANNOT return a reference to this (or even (UserDetailsBean)this). I have tried and this generates errors (in Weblogic anyway). I answer: It seems to me like a Weblogic problem. I haven(t found anything in the specs saying that You could not do that. To me, since the method signature returns a UserDetailsBean, which is Serializeable, and not Remote, the method must return the object by value. I use this all the time in Inprise Application Server, and it works like a charm. Floyd also wrote: In fact, if you use an isModified pattern, you will also have to move this logic into the details bean, or you could (my preferred solution) actually implement all the setters of the details bean, and delegate all calls to super.setXXXX() I answer: To me, the isModified pattern used by Weblogic is a bad pattern. In the EJB world, this should be managed automatically by the container, or at least in a declarative way (set a method as read-only in the DD). Using Inprise Application Server, the container can automatically detect which fields of the bean have been modified, and only update these ones in the database. Some patterns work better with some AppServers... Regards. JB. To make it clearer[ Go to top ] It might be a weblogic problem, but in any case, it's not nice to return instances of your bean to the client - it means they have to have the bean class on their classpath, which is a bit ugly. What happens if the client decides to call ejbFindByPrimaryKey? boom! It also throws away the advantage of beans that the interface and implementation are decoupled; with classic beans, you can replace a CMP bean implementation with a BMP one, or move from a JDBC-backed BMP implementation to one backed by more abstract data access components, all just by changing some options in the deployment and without having to have one classname for multiple implementations. Okay, so maybe not many people take advantage of this ability, but it's an aesthetic thing :). - Posted by: Tom Anderson - Posted on: July 06 2000 10:11 EDT - in response to Jean-Baptiste Nizet What we tend to do at Synomics (all three of us) is break it down a bit further; i posted about this to a JDC forum, by putting a document on the web.. Oh, and we have a finder session bean which makes instances of the details class by going direct to the database, sidestepping all that ejbLoad()ing; it's a bit unclean, but it's faster. Re the isModified thing; some business methods may or may not change the state of the bean - consider an Account bean with an overdraftLimit field and a boostOverdraftLimit method; if the value passed to the method is smaller than the existing value of overdraftLimit, it shouldn't update it. How do you explain this to the container? You can't, so you'd have to declare that method as a mutator, and you'd get unnecessary ejbStore()s. I would say that the best option is to make both available: the container keeps a dirty flag for the bean (cleared by ejbStore); some methods are declared as setting it in the DD, some set it by a call in the code. great ideas, why not post them as patterns?[ Go to top ] I am really impressed with some of the great ideas people in this thread are expressing, and I would like to encourage you to write them up as patterns and post them in our repository. - Posted by: Floyd Marinescu - Posted on: July 06 2000 12:08 EDT - in response to Tom Anderson The more patterns we can accumulate, the more we can help other developers code intelligently, and avoid the problems that made us trip and have to come up with these patterns in the first place! Thanks everyone! Floyd To make it clearer[ Go to top ] Tom wrote: - Posted by: Jean-Baptiste Nizet - Posted on: July 07 2000 11:18 EDT - in response to Tom Anderson It might be a weblogic problem, but in any case, it's not nice to return instances of your bean to the client - it means they have to have the bean class on their classpath, which is a bit ugly. I answer: I agree completely. BTW, I've thought about extending the pattern a little bit: - make the value class implement Cloneable - implement the clone method this way: public Object clone() { ValueClass clone = new ValueClass(); clone.field1 = this.field1; clone.field2 = this.field2; ... return clone; } - implement the getValue method this way: public ValueClass getValue() { return (ValueClass) this.clone(); } It doesn't require much additional code, and avoids transporting the bean class to the client. Tom also wrote:. I answer: I also use a business interface, but I don't make the value class implement it. The bean class implements it and extends the value class. There are two reasons for that: - the bean could contain business methods that don't make sense in the value class - I think it can be confusing for a client to deal with an object without knowing if it's local or remote. BTW, I just realized that it was now deprecated to throw RemoteExceptions in the bean class. This means that the Value class methods (and the other bean methods) don't need to throw RemoteException. That's great, because the client doesn't have to catch them unnecessarily when dealing with a local value object. Finally, Tom wrote about fast finders in a session bean and about methods that sometimes modify the state and sometimes not. I answer: You should really look at Inprise Application Server. Indeed, it can automatically detect if the state has been modified or not (and thus bypass the database update), without needing an additional isModified method. It is also able to update only the modified fields, instead of all the bean state. Moreover, it can load the bean state during a CMP finder, even for a multi-finder. Only one database call is made to load all the beans. Using this, your custom finder, using JDBC code, could become unnecessary (unless the ejbLoad method is complex). Regards. JB. How about Aggregate details objects[ Go to top ] In the same way that you can have a Entity bean refer to another "child" entity bean to create a representaion of a 1-m relationship, could you also have the detail object that is returned by the "getDetails" method of the "parent" entity bean hold a reference to the detail object that is returned by the "getDetails" method of these "child" entity beans? In this way any aggregate entity beans could return one aggregate detail object in one network trip. - Posted by: Jeff anderson - Posted on: July 10 2000 00:35 EDT - in response to Jean-Baptiste Nizet The getDetails method in the parent entity bean would be responsible for calling the child entity bean 's getDetails method and placing it into the parent's getDetails object. Kind of like the following code that would appear in a "parent" entity bean. private Vector mChildEntities = new Vector(); ..... /*the vector would get filled when this bean is loaded by the container according to relational schema */ ParentDetailOb getAllDetails(){ DetailOb pParentDetails=new ParentDetailOb (); pParentDetails.setProperty1(getProperty1()) pParentDetails.setProperty2(getProperty2()) ... for(Iterator i= mChildEntities.iterator(); i.hasNext );i.next()) { int piChildIndex=0; pParentDetails.setChildDetails(piChildIndex++,i.getAlldetails()); } return pParentDetails; } This would assume you are not using lazy instantiation because maybe you have a requirment for the complete graph of the object when using the getDetails method. Alternatively maybe you could have a getAllDetails method that would return the aggregate details object I mentioned above and a regular getDetails method that would return the same object but with null references to the "child" detail objects. I would like to have all my bean extend from some sort of "Aggregate" bean and put this code there. I would then extend this method for each of my entity Beans and call Super.getAllDetails(). if the entity contained any "child" entity references. (Sort of like the composite pattern.) Is this idea reasonable? I would appreciate any thought/comments or suggestions as I am relatively new to the ejb world. thanks Jeff How about Aggregate details objects[ Go to top ] Jeff, - Posted by: Floyd Marinescu - Posted on: July 13 2000 15:25 EDT - in response to Jeff anderson I think this is a good strategy, worthy of being posted as a separate pattern in our patterns repository Jeff. That way, comments on your pattern won't be mixed with comments on this original thread. thanks, Floyd To make it clearer[ Go to top ] Anyone has an idea how to synchronize value (detail) objects between client and server once they were sent to the client? Client to server synchronization looks simple as a client just have to send changed value object to server (or better just a things that were modified thus avoiding network overhead). How about server to client synchronization? What if value object was sent to client and the server data changes? Does the server need to keep track of all value objects sent to the particular clients and inform all of them when change was done so they can update their value objects? - Posted by: Ivan Mitrovic - Posted on: July 19 2000 01:43 EDT - in response to Jean-Baptiste Nizet Ivan JBZ how it's going? ;) To make it clearer[ Go to top ] I think one sensible, safe solution (although perhaps not relevant in all cases) is to make the value object immutable (i.e. no setters) so that client developers are not given the impression that any 'real' data can be changed by manipulating the value object. The data is squirted into the value object in the constructor. Any updates would then be carried out by methods on a session bean wrapping the entity, or other standard techniques. - Posted by: Matt Staples - Posted on: July 24 2000 13:58 EDT - in response to Ivan Mitrovic Also, I would not restrict the value object to just being a container for data - it could also be given more sophisticated query behaviour. For instance, if you use a value object representing addresses, give it operations returning formatted versions of the address and so forth. Pretty standard stuff, I know, but when things are referred to as 'data objects' some people take it a bit literally. These are just vanilla Java objects. Finally, why does the original poster (sorry, I can't see the name at this point in my post) refer to the value object as a bean? Doesn't this just create confusion, when the whole point is distinguishing it from an EJB? Can't we just go back to calling them 'objects'? Matt To make it clearer[ Go to top ] Finally, why does the original poster (sorry, I can't see - Posted by: Floyd Marinescu - Posted on: July 27 2000 09:13 EDT - in response to Matt Staples >the name at this point in my post) refer to the value >object as a bean? I refer to it as a bean because the value object is just a data holder with getters and setters. Java Beans follow a similar conventions. ie: for attribte xxx, you would have a getXXX and setXXX methods.. Thus for those familiar with a Java Bean is, calling the value object a bean would make things clearer in my opinion, but I can see where the confusion would arise if the reader is not familiar with JavaBeans. Floyd To make it clearer[ Go to top ] I agree with Floyd, if a java class uses getters and setters and it is serializable then it fits all the requirements to bea java bean . The various j2ee books out there seem follow the same convention. - Posted by: Jeff anderson - Posted on: August 15 2000 23:53 EDT - in response to Floyd Marinescu Jeff Detail - Entity Bean Synchronization[ Go to top ] I've been playing with this pattern a bit and keep running into one aspect that is giving me heartache. For simple object hierarchies, sync'ing up calls to the detail objects setters is pretty straight forward. However, with complex object hierarchies, (multiple 1-1, 1-M, etc), this seems to get very ugly, very fast. In trying to keep straight in the 1-M relationships, what has been added, removed, or simply changed, can get messy. How have people been dealing with this? I've tried having a session bean handle this as a form of mediator and also tried having the EJB take a detail object as an argument to a method or constructor. Both have been messy. Thoughts? - Posted by: Bill Smith - Posted on: November 06 2000 10:42 EST - in response to Ivan Mitrovic Bill To make it clearer[ Go to top ] Tom, - Posted by: Ash Hassib - Posted on: August 29 2000 20:14 EDT - in response to Tom Anderson I've read the code you you mentioned on that web page. It's really good. One question though, why don't you have the CustomerValue class implement the CustomerRemote directly? What value does the base Customer interface add? It should be ok to provide a local implementation of that remote interface. Thanks. Ash To make it clearer[ Go to top ] I can't speak for Tom, but it appears to me that having the Value class implement the Customer interface and not CustomerRemote allows for the base interface and the Value class to not make any references to any of the EJB packages. In essence, you have a layer that truly knows nothing about the persistent components. The only part of this that is a little ugly is that the methods in the base interface must throw RemoteException. - Posted by: Bill Smith - Posted on: September 11 2000 09:16 EDT - in response to Ash Hassib One question regarding that. Someone mentioned earlier that throwing RemoteException was no longer required. What are the details of this? Is this an EJB 2.0 thing? Bill To make it clearer[ Go to top ] Reply for a post a while ago... - Posted by: callum wallach - Posted on: December 12 2000 07:09 EST - in response to Bill Smith The EJB 1.1 spec states that throwing of RemoteExceptions is deprecated from business methods. Throwing of RemoteExceptions are reserved for system exceptions. Business methods should instead throw application exceptions or runtime exceptions which cause the application server to rollback the transaction etc. Check out section 17.2 of the EJB 2.0 spec (possibly the same section in 1.1, I just don't have it with me at the moment) To make it clearer[ Go to top ] I have go through Tom Anderson's document. It's pretty good, but I still have some comments: - Posted by: Benjamin Jiang - Posted on: March 13 2001 13:14 EST - in response to Tom Anderson in the sessionBean, I don't see any needs to implement the findValueByPrimaryKey and findProxyByPrimaryKey, since these functions have been done in the EntityBean. I think, in the sessionBean, the most important method should be: public Vector findAllValues(); Because this method provides bulk read to the database. Any comments? To make it clearer[ Go to top ] The correct code is: - Posted by: Eron Wright - Posted on: July 24 2000 02:30 EDT - in response to Jean-Baptiste Nizet public UserDetailsBean getUserDetails() { return entityContext.getEJBObject(); } Problem with Details Pattern[ Go to top ] We are using Weblogic server 5.1 and our interfaces and classes looks like this. - Posted by: Kaja Mohaideen - Posted on: September 14 2000 12:10 EDT - in response to Jean-Baptiste Nizet //This interface has business methods public interface IBusiness { public Object getDetails() throws java.rmi.RemoteException; } //This interface has Detail object get/set methods public interface IUserDetails { public Integer getUserId(); public Integer getCompanyId(); } //This class implements IUserDetail interface public class UserDetails implements IUserDetails, java.io.Serializable { protected Integer iUserId; protected Integer iCompanyId; public Integer getUserId() { return iUserId; } public Integer getCompanyId() { return iCompanyId; } } //Remote interface public interface User extends IUserDetails, IBusiness, javax.ejb.EJBObject { public Integer getUserId() throws java.rmi.RemoteException; public Integer getCompanyId() throws java.rmi.RemoteException; } //Bean class public class UserBean extends UserDetails implements IBusiness, javax.ejb.EntityBean { public Object getDetails() { //implementation } //other ejb callback methods } When building the bean ejbc is throwing the following error. ERROR: Error from ejbc: [9.2.7] In EJB UserBean, method java.lang.Integer getUserId() defined in the remote interface must include java.rmi .RemoteException in its throws clause. ERROR: Error from ejbc: [9.2.7] In EJB UserBean, method java.lang.Integer getCompanyId() defined in the remote interface must include java.rmi .RemoteException in its throws clause. ERROR: ejbc found errors What is the reason and what is the solution? Note: Even if we delegate the get/set calls to super class we get the same error. Clarification[ Go to top ] Floyd - - Posted by: Daniel MacDonald - Posted on: September 19 2000 22:51 EDT - in response to Kaja Mohaideen I've read through all the patterns in this site and serveral other sites and I would like you to clarify your terminology. Are Detail objects and Value objects synonymous? If not, how do they differ? Clarification[ Go to top ] Daniel, - Posted by: Floyd Marinescu - Posted on: September 21 2000 00:10 EDT - in response to Daniel MacDonald They are perfectly synonymous. There are many names for this pattern, I just chose to use the name I read in the original article I learned this pattern in. Floyd Over All Design Pattern[ Go to top ] Hi, - Posted by: Parikshit Pol - Posted on: September 25 2000 07:52 EDT - in response to Floyd Marinescu I would suggest not inheriting the Value Object into The Entity Bean, if it is going to cause implementation issues in EJB 2.0. Creating an immutable Value Object(a very good idea) and passing it to Client does make good sense. This solves the Original purpose of reducing the network traffic for this design pattern. As suggested previously this object can have smart get methods like getBySorting or getAfterCalculatingX. Doing lazy loads in the Data Object will give problems in some cases where transactions are being taken into consideration. Entity Beans are already an Object representation of Data with some Logic as well. Value Object does serve a purpose but should it replicate the whole of Entity Bean(stripped of it's Callback methods). If I m wrong please do correct me. Parikshit parikshitpol@hotmail.com Article online[ Go to top ] I agree. Throwing RemoteException from each method doesn't seem right. plus your business objects must now inherit from entity beans, rather than some other class, perhaps linked to your own persistence framework. - Posted by: Jeremy Chan - Posted on: July 03 2000 19:05 EDT - in response to Floyd Marinescu At I describe an approach which not only allows you to generate single Details objects, but graphs of them automatatically. The details objects and business objects are generated from a single schema, and Java reflection is used to map between them, so there is no extra coding required. Check it out at Jeremy Article online[ Go to top ] Hi! Jeremy, - Posted by: Henri Chen - Posted on: February 15 2001 04:58 EST - in response to Jeremy Chan > Check it out at > The provided link does not seem works. Can you point out the javareport issue number that your artical is on? Henri Chen. henri_chen@yahoo.com To make it clearer[ Go to top ] Question about the code: - Posted by: Jianming Wang - Posted on: April 04 2002 11:41 EST - in response to Jean-Baptiste Nizet public class UserDetailsBean implements Serializable { public UserDetailsBean getUserDetails() { return this; } //... } If you return "this", does it increase coupling between your presentation tier? Details Object[ Go to top ] How (if at all) is the advice in this pattern affected if the "Sessions Bean Wraps Entity Beans"-pattern is applied? (That is, if the only clients to entity beans are session beans that access one or more entity-beans within single transactions, implementing "coarse grained" business logic). - Posted by: Mikael Nyberg - Posted on: July 13 2000 07:59 EDT - in response to Floyd Marinescu The answer to this may perhaps depend on whether the beans all run in one container or not. I would think that sensible containers are able to use non-remote calls between beans running in the same container (or is this misguided?) Anyway, I realize that this would address implementation details, so maybe it is irrelevant to my question. Details Object - Problems in Weblogic 5.1[ Go to top ] Hi, - Posted by: Julian Khoo - Posted on: July 25 2000 09:03 EDT - in response to Floyd Marinescu I'm currently designing an EJB using the Detail Pattern, and I'm evaluating both BEA Weblogic 5.1 (with SP4), and Inprise App Server 4. I've been able to deploy it without problems on IAS, but when I try it create the ejb jar using Weblogic's deploytool, I get an error saying " ". Has anybody encountered this problem before? Thanks. Details Object - Problems in Weblogic 5.1[ Go to top ] Sorry, - Posted by: Julian Khoo - Posted on: July 25 2000 09:28 EDT - in response to Floyd Marinescu I left out the error message in my last post. Here it is: "java.lang.NoClassFoundException: No suitable home found for bean". I've tried making the Detail Object serializable, and making the methods throw RemoteExceptions, but the problem still persists in Weblogic. Details Object - Problems in Weblogic 5.1[ Go to top ] I have encountered the exact same problem with using the deploy tool for BEA. I am actually in the middle of getting some answers from technical support on that very issue. I have sent them a jar file of my own and waiting for an answer. - Posted by: Ozzie Gurkan - Posted on: July 26 2000 00:37 EDT - in response to Julian Khoo However, in the meantime, I have actually edited the XML files myself and compiled and deployed the EJB manually. If you go to the documentation on BEA's website for using the weblogic.ejbc tool, you can generate and compile the stubs all in one step yourself without using the tool. After that, you can use the command line deploy tool to deploy the jar or just modify the weblogic.properties file for permanent deployment. My guess is that their tool cannot "reflect" or understand the extra inheritance layer in the bean. For example, I was trying to use the patterns mentioned here and it didn't work. Also, I was trying to extend their BSC smart components--which make up their Buy Beans demo--and it didn't work, either. Here is the exact syntax for generating and compiling the stubs: java weblogic.ejbc -keepgenerated -compiler javac myEJB.jar myEJB_deployable.jar Hint: Make sure you have your environment classpath setup properly: c:\weblogic\lib\weblogic510sp3.jar;c:\weblogic\classes;c:\weblogic\lib\weblogicaux.jar;c:\j2sdkee1.2.1\lib\j2ee.jar; Good luck! Ozzie Details Object[ Go to top ] One comment w.r.t to the bean implementation inheriting from the details object. As good as the idea might be for EJB 1.1 it will not work for EJB 2.0 - style beans. That is because EJB 2.0 bean implementation is an abstract class with abstract getters and setters. - Posted by: Bartek Kiepuszewski - Posted on: August 17 2000 02:10 EDT - in response to Floyd Marinescu My opinion is that to ease the future transition one should not go into a habit of making the bean implementation inherit from the detail object. Also, seems to me that this is not such a great idea from the conceptual point of view as the proper conceptual model would have bean implementation aggregating the detail object, not inheriting from it. Regards, Bartek Details Object[ Go to top ] Bartek, - Posted by: Floyd Marinescu - Posted on: August 17 2000 12:04 EDT - in response to Bartek Kiepuszewski From a purist OO perspective, I agree that aggregating the details object may be better than inheriting from the details object (after all, and EJB is not a special kind of details object, although one might say that the entity bean is a persistent version of the details object). Inheriting from a details object is not a fundamental part of the details object pattern, just a peripheral convenient use of it. I wasn't aware of the ejb2.0 restriction you mention. Can you please elaborate on that? Floyd Details Object[ Go to top ] Floyd, - Posted by: Bartek Kiepuszewski - Posted on: August 21 2000 04:27 EDT - in response to Floyd Marinescu I was referring to the fact that in EJB 2.0 the CMP entity bean should have all getters and setters for every container-managed field defined as abstract methods. That is because when you deploy the bean, the persistence manager should generate the actual class and provide the getters and setters. That is certainly very different from EJB 1.1 where it was enough to define the CMP fields as public attributes of the bean implementation class. Now, clearly inheriting from the detail object that provides the implementation for the setters and getters is no longer a valid thing to do as we should leave getters and setters abstract. Regs, Bartek Details Object[ Go to top ] Hi, - Posted by: Amie Alousis - Posted on: April 02 2001 12:10 EDT - in response to Bartek Kiepuszewski The discussion is evry informatoive and this is the one i'm looking for.. I need u'r help experts.. We need to have a java value object that shuld be passed between client(applet) and ejb What r the pros and cons in the following two designs ..? Inheriting Java Object: By Inheriting the Java Object from the entity bean, the client will get the java object thru remote interface.. Here the attributes of java object shuld be public.. Using Ejb2.0: setting values of the entitybean attributes using abstract set and get methods of ejb2.0 specification. Here we have attributes of java value object as private which is one of our requirements. The Entity bean has the following methods.. abstract public void setId(java.lang.String val); abstract public java.lang.String getId(); abstract public java.lang.String getNumber(); abstract public void setNumber(java.lang.String val); abstract public void setName(java.lang.String val); abstract public java.lang.String getName(); public String ejbCreate(DataObject obj) throws CreateException { log("ejbCreate( )"); setId(obj.getId()); setName(obj.getName()); setNumber(obj.getNumber()); return null; } public void setJavaObject(DataObject obj) { setName(obj.getName()); setNumber(obj.getNumber()); } public DataObject getJavaObject() { DataObject det = new DataObject(); det.setName(getName()); det.setNumber(getNumber()); return det; } Where DataObject is a simple Value Object having attributes and get and setMethods.. Is the above design with EJB2.0 has any disadvantages..? Any help will be highly appreciated.. Thanks Amie Details Object[ Go to top ] Hi. I am developing a EJB solution using the Details Object or the Value Object pattern. I am using TOPLink for Weblogic 2.5.1 GA for entity bean persistence. - Posted by: Pradeep Jaligama - Posted on: September 25 2000 16:48 EDT - in response to Floyd Marinescu I have a business object called Customer with getters ans setters for the attributes. The remote interface CustomerRemote extends the business interface and has methods like login(). I have a details Object CustomerValue which implemnts the business interface. The EJB class CustomerBean extends the value class, CustomerValue and has a method called getCustomerDetails() which looks like this. CustomerValue myClone = new CustomerValue(); myClone.setFirstName(this.getFirstName()); myClone.setLastName(this.getLastName()); myClone.setEmailAddress(this.getEmailAddress()); myClone.setPhoneAreaCode(this.getPhoneAreaCode()); myClone.setPhoneNumber(this.getPhoneNumber()); myClone.setLoginName(this.getLoginName()); myClone.setPassword(this.getPassword()); //myClone.setCustomerId(this.getCustomerId()); return myClone; So I invoke the login method from the client which returns a reference to the EJBObject. Then I do a getCustomerDetails() to get the value class. The problem is, its correctly looking up for the entity bean when I say findByLoginName(String aLogin). But when I do a getCustomerDetails(), its inserting one more row into the Customer table with the same data that was got from the findByLogin() method. I mapped the CustomerBean class to the Customer table in the Builder and the CustomerValue is unmapped. Is there some configuration needed in the TOPLink Builder for the inheritance between CustomerValue and CustomerBean. I have all my getters,setters and the attributes in the value class. Should I duplicate the attributes in the bean class also. I think I am being forced to have the setters in the value object for instantiating a new object. The client would just be accessing the getters. Please suggest me how to do this. Details Object[ Go to top ] Pradeep, it looks like TOPLink thinks that the row that represents your Customer does not exist. You can try calling TOPLink.Public.Sessions.ServerSession.logMessages() to switch on TOPLink diagnostic tracing. This will show you the SQL that it is executing against the DB. - Posted by: Timothy Fry - Posted on: September 26 2000 21:38 EDT - in response to Pradeep Jaligama Also, make sure that the column in your customer table that represents the primary key ( LoginName ?) has a unique constaint on it. The stack trace produced by TOPLink when it tries to insert the duplicate row when the constraing is in place should help you diagnose where things are happening. Tim Details Object[ Go to top ] Oh, and Pradeep, you should really be posting these type of questions to the appropriate forum, i.e., "Enterprise Java Beans Troubleshooting Forum" as this has nothing to do with this pattern per se. - Posted by: Timothy Fry - Posted on: September 26 2000 21:41 EDT - in response to Timothy Fry Tim Details Object[ Go to top ] Hi everybody, - Posted by: Farhan Alam - Posted on: May 08 2001 14:21 EDT - in response to Floyd Marinescu I am new in this thread. Is this pattern applied on Session Bean (stateless)? If so, how do you get the real benifit when you dont have any state in your objects (stateless session bean)? thanks, fa. Details Object[ Go to top ] I am impressed by your pattern . It realy will give - Posted by: SELVA S - Posted on: October 21 2001 12:04 EDT - in response to Floyd Marinescu the improvement to performonce . I think calling the object which carries the Entity Bean's state as " State object " would be more meaning full , because it contains the state of the entity bean. One more think I want to add here is when we use the XML for Data representation , keeping one method so that it will return the object state a XML format will be more helpful while we do session bean coding , the reverse can to for Converting XML to state object. I mean readToXML() and WriteFromXML() methods we can maintain as madatory in the Sate object. Details Object[ Go to top ] This actully reduce the serialization and deserialization - Posted by: SELVA S - Posted on: October 21 2001 12:06 EDT - in response to Floyd Marinescu to much and improve the performance.
http://www.theserverside.com/discussions/thread.tss?thread_id=79
CC-MAIN-2016-22
refinedweb
7,625
58.01
in reply to Re: $_ haters anonymouin thread $_ haters anonymou >. i blinked b4 replying, but you don't have to: $::^M is equivalent to $main::^M - 'main' is the default namespace. Or have I grabbed the wrong end of a pointy stick? cLive ;-) $::^M is equivalent to $main::^M - 'main' is the default namespace. If they weren't syntax errors, then yes, the variable $::^M is identical to $main::^M. But not because main is the default namespace. It's because the empty stash name is interpreted as though you had said main instead. See line 579 of gv.c: if (!*name) return gv ? gv : (GV*)*hv_fetch(PL_defstash, "main::", + 6, TRUE); [download] -- Mark Dominus Perl Paraphernalia Fireworks Stars/planets Lanterns Distant Aircraft/Seacraft Fireflies The moon Glowsticks City lights Aurorae The ISS (or other satellites) Campfires Blinkenlights Other Results (250 votes). Check out past polls.
http://www.perlmonks.org/?node_id=46636
CC-MAIN-2018-09
refinedweb
146
75.91
On 03/11/2012 13:33, William Hubbs wrote:> I highly discourage moving more things to /. If you google for things > like, "case for usr merge", "understanding bin split", etc, you will > find much information that is very enlightening about the /usr merge and > the reasons for the /bin, /lib, /sbin -> /usr/* split. > >.On a somewhat sarcastic note, why don't we just deprecate /usr and move everything back to /? Isn't that, largely, what is being accomplished here? Solaris at least keeps some kernel stuff in / off of /stand (I believe). Linux, after this /usr thing is fully complete, about the only thing left in / that is of any value will be /etc. Kernels were moved into /boot ages ago. I mean, what really is / in the literal sense? It's the first filesystem that the kernel mounts. If you put everything into /usr, including the init scripts and /etc, create a few stub mount points for /var, /tmp, etc (assuming those are separate partitions), then told the kernel that /usr is /, what's the real difference? So I think Fedora's approach, while copying existing behavior from Solaris, is partially broken in this). Heck, why not redesign the original root filesystem layout while we're at it? / - Root. /boot - Kernels, bootloader. /apps - Installed, non-system critical applications. Merges /bin, /sbin, /usr/{bin,sbin}, /usr/local/{bin,sbin}, and /lib and all of its multilib variants. /core - System-critical apps needed to get the system into a MINIMAL, usable state (core device detection, mounting disks, etc) /conf - System configuration data. /dev - Device nodes. /home - User stuff. /data - Variable data. /var's new name. /tmp - System-wide temp dir. /virt - virtual filesystems (proc, sys, ramfs). /svcs - Data dir for services (Apache, LDAP, FTP, etc). /ext - holds mount points for external devices (merges /mnt & /media). /root - Superuser's /home. From that, for the new proposed directories: /apps/sys/bin - System binaries. Only non-critical, system-wide binaries go here. /apps/sys/lib - Like /apps/sys/bin above. Except this can also be duplicated for multilib (lib32, lib64, lib128, etc). /apps/std/bin - Standard program binaries for all non-system, non-critical binaries. /apps/std/lib - Like /apps/std/bin above. Ditto for multilib. /apps/local - If on a stand-alone system, this is a symlink to /apps/std. otherwise, this holds a bin/lib folder that is only for apps installed locally, while /apps/std might be a network mount that holds apps common to multiple systems of the same/similar type of install. /core/bin - Critical system, binaries needed to get the system into a minimally-usable state. Predominantly occupied by various filesystem tools. /core/lib - Libraries, usually static, to support /core/bin. Can be multilib, but a system should have a single ABI that can successfully boot the userland components of the system. /core/inf - Holds minimal information to identify and locate boot-critical devices, typically in the form of a small database of some design, but which can be parsed with no additional dependencies. /core/init - Home of your init system of choice, including all the information needed for various run levels, etc. Its sub-layout is dependent on the particular init system that is installed. /conf - Basically a rename of /etc. The "etc" name doesn't convey any useful information to a user anymore about its true purpose. /conf, however, does. Files stored here will largely be comprised of text files that configure various system services. Like /etc, it's sub-layout will probably be a complete, unrestrained mess. /virt - Everyone loves virtual filesystems. When there was just /proc, everything was alright. Then /sys comes along, and now we've polluted the / namespace with two virtual filesystems. /virt provides a home for those (so /virt/proc and /virt/sys), in addition to others like /virt/shm, and /virt/pts, or even /virt/ramfs if you want. Anything in here doesn't physically exist, and either changes rapidly or is lost once the system loses power. /data - Like "etc", /var's original function has been largely overridden and hardly contains "variable" data anymore. thus, it is reborn as /data, which conveys *exactly* what it is for -- data of some kind, whose presence may be permanent or transitory. Mail spools, caches, print spools, whatever. Fill it with data from /dev/urandom if you want! /svcs - Like /srv, which some people are resistant to using. The original idea is quite a marvel, though, because it never really made any sense to stick Apache into /var/www, or hang the TFTP boot directory off of /, or chroot BIND inside of /etc or /var (or both). /ext - A place for external mounts, either filesystems or devices. NFS, CD-ROMs, thumb drives, Samba/CIFS, etc, it goes here. This replaces both /mnt and /media, the only difference between the two being the same as the difference between two shades of purple. The only exception to this rule is /apps/local above. All other directories retain their original, standard functionality. I thought this up on a whim, it hasn't been tested nor vetted. It's largely meant as a joke, but also to provoke discussion on the current filesystem design and the direction we're getting pulled in with Fedora's declaration that separate /usr is broken. I don't think it is and I don't find their argument very convincing, and probably never will. At some point after this change becomes fully adopted (and it will, trust me), the difference between the / of old and /usr will be so minor, that you could probably move a few files around, chop /usr off into a separate partition, and then pass root=/dev/<where /usr is>, and bring a system fully online, *without a /usr*. And then, after that, someone will come along and propose "the new /usr", and the cycle repeats. But I do, hesitantly, agree that the standard UNIX filesystem has a lot of "traditions" to it that don't make a lot of sense anymore. It's a hallmark of an era where machines usually kept a local copy of stuff needed to start or stop themselves. Now we're in an era where machines aren't even physical anymore. The location of actual data is somewhat meaningless, if you write a program correctly and don't hardcode filesystem paths. So it's probably time to have some kind of a discussion on the filesystem, and what would need to change to bring it up to date with the era of large-scale virtualization and embedded systems that run on your wristwatch, in addition to the standard black (or beige) box sitting on a desk somewhere. Food for thought.. Cheers, --
https://archives.gentoo.org/gentoo-dev/message/c1abc6544b2a47c4faaf665e56517458
CC-MAIN-2017-22
refinedweb
1,120
65.52
This section illustrates you the use of seek() method. Description of code: The java.io.* package provides several input output streams. But there is only one stream that lets you both read and write to it and allow you to move to any point within the file to carry out operations. This stream is RandomAccessFile. This class has two arguments, one of which is a File object or filename to specify the file. A second argument determines the access mode for the file, 'r' for reading and 'rw' for both reading and writing. If you want to perform operations(read or write) from particular position, then there is a need of method seek() that allows you to specify the index from where the read and write operations will start. You can see in the given example, we have created an object of RandomAccessFile class and pass file object and 'rw' mode as an arguments. Using the method seek() we have set the file pointer at the end of the file and write some text into it. writeBytes method- This method of RandomAccessFile writes the string into the file. Here is the code: import java.io.File; import java.io.RandomAccessFile; public class FileSeek { public static void main(String[] args) throws Exception { File file = new File("c:/abc.txt"); RandomAccessFile access = new RandomAccessFile(file, "rw"); System.out.println(access.readLine()); access.seek(file.length()); access.writeBytes("Truth is more important than facts"); access.close(); } } Through the method seek(), you can set the particular index and can perform operations from that index. Advertisements Posted on: July+
http://www.roseindia.net/tutorial/java/core/files/fileseek.html
CC-MAIN-2015-40
refinedweb
264
66.23
Search the Community Showing results for tags 'phaser'. Found 3,280 results how to make the player passed through the ring with correct z-index value syed samoon posted a topic in MightyEditori want to make the player goes inside the ring); }, Impossible Snake 2, one-button snake sequel with more levels BdR posted a topic in Game ShowcaseI've been working on Impossible Snake 2 for a while now and at this point I feel it's finished. You can play a 9 level preview demo in the link below. Impossible Snake 2 demo It is the sequel to Impossible Snake and it's a one-button snake game. You control the snake with only a single tap to change its direction, each time you tap the snake will toggle between turning clockwise and counter-clockwise. So in a way the controls are similar to Flappy Bird. Eat all apples to open the exit, go through the exit to complete the level. There are bonus coins in difficult to reach spots to add an extra challenge. There are some new features compared to the first Impossible Snake: Go through the exit to complete a level Collect bonus coins for an extra challenge Moving spark enemies, avoid them or you'll get electrocuted Laser beams, some can be switched on and off 27 levels + 9 bonus levels 3 different background themes Some sound & graphics tweaks Btw looking back I don't know why I didn't include screen shake in the previous game, as it's simply built into Phaser. It was just adding one line of code but it gives that much more *oomph* when you hit a wall. 😆 Anyway let me know what you think of the game.!). Kill emitter particle on overlap Titus posted a topic in Phaser 2Hello, Just a quick question. I want to kill any emitter particles that overlap with a sprite. I've tried: if(this.game.physics.arcade.overlap(this.emitter, this.sprite)) { this.emitter.removeChildAt(0); //and this.emitter.removeChild(); }. [Phaser] HADRON Vvalent posted a topic in Game ShowcaseYou are the Large Hadron Collider, but are you the best Hadron Collider? --- This is my first complete game. It's far from perfect, but I put a good deal of work into it so I hope you guys enjoy it. Any comments or impressions are welcome. Play it here on Desktop or Mobile (recommended): Details: Stack: JS (ES6) + Webpack + Babel Built with Phaser 2 (started development before v3 release) Source repo: Issue drawing arc graphics with phaser mauro98 posted a topic in Phaser 2I'm trying to create a pie chart with Phaser, using `graphics` to draw each slice of the pie (`graphics.arc(...)`). The problem is that when it renders I get (what I think) an unexpected result. I basically want to draw 3 slices the same size, the code I use looks something like this: function degToRad(degrees) { return (degrees * Math.PI)/180; } var total = 3; var width = 300; for (var i = 0; i < total; i++) { var radius = Math.floor(width / 2); var deg = 360 / total; var start = degToRad(i * deg); var end = degToRad((i + 1) * deg); graphics = game.add.graphics() graphics.beginFill(0xFF0000) graphics.lineStyle(2, 0x000000) graphics.moveTo(0, 0); graphics.arc(0, 0, radius, start, end, false); graphics.endFill() } I've created 3 fiddles to show the difference between a canvas, pixi and phaser based examples, each of them using the same process to draw the slices: canvas: pixi: phaser: Does anyone know why this happens and how can I achieve what I! Buying HTML 5 Phaser based games yan posted a topic in Jobs (Hiring and Freelance)We are buying a couple of HTML 5 Phaser (preferably Phaser 3) games. It could be of any categories and being Mobile Friendly is a must. If you are interested, plz drop a line and I will contact. Thanks, Yan Phaser/WebGL flickering on Chrome for Android v53 JoeKryog posted a topic in Phaser 2.); } }; Text getting cropped / cut-off - (updated issue) yougotashovel posted a topic in Phaser 2The Issue Text object is getting cut-off / cropped at the top and sometimes on the bottom, when using a custom font with a narrow width. (screenshot attached) The fonts in question work correctly in every other environment, and even work with HTML canvas and the regular getContext method of adding text. So i'm fairly positive the issue is isolated to Phaser using HTML canvas. Possible Cause I think issue is most likely happening due to the way Phaser/PIXI calculates the height of text from the width of letters. Possibly using the width of the widest letter and assuming the height? I tried to work out what the source code is doing. Current Workaround The only workaround i've found is rebuilding the font and adding a wide margin to each letter (so the letter boundaries are more 'square'), then in Phaser splitting a Text object into individual Text objects for letters and calculating their position based on letter width, and manually subtracting a value to change the letter spacing. But even splitting and repositioning doesn't work that well (with any font, not just thin fonts) i have to calculate separate margins for even thinner letters like 'I', 'i', or 'l', or wide letters like 'm' and 'w'. I would rather not use BitmapText as i need to use different font sizes. Solutions Has anybody else encountered this issue? Found a solution or a better work-around? Thanks. !() { } } disableVisibilityChange in Phaser 3 dontHaveName posted a topic in Phaser 3Hi, what's an equivalent of stage.disableVisibilityChange in Phaser 3? I don't want to stop all tweens after I switch between tabs.:
http://www.html5gamedevs.com/tags/phaser/
CC-MAIN-2018-26
refinedweb
954
60.24
Most programming languages have a switch or case statement that lets you execute different blocks of code based on a variable. In this article, we will learn what is the switch case statement and its requirements. We will also learn whether python language has a switch case statement or not and if yes then how to apply it. Further, we will learn 3 different methods to implement the python switch case statement, along with complete syntax. So, let’s get started! What is a Switch statement? In computer programming, a switch case statement is a kind of selection control system used to allow the value of the variable to change the control flow of program execution. The switch case statement is similar to the ‘if’ statement in any programming language. The switch case statement is a replacement of the ‘if..else’ statement in any program. The advantages of using the Switch Case Statement in the program are as given below: - It is easier to debug. - It is easier to read the program by anyone except the programmer. - It is easier to understand and also easier to maintain. - It is easier to verify all values that are to be checked are handled. So, in short, the switch statement allows us to execute one code block among many alternatives in the program. Need of Switch Case Statement While programming, there are times when we need to execute the specific block of code depending on some other situation. If the given situation does not satisfy, the code block is skipped and does not get executed. If we check and apply these blocks of codes manually without any format, the length and complexity of the code will increase. A switch statement allows a variable to be tested for being one of a number of possible values, and to have different instructions executed depending on which value is found. Adding a switch statement to an existing program is almost always an improvement. The switch statement is definitely something to use liberally. The only way it can hurt is if you are using an expression that can be simplified away by the compiler, but every expression you accept every day has the potential to confuse the compiler. Switch Statement in C++/Java Before moving towards learning the switch case statement in python language and different ways to implement it let us first understand the switch case statement in C++ or Java language. In the switch case statement, the variable is compared to the list of values. This value is known as case and the variable keeps on checking the value until it becomes the same. The syntax for switch case statement in C++ is as given: switch(expression) { case constant-expression : statement(s); break; //optional case constant-expression : statement(s); break; //optional // multiple number of case statement is allowed default : //Optional statement(s); } Explanation of code: - Expression: It should be an integral type or enumerated type. - Constant expression: The constant expression should have the same data type as the variable to be compared with and also it must be literal or constant. - Break: The break statement is used to terminate the switch statement if the case value matches the variable value. After the break statement, the flow control of the program jumps to the next line of code immediately after the switch case statement. - Default: The default case is used in a switch statement for the situation where no case is executed. Declaring the default case is optional. Example: #include using namespace std; int main () { int marks = '10'; switch(grade) { case '5' : cout << "You scored 5 marks" << endl; break; case '7' : case '7' : cout << "You scored 7 marks" << endl; break; case 'D' : cout << "You scored 10 marks" << endl; break; default : cout << "You scored 0 marks" << endl; } cout << "Your marks is " << marks << endl; return 0; } Output: You scored 10 marks Your marks are 10 Is there any python switch statement? It is usually found that the use of switch statements is very rare while programming in the python language. So, always a question arises whether the python language supports the switch case statements or not? Well, the answer to this question is NO. Unlike any other programming language, python language does not have switch statement functionality. This is also a trick question for students to get in their python assignments. So, we use the other alternatives which can replace the switch case statement functionality and make the programming easier and faster. Let us study each python switch statement one by one below. How to implement Switch Case in Python? As we studied that the python language does not use a switch case statement like other languages, we can use 3 different replacements to implement a python switch case with syntax. - If-elif-else - Dictionary Mapping - Using classes Let us understand each python switch syntax one-by-one in detail below: Method 1) If-elif-else If-elif is the shortcut for the if-else chain. We can use the if-elif statement and add the else statement at the end which is performed if none of the above if-elif statement is true. Python Switch Syntax with If-elif-else: if (condition): statement elif (condition): statement . . else: statement Example: # if-elif statement example fruit = 'Banana' if fruit == 'Mango': print("letter is Mango") elif fruit == "Grapes": print("letter is Grapes") elif fruit == "Banana": print("fruit is Banana") else: print("fruit isn't Banana, Mango or Grapes") The output of the above code will be as given below: Output: fruit is Banana Method 2) Dictionary Mapping If you know the basic python language then you must be familiar with a dictionary and its pattern of storing a group of objects in memory using key-value pairs. So, when we use the dictionary to replace the Switch case statement, the key value of the dictionary data type works as cases in a switch statement. Example: #(3)) print(switch(5)) Output: wednesday friday Method 3) Using classes Along with the above methods to implement the switch case in python language, we can also use python classes to implement the switch case statement. An object constructor that has properties and methods is called a class. So, let us see the example of performing a switch case using class by creating a switch method inside the python switch class. Example: class PythonSwitch: def day(self, dayOfWeek): default = "Incorrect day" return getattr(self, 'case_' + str(dayOfWeek), lambda: default)() def case_1(self): return "monday" def case_2(self): return "tuesday" def case_3(self): return "wednesday" def case_4(self): return "thursday" def case_5(self): return "friday" def case_7(self): return "saturday" def case_6(self): return "sunday" my_switch = PythonSwitch() print (my_switch.day(1)) print (my_switch.day(3)) Output: monday wednesday Conclusion In this blog, we studied what is switch case and its implementation in python language using 3 ways as python does not have the functionality to use a switch statement, unlike other languages. Now you also code for python switch case to try it yourself. Therefore, it is highly recommended to use a python switch statement while programming because it increases the coding efficiency and easier to implement.
https://favtutor.com/blogs/python-switch-case
CC-MAIN-2022-05
refinedweb
1,191
58.42
Issues ZF-8333: Zend_Validate::is() should not fall back to Zend_Loader::loadClass Description Currently Zend_Validate::is() checks if validator class exists using class_exists($className). If it doesn't then Zend_Validate::is() falls back to the Zend_Loader::loadClass($className). This behavior generates "Failed opening" warnings if multiple namespaces are used. Sample code: Zend_Validate::is("2009-01-01", 'Date', array(),array('FirstNamespace', 'SecondNamespace')) Result: Warning: include() [function.include]: Failed opening 'FirstNamespace/Date.php' for inclusion (include_path='...') in ZendFramework-1.9.5/library/Zend/Loader.php on line 83 My opinion is that Zend_Validate::is() should not fall back to the Zend_Loader::loadClass, since all namespaces (since ZF 1.8 as far as I remember) must have all respective namespace loaders registered via the Zend_Loader_Autoloader->pushAutoloader method. When the validator class is not defined after all namespaces are checked then "Validate class not found from basename '$classBaseName'" exception sould be generated. To sum up: In my opinion it's class_exists (via namespace loaders) job to load desired validator class. Posted by Thomas Weidner (thomas) on 2009-11-19T02:38:03.000+0000 class_exists does not load files when no autoloader is set. It is a php method which just checks if a given class exists or not. When you think that PHP itself should add class loading within class_exists then please fill in an issue at PHP. Additionally we should and will not duplicate Zend_Loader within Zend_Validate. Posted by ChieftainY2k (chieftainy2k) on 2009-11-19T03:03:08.000+0000 I was referring to the case when autoloader is set by the Zend_Loader_Autoloader. Posted by Thomas Weidner (thomas) on 2009-11-19T03:12:32.000+0000 And when no autoloader is set then your case would no longer work because using namespaces is independently from a set autoloader. Posted by Thomas Weidner (thomas) on 2009-11-19T03:13:15.000+0000 Changed with r19026
http://framework.zend.com/issues/browse/ZF-8333?focusedCommentId=36140&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2016-26
refinedweb
310
59.09
Event Details POLE (aka Stefan Betke) is one of the most important and influential electronic music producers of the last 15 years. His first three albums ("1", "2", & "3"), released from 1998 to 2000 and packaged in monochromatic blue, red, and yellow sleeves, are classics of abstract dub techno, marrying fantastically deep bass with crispy crackles and pops. In 2011, after an extended period of relative quiet, Betke released a beautiful pair of new Pole 12"s, "Waldgeschichten" 1 & 2, that marked a return (with subtle variations) to the original Pole formula. A new album is due out in 2012. Amazingly, his performance at the Goethe-Institut will mark his Boston debut! Presented in partnership with Non-Event Related link When & Where Goethe-Institut Boston 170 Beacon Street Boston, MA 02116 Wednesday, May 2, 2012 at 8:00 PM (EDT) Add to my calendar Share Pole (aka Stefan Betke)Share Tweet
http://www.eventbrite.com/e/pole-aka-stefan-betke-tickets-2917978753?ref=etckt
CC-MAIN-2015-11
refinedweb
151
55.37
A SAS Professionals attendee and Twitter follower named Marco asks for help: ..struggling to find a method with custom tasks in EG to be able to list the datasets in a library, can you help please? Sure, no problem. This is easy-peasy-lemon-squeezy. First, make sure that you have a reference to the SAS.Tasks.Toolkit.dll in your custom task project. If you used the Visual Studio template to set it up, you've got it. The SAS task toolkit library provides many easy-to-use classes to help your custom tasks deal with SAS servers, libraries, and data, including: - SAS.Tasks.Toolkit.SasServer Represents the basic attributes of a SAS server, including its name, host, and connectivity status. - SAS.Tasks.Toolkit.Data.SasLibrary Represents a SAS library including its descriptive name (from metadata), libref, library engine, and more. - SAS.Tasks.Toolkit.SasServer.SasData Represents a SAS data set and provides access to data set attributes and columns. - SAS.Tasks.Toolkit.SasServer.SasColumn Represents a SAS column and its attributes (name, type, format, and more). To accomplish what Marco is looking to do, the C# code looks something like: using SAS.Tasks.Toolkit.Data; ... // Get a library object SasLibrary lib = new SasLibrary("Local", "SASHELP"); System.Diagnostics.Debug.WriteLine(string.Format("Data members in: {0}", lib.Name)); // list each data set name foreach (SasData d in lib.GetSasDataMembers()) { System.Diagnostics.Debug.WriteLine(string.Format(" Data member: {0}", d.Member)); } The output looks like this: Data members in: SASHELP Data member: _CMPIDX_ Data member: ADOMSG Data member: ADSMSG Data member: AFMSG Data member: AIR Data member: ASSCMGR Data member: BMT ... For example, this snippet puts the data set names into a Windows listbox control: // lbData is System.Windows.Forms.ListBox lbData.DisplayMember = "Member"; lbData.DataSource = lib.GetSasDataMembers(); 3 Comments Hi Chris, Thank you for your help. We had explored this method but as I should have probably said on my initial tweet (but was limited by the character allowance) we are using Enterprise Guide Version 4.1. Unfortunately this does make it more difficult for us as we cannot make use of the Toolkit. For anyone using 4.2 and above your solution will be great and should save a lot of time and effort. I have found a work around by calling a SAS macro from within the custom task, which utilises the Vcolumn dataset and then reads the values back to the custom task. I was wondering if you knew of anyway in 4.1, possibly using the Workspace Server that I could achieve the same results. As I said I have already implemented the work around but if I can use an alternative, more efficient method that would be great. Unfortunately, I cannot seem to find any documentation that would suggest I can achieve this. Thank you for all your help. Marco Marco, It might be easier for you to use the SAS OLE DB IOM data provider to read the contents of VCOLUMN and other "metadata" dictionary tables. There are examples -- 4.1 compatible -- in the SAS Catalog Explorer within these source files. Specifically, look at CatalogExplorer\CatalogExplorerForm.cs. Thank you for your help Chris. It is much appreciated. One Trackback [...] I described in a previous post, I'm using data binding to populate the UI controls with the content of the SAS data [...]
http://blogs.sas.com/content/sasdummy/2012/07/16/listing-the-data-sets-in-a-library-within-your-custom-task/
CC-MAIN-2014-52
refinedweb
559
57.98
Wikibooks:Reading room/Archives/2007/November From Wikibooks, the open-content textbooks collection CAPTCHA at login Is there any way to remove the CAPTCHA at login for a specific user? For example if a user is blind, or is a bot (of the legit variety) which can't handle a CAPTCHA? I made one mistake on the password trying to log in to my bot's account, and now I have to wait a while (anyone how long?) until I can try again without the CAPTCHA :( – Mike.lifeguard | talk 01:35, 31 October 2007 (UTC) - Someone fixed this. pywikipediabot now loads the CAPTCHA so you can solve it :) – Mike.lifeguard | talk 22:31, 1 November 2007 (UTC) Wikijunior in Trouble Wikijunior is in trouble. Since the new book of the quarter was taken off the front page we have gotten very little traffic. For example, in the last 14 days there have only been 6 edits adding any amount of substantive content in all of Wikijunior by anyone not named xixtas. I'm really not sure what to do at this point, but I hate to see the project die the way it has. Does anyone have any idea how we can generate more traffic at wikijunior? --xixtas talk 03:16, 18 October 2007 (UTC) - Maybe improve the quality of the Wikijunior page and add the featured wikijunior books to it? --darklama 04:05, 18 October 2007 (UTC) - Try recruiting contributors from WikiProjects on en.wp? I did that for First Aid and got one person to join the light side. For an entire project, you'd probably be able to do better. I don't know which WikiProjects might be good targets though. – Mike.lifeguard | talk 04:08, 18 October 2007 (UTC) - What's counter-intuitive here is that there still are wikijunior books featured on the main page, more then one at a time even. Maybe we need to tweak the main page to feature a more prominent link to wikijunior? Maybe even replace the main page entirely with a "Portal" that would give visitors the option of visiting the with "real" main page, or the wikijunior main page? Maybe we need to do some kind of advertising blitz, both on wikimedia (mailing lists, blogs, wikipedia projects, etc) and off (websites for teachers and students). A lull in a project doesnt necessarily mean it's "dead" or "dieing", but it could just be a temporary reprieve. Whatever needs to be done to reverse the trend should be done though, because Wikijunior is an important part of what we do here. --Whiteknight (Page) (Talk) 12:41, 18 October 2007 (UTC) - I added a more prominent link to Wikijunior on the main page, hopefully that will attract some attention. We already have a link to it in the side bar, where else can we advertise? Is the solution to put the collaboration of the quarter back onto the main page? If you can come up with a template that is sufficiently small, we would be able to put it right above the list of other featured books. --Whiteknight (Page) (Talk) 13:17, 18 October 2007 (UTC) - As you've said there is more then one featured wikijunior book now, so it seems like having a quarter book again wouldn't make a difference. I think the more prominent link to Wikijunior was a good step, maybe add the wikijunior logo above it though? I suppose keeping people interested in writing books for children could be a problem. What about trying to attract teachers, parents, grandparents, etc? How about trying to find some old children's books and children's textbooks that are now public domain that could be added to wikijunior? Could it just be the time of year? How long has Wikijunior appeared to have been in trouble? --darklama 13:47, 18 October 2007 (UTC) - According to the page at meta, the wikijunior logo is just a proposal, not fully accepted. Let's start a process to formalize that logo, in parallel with the new wikibooks logo that is being discussed. Having a good logo for Wikijunior that we can plaster all over the place will certainly help things. --Whiteknight (Page) (Talk) 13:58, 18 October 2007 (UTC) - I don't know who's "in charge" of the current edition, but Social and Cultural Foundations of American Education (in its several editions) is written by education students. Maybe they'd be willing to put us in touch with the ECE instructors? --SB_Johnny | PA! 18:29, 18 October 2007 (UTC) - @Darklama - I would say that contributions to Wikijunior dramatically declined in February or March of 2007. @WhiteKnight - As far as publishing Wikijunior goes, I would like to figure out how to launch a stable version of Wikijunior at Wikijunior.org (which is owned by the foundation.) This is apparently something that was already okayed by the foundation, at one time, but I don't think anyone had ever decided how to do it. Anyway, I would like to propose that that website be launched, running mediawiki with a special default skin. One that removes most of the extraneous links and has bigger "kid-friendly" fonts and design features. The versions on this site could be protected and only admins could update them. I'm happy with any process that will move the Wikijunior logo selection process forward. @SB Johnny - Finding a way to get more teachers involved would be nice. -- xixtas talk 02:59, 19 October 2007 (UTC) - As a newbie here I find it quite confusing there is all these wiki sections. I don't know how new the wikijuniour part is but understand it takes time for search engines to list the content. The link as added whiteknight added above will help. The problem will nearly always be that someone searching will be provided with wikipedia links before they are provided with wikibooks links, thus the traffic goes to wikipedia or other sites and not to wikibooks - We don't know how many are reading the Wikijunior books merely how many are editing them. This could be a good thing as it may mean most of the books are quite advanced in development so need little editing (but probably not). One thing that definitely discourages people from editing or creating new Wikibooks titles (including myself) is the differing policies that Wikijunior has to Wikibooks. All this voting for new titles is very off-putting - my advice to anyone wanting to create a Wikijunior book is JUST DO IT! Xania talk 18:59, 20 October 2007 (UTC) - I wonder when the whole having to vote for new titles came about and if its something that could just be marked as rejected/obsolete? Was there every any discussion and consensus decision that new titles have to voted on? I have a hard time believing it was something agreed to. Maybe thats what needs to be done to make Wikijunior better and encourage more contributions. --darklama 19:13, 20 October 2007 (UTC) reset FYI, Rob Horning apparently declared it to be policy on 17 August 2005 because the previous policy was that no new books could be started. – Mike.lifeguard | talk 19:27, 20 October 2007 (UTC) - I don't see any indication that Wikijunior:New Title Policy was ever declared an official policy nor ever discussed and agreed to, but rather Robert had started it on August 16 2005 as a proposed policy so new books could be started. I think it could be marked as rejected with a link to Wikibooks:What is Wikijunior --darklama 19:52, 20 October 2007 (UTC) - I was just paraphrasing the first sentence of Wikijunior talk:New Title Policy. That sounds like as good a solution as any. – Mike.lifeguard | talk 20:32, 20 October 2007 (UTC) - It's my understanding that you can create a new book at any time, but that they try to reduce the number of new books being worked on simultaneously to try and consolidate effort. I've already started at least one book without going though the voting process, and it's a successful book (if I will toot my own horn a little). Maybe the new title policy needs to be "tweaked" to reflect this. --Whiteknight (Page) (Talk) 01:25, 21 October 2007 (UTC) - I'm sorry I havn't injected my $0.02 into this discussion until now, but I'd like to clear this up a bit. When Wikijunior was first started, those "founders" of the original project (I wasn't really one of them) had a bunch of huge and grandiose ideas, including trying to start a monthly magazine and getting all sorts of grant money, including the original "seed money" that was donated explicitly to help get the project off the ground. BTW, I have seen absolutely no accounting of that original grant of money, which was fairly substantial, from the WMF. Even the original terms of what that money was supposed to be used for has never really been nailed down effectively, and as far as I can tell, it got dumped into the great black hole pit of the Wikimedia server farm. I could go on even more, but moving on..... - The number of books for Wikijunior was restricted in the beginning to just the original 3 titles, Wikijunior Solar System, Big Cats, and South America. During the first year or so, there were several attempts to start additional Wikijunior books from several individuals, but the "policy" was to keep just those books, and Wikibooks admins simply deleted those "alternative" Wikijunior books, usually with a more or less polite reply as to why additional Wikijunior books couldn't be written yet. By the time I got involved with Wikijunior (and a couple of months after I became an admin) I had to deal with one of these "alternative" Wikijunior books, and I didn't feel quite like deleting it outright. So I tried to come up with a system that could generate additional titles, but at the same time help out in reducing the huge number of new book titles that has been an ongoing problem with Wikibooks even from the very beginning. Since absolutely none of the original "founders" of Wikijunior were even active at the time (and to the best of my knowledge, still aren't), I tried to set up some new policies for Wikijunior and make a request for comments about the new policy on the Staff Lounge. - As there wasn't really any formal policy I could invoke in the Wikibooks Deletion Policy to remove non-approved Wikijunior books from the new Wikijunior policy, I didn't see any real reason why I should be zealous and delete the new Wikijunior books that were created outside of the new book process. A sort of mutual understanding came up, but never formalized, to not necessarily put the Wikijunior books on the "front page" of the main Wikijunior page (or on the main page of Wikibooks) that were created out of the new book process. They were still noted on the talk page, but otherwise not given the same distinction. - This was also a sort of experiment to see if restricting the number of titles on a sub-project like Wikijunior could help improve the overall writing quality of the existing books. In some ways, I would like to think it was successful, as there have been several Wikijunior books that have been created over the years which have a fairly high quality, and the number of Wikijunior books that achieved "Book of the Month" or "Featured Book" status is quite high compared to the rest of Wikibooks in general. But this is a point that certainly can be debated and argued over. - I would love to see some sort of restoration of a "Wikijunior" section on the main page of Wikibooks, but I have deliberately chosen not to engage in a sort of edit war, particularly on the main page. I hope that we can get another "generation" of Wikijunior contributors somehow, but it is going to take some real creative work to get that to happen. I certainly hope the effort to request assistance on foundation-l turns out to help even a little bit. --Rob Horning 20:52, 31 October 2007 (UTC) - Hello Rob, how are you? The history is interesting, I certainly hope some of it gets distilled into History of Wikibooks. The post to foundation-l was very depressing. Few people commented on it at all. I posted about it on my blog and got a few comments, but nothing helpful. That the original grant money has all but vanished is depressing as well, because I can think of a lot of things we could do with that money right now to help revitalize wikijunior. Of course, the foundation has been terrible at keeping people informed of finances, and this current "emergency" fundraiser is evidence of this. Pursuing grant money is something that I believe we should be doing aggressively, but I wouldn't allow the foundation to "oversee" that money should any be awarded. Not, at least, without some kind of accountability. - Also, what you said about the genesis of the Wikijunior new book policy is eye-opening as well. I can't believe that people were so restrictive about the creation of new books, and that as much as anything could be a reason for the low popularity of the wikijunior project. Maybe we need to rethink the new book policy from the ground up, to make it more accessible to new authors. I would like to get User:Xixtas' take on that. --Whiteknight (Page) (Talk) 22:26, 31 October 2007 (UTC) Update I've posted a message about Wikijunior to the foundation-l. I'm hoping that it attracts some attention and gets the ball rolling on a few ideas. Specifically: - I've started a new logo selection process for wikijunior at meta:Wikijunior/Logo. I would like to try and keep this process in sync with the wikibooks logo selection discussion, and try to maximize parallelism between those two efforts as much as possible. - I suggested turning into a read-only host for completed wikijunior books. Doing this may require some technical effort on our part because the devs are very busy. Things such as designing a new child-friendly interface for the site are things that we can't expect the devs to do for us. - I brought up the idea of physical publication, or inclusion in the OLPC project. Both things would be good. Let's see how the foundation reacts to this. - We need to come up with outreach ideas for attracting new contributors to wikijunior. I think it's becoming obvious that we arent going to attract new contributors just by advertising on this site. We need to reach out and bring in new contributors. we could spam wikipedia, but i don't feel like that route has ever been fruitful in the past. We may need to find a way to contact children's educators directly. What kinds of forums could we utilize for this? I do want to see what the foundation people say, but I also realize that a lot of the burden of any changes is going to fall onto our shoulders here. That's why I would really like to get more input from people here. --Whiteknight (Page) (Talk) 15:08, 26 October 2007 (UTC) First time on the Wiki and am confused I thought this was a book discussion page - is there a subject area? This is my first time on the Wiki so please excuse my ignorance and post some suggestions about finding a spot or locale on books online for elementary. Thank you! —The preceding unsigned comment was added by 69.55.136.205 (talk • contribs) 19:48, November 3, 2007. - There is a discussion page for every module of every book. This page is for asking general questions. - We're currently working on categorizing books by reading level, but it is only just beginning. For now, your best bet is to search for books by subject instead. You may be interested in WB:AS and WB:ABS as starting points for your search. Hope that helps. – Mike.lifeguard | talk 22:07, 3 November 2007 (UTC) Wikibooks:Special groups department What do people think of this page? In all my time here as a wikibookian, I've never even heard of it, so I can't imagine that most other people have either. It's also the only non-user page that includes Template:Wikijunior. I was going to use that template for a different purpose when I found this page. Maybe I should have brought this up on VfD, but we don't necessarily need to consider deletion. --Whiteknight (Page) (Talk) 13:30, 1 November 2007 (UTC) More Categorization templates I've created a few simple templates that can help to make clear some aspects about a book to new readers. These are: - {{Prerequisite}} - {{Corequisite}} - {{Reading level}} Also, I've started a draft of a description of various reading levels at Wikibooks:Reading Levels. There is now a subject page to keep books organized by reading level at Subject:Reading Levels. --Whiteknight (Page) (Talk) 14:50, 1 November 2007 (UTC) - I think this is a good idea, thank you for making it; I would support the guideline at first glance but should take a closer look. Mattb112885 (talk to me) 19:14, 1 November 2007 (UTC) - Maybe it shouldnt even be a guideline, maybe we need a different classification of page such as "information page" or something. Whenever I write a new page in the Wikibooks: namespace, I always feel like i have to tag it with {{proposed}}. If we can find a better place to describe it, we could delete that information page entirely. - As to the templates, information about target audience, prerequisites, and other information that should be available before reading really makes sense to be put into template form. I'm actually surprised that nobody (myself includeD) have done this previously. --Whiteknight (Page) (Talk) 21:10, 1 November 2007 (UTC) - Forgive me if i'm wrong, but i'm pretty sure the infobox templates have been abandoned wholesale. I know that I do not use them for the books that I write, and I find that it's very rare to see infoboxes in books that other people are writing too. If the point that you are making that that people have previously tried to include this information, then you are correct. However, if you are trying to say that we should all turn to using the cumbersome infoboxes, then I would have to disagree with you strongly. - Information pages could go into the help pages, although I don't feel that is an optimal solution for it. I would want to see a significant cleanup of the help space before we all decide to try and cram more unorganized garbage into it. I don't see a reason why information about our books could not be hosted in the Wikibooks: namespace. I don't think it needs to be reserved for policy or guideline pages, but instead should be free to contain information pages. Notice that a page that contains information about Wikibooks isn't necessarily "helpful" in the way that I think people going to the help pages are interested in. --Whiteknight (Page) (Talk) 22:03, 1 November 2007 (UTC) - I don't think the infobox templates have been abandoned. They were updated a bit ago when discussion regarding removing some information from the infobox templates was discussed. I was merely suggesting that the infobox template provides for the same info and that this might be duplicated effort. Well if you think they should go into the wikibooks namespace, maybe we need a new template to make it clear what informative pages in the wikibooks are not to be mistake for policy/guideline proposals. However I don't see why the help namespace has to be limited to generic or general help. --darklama 22:22, 1 November 2007 (UTC) - The only limits that i'm trying to put put on the help namespace is that it should be organized, and it shouldnt be filled with all sorts of unrelated things. If we move this to the helpspace, it's just going to disappear like all the rest of the things in there. --Whiteknight (Page) (Talk) 01:04, 2 November 2007 (UTC) Is this allowed? [1]. I didn't want to comment, since licensing isn't my specialty, but I think it warrants some attention. Requiring people who contribute to that particular book to PD-license their work seems at odds with the "all contributions to Wikibooks are considered to be released under the GNU Free Documentation Licence" notice on the edit page. As well, the notice would have to be placed on every page of the book to come anywhere close to binding, I think. – Mike.lifeguard | talk 17:54, 30 October 2007 (UTC) - I dont know, i'm not an expert in it either. If it's here, I think it has to be GFDL compatible. However, people have tried to cross-license books in the past. So long as the notice is prominent, I'm inclined to say that it's acceptable. the Roman Catholicism book is attempting to be released in the same way (although it's not a separate book anymore). This is an issue that we had discussed previously with all the other copyright issues, and we never made any substantial progress on. --Whiteknight (Page) (Talk) 18:03, 30 October 2007 (UTC) - I would say its not appropriate because public domain means different things in different countries which may not be compatible with the GFDL, some countries may not even recognize/acknowledge public domain, duel-licensing under both GFDL and PD makes no sense - however its not even saying that, and because of all those issues I think its against Wikibooks' policy to allow it to remain here. Public domain does not guarantee the freedoms required by the GFDL in all countries that recognize its enforceability. --darklama 19:31, 30 October 2007 (UTC) - I dont think the issue is whether or not it can remain here, PD materials are allowed to be uploaded to wikibooks. If the licensing is the problem, then we remove the licensing tag from the book and say that it is simply released under the GFDL now. If one person makes an edit to the page that is released under the GFDL, the entire derivative work becomes a GFDL work. --Whiteknight (Page) (Talk) 20:02, 30 October 2007 (UTC) I've had a couple interesting posts on my blog about this, and people there seem to generally agree with what we are saying here. PD really can't be allowed in this instance, because we can't require contributors to release works into the public domain. I'm going to remove those templates from the book,s and possibly delete the templates all together since they should never be used. --Whiteknight (Page) (Talk) 01:16, 1 November 2007 (UTC) Hi Hi! I was told to introduce myself as a new user here, wow it's so nice to be a new user again ^^. Anyway, my name is Jóhann and I am editing here mainly for langauges. My first book, Manx, I am trying to complete. My main project is the Icelandic wikibooks where I have definitely shaped up the Language department and making it the most active department there, by making bookshelf pages for the languages with beginners, intermediate, and advance guides in the common languages to not so common (like Kazakh). Maybe I can contribute that here. I am more interested in a Tutorial guide rather than divided langauges like Nouns, Adjectives, Colours and such, which is not a good way to teach a language. So I also plan in the future to adjust the Icelandic book to a tutorial guide since that has not seen much activity in a while. Uhm, what else...I am a university student studying langauges (nice guess?), and I am also a beraucrat on the Chechen wikipedia and sysop on the Faroese Wikipedia. You want to contact me, leave me a message on my talk page obviously. Ciao! :) --Girdi 23:51, 4 November 2007 (UTC) - Improving those books to be tutorials and not simply lists of words broken by category is a good thing. Good luck in your work, and let us know if you need any help. --Whiteknight (Page) (Talk) 23:54, 4 November 2007 (UTC) relatively new to Wikibook I recently started making significant additions to the Wikibook for Celestia which hadn't been worked on for a while. Some kinds of misuse of English tend to grate on my nerves, so I may be making small changes to some other titles occasionally, as well as grumping in some of the Reading Rooms. Whiteknight's welcome message inspired me to introduce myself here. Of course, help on the Celestia book by other astronomy enthusiasts would be welcomed! Selden 20:50, 30 October 2007 (UTC) - Hi Selden and welcome! We would be happy to see you clean things up if you so desire! Celestia looks like a very interesting book, I'll have to take a closer look at it some time. Regards, Mattb112885 (talk to me) 22:32, 4 November 2007 (UTC) Collapsible Tables and related It would be possible to have collapsible tables like wikipedia, seems that the Mediawiki:Common.js it's not the same for wikibooks and thus, for example, renders the template Template:hidden useless: Body text line 1 Body text line 2 It would be nice to have these tables :) Bunder 11:54, 31 October 2007 (UTC) - This template isn't useless to me, it appears to work perfectly as expected. What doesnt it do that you are expecting it to? Can you give an example of a wikipedia collapsible table for comparison? --Whiteknight (Page) (Talk) 14:39, 31 October 2007 (UTC) - The template here just seems to need to be updated to include more optional parameters. Other than that there is no differences that I saw from a quick look. Just because MediaWiki:Common.js isn't identical to Wikipedia's doesn't mean that the code to allow collapse boxes isn't here. I don't have any problems with that box either. Its currently collapsed and when I click it, it expands. Is it not collapsed? Is it not expanding? Unless we know what isn't working for you, there isn't anything we can do. --darklama 14:41, 4 November 2007 (UTC) Can anyone help me understand why the hidden template isn't working for me here? --xixtas talk 01:28, 9 November 2007 (UTC) - For complex parameter values which break templates, always try using parametername=whatever or #=whatever. My sig breaks just about everything, so I'm used to it now ;) – Mike.lifeguard | talk 01:47, 9 November 2007 (UTC) Hello from Fyedernoggersnodden Hey; Thanx as well to Mike.lifeguard for the welcome, even if (As I presume) it was just an AWB thing. I'm a Computer Science and Math student myself, and am interested in doing what I can to improve the wikibooks that are within the realm of what I've learned so far. For now, though, I'm reading Cognitive_Psychology_and_Cognitive_Neuroscience between classes, out of sheer curiosity.--Fyedernoggersnodden 00:34, 8 November 2007 (UTC) - No AWB involved; we don't use bots to welcome here. I'm glad you're interested in Cognitive. I'll be contributing to that once I have time. If you have suggestions for where to start as you're reading through it, drop me a note on my talk page. See you around! – Mike.lifeguard | talk 02:04, 8 November 2007 (UTC) World Stamp Catalogue/Soviet Union I represent the Russian WikiProject Philately. My colleagues and I want to contribute to World Stamp Catalogue for Soviet Union and Russia. All interested persons are welcome to join us. --Michael Romanov 19:10, 6 November 2007 (UTC) Hello! I am too.--Mariluna 19:29, 6 November 2007 (UTC) Hi, I am yet another colleague of Michael Romanov from among the contributors to the Russian Philately Project so nicely introduced above by him. Please feel free to contact me. --Leonid Dzhepko 20:36, 6 November 2007 (UTC) - Excellent! Welcome to Wikibooks, let us know if you need any help. --Whiteknight (Page) (Talk) 22:45, 6 November 2007 (UTC) - Thanks Whiteknight! We intend to make Soviet Union section of the WSC bilingual (both English and Russian) for convenience of users. Unfortunately, some talk on discussion pages may be in Russian, since not all Russian WikiProject Philately participants are well versed in English. Hopefully it is OK with Wikibooks. --Leonid Dzhepko 08:55, 7 November 2007 (UTC) - I think that would be a problem here. This is English Wikibooks, not Russian Wikibook, and this book isn't about learning Russian. Both the book pages and discussion pages need to be in English so English readers and writers understand whats going on. --darklama 14:08, 7 November 2007 (UTC) - Dear Darklama, as Leonid kindly explains above, the Wikibooks Stamp Catalogue for Soviet Union and Russia will be in both English and Russian that would be extremely useful for Russian-speaking users and readers who cannot speak English. Would it be better if we at first provide stamp information in English following its translation in Russian? The talk page currently contains discussion of technical aspects only, first of all templates, and we provide English names for section titles. We cannot secure all the discussion in English only because there are only two of us who can speak and write English. As you can see, we have two templates and five versions now and are trying to improve them and select the best one. With kindest regards, --Michael Romanov 17:07, 7 November 2007 (UTC) - The problem is that its suppose to be a book cataloging stamps for English speaking stamp collectors, this page would be inconsistent with the rest of the book which I think consists only of English. Also there are plenty of English-speaking users here who cannot speak Russian who could not participate in any of the Russian conversations and could not improve the Russian translations. Perhaps a solution would be to create a Russian translation of this book on Russian Wikibooks and those of you from the Russian Philately Project that can speak English can at first help in the translation process? After that then those who can speak English and Russian can work on improving the book or that page at both websites? Creating a sort of interlanguage collaboration between the two Wikibooks projects to improve both books, while making it easier for those who can only speak one language to help improve there local language version. --darklama 14:03, 9 November 2007 (UTC) - I don't necessarily see it as a problem for conversations to be held in a different language here. However, the burden is on you to ensure that english-speaking participants are included in the decision-making process, should any such users wish to participate. So long as you are willing to translate, it shouldnt matter what language you speak in. As for the content pages, if you want to do a russian version, you may be more interested in hosting a parallel version at the Russian Wikibooks as well, and include an interwiki link from here to there (and vice-versa). That's probably the best solution, so that russian speakers will be able to find and participate in the book. --Whiteknight (Page) (Talk) 17:44, 9 November 2007 (UTC) Exactly! Dear Darklama and Whiteknight, this is what we intended to do and what we did. We develop the English version only here, and the Russian parallel version there, at the Russian Wikibooks. And both versions have already been linked with interwiki. You cannot imagine how excited and enthusiastic the project contributors are and we thank you so much for all your outstanding support and friendly advice. Have a great weekend! Sincerely, on behalf of the Russian WikiProject Philately, --Michael Romanov 10:42, 10 November 2007 (UTC) Hi, world! That`s me. Nickpo 14:00, 7 November 2007 (UTC) Hello hello! i am antome, i will be on wikibooks, mostly in the "Game Maker" areas. I have just made the An outline of game maker book. —The preceding unsigned comment was added by Antome (talk • contribs) . - Hello Antome, welcome to Wikibooks! I'll take quick read-through of your book, let me know if you need any help with it. This is hardly an area of expertise for me, however. If you need any help, or if you have any questions about how things work around here, leave us a question and we will get back to you quickly. --Whiteknight (Page) (Talk) 19:10, 12 November 2007 (UTC) WritersUA conference I dont know if everybody knows this, but I got invited to the WritersUA conference in March to talk about Wikibooks to an audience of software documentation writers. The information about my presentation is located at: Two notes: - If anybody has any suggestions on what I should talk about, I would love to hear them. My presentation is supposed to last about 75 minutes, including about 15 minutes for questions (at least). The people there are familiar with wikis, and they should all be familiar with wikipedia, so that's a good starting point. Most of them should also be familiar with Copy-Left licensing, so if I talk about that at all, it will be brief. - If anybody is going to be in the Portland area March 16-19, let me know and we might be able to meet up. This could be a great opportunity for us to really advertise wikibooks and attract some new contributors/readers. --Whiteknight (Page) (Talk) 03:05, 5 November 2007 (UTC) What's up with the over-protection Coming from the most vandalized wiki (the English Wikipedia), I have to say there is an unsettling amount of page protection going on here. This runs counter to the defining quality of wikis, which makes them so great. I saw a couple of simple typos I wanted to correct, but couldn't because they were protected. I don't know if these pages are fully protected or just semi-protected (no anon edits), but it doesn't really matter. As editing Wikipedia, Wiktionary, and Commons, takes up all my time already, I have no plans to be a consistent or even semi-consistent editor for WikiBooks, and thus see no reason to create a user account at this time. With me, WikiBooks is only losing two trivial edits, but in general is probably losing much much more as far as potential editors go. A few years ago, I merely read articles on Wikipedia and didn't think to edit them, however after seeing some obvious spelling and grammar errors, that "edit this page" button was just begging to be clicked on. Everytime I ran into an error when reading articles, I would fix it. I found myself going out of my way to correct articles (i.e. going to pages I had no interest in reading). When I got involved to the point where I was going to talk and other namespace pages, I decided to get a username to be part of the community - not to simply edit articles. If I didn't have this open experience, I wouldn't be a Wikipedia editor at all, let alone a very dedicated one. I got involved with Commons and Wiktionary in much the same way, usually because of trans-wiki linking. Likewise, I came here to find a appropriate link to use on Wikipedia, saw a couple of errors I wanted to correct on my way, which could have been my first step into being a full-time editor, but got derailed by all the protected pages. I'm sure others feel the same. This is very unfortunate, as WikiBooks has lots of potential, but desperately needs more editors. Vandalism sucks, but it's small price to pay for freedom. Vandals are annoying, but editors are more important. On Wikipedia, we have a behavioral guideline called "Assume good faith", I suggest WikiBooks adopt this too. Sincerely, one less editor aka 68.74.158.43 17:48, 11 November 2007 (UTC) - I'm sorry you won't be editing. I'm not sure which pages you're referring to. So far as I know, Wikibooks actually has far less page protection than Wikipedia. Assuming good faith doesn't mean unprotecting everything; there is a balance to be had. If you like, feel free to tell us where the balance is off. – Mike.lifeguard | talk 18:12, 11 November 2007 (UTC) Template:Nowcommons Could someone familiar with template syntax get this to put images into Category:NowCommons unless a different name is specified, in which case put the image into Category:NowCommons (different filename). This is because images which have the same filename at Commons can simply be deleted, whereas those which have a different filename need extra attention before deletion. Thanks in advance. – Mike.lifeguard | talk 00:49, 9 November 2007 (UTC) - Okay, I think that fixed it. Double check me, but the few images i looked at seemed correct. --Whiteknight (Page) (Talk) 02:30, 9 November 2007 (UTC) - I think the categories were switched; all the images listed there now have the same name on commons. I think our friendly job-cue-category bug is going to keep them from switching over though. I'll test by moving and tagging another image. – Mike.lifeguard | talk 03:35, 9 November 2007 (UTC) - No, your version was right. I should've known better... – Mike.lifeguard | talk 03:48, 9 November 2007 (UTC) I found the real problem. When you hit "add {{nowcommons}}" on CommonsHelper, it always puts {{NowCommons|1=filename.ext}} regardless of whether the filename changed or not. Is it possible to put images into the different filename category if parameter1 != FULLPAGENAME? – Mike.lifeguard | talk 03:53, 9 November 2007 (UTC) - Well there's nothing like a template breaking to spur one to learn about parser functions. I finally figured out what the real problem was & fixed it. *feels proud* – Mike.lifeguard | talk 04:33, 9 November 2007 (UTC) {{query}} I don't know if anyone has noticed an error that occurs sometimes with the {{query}} template. Here is a screenshot showing that some of the contents of the template are being shown on the page. Purging the page undoes this. Ideas? – Mike.lifeguard | talk 21:19, 11 November 2007 (UTC) - A while back, darklama came up with a mechanism to automatically move a page into the speedy delete category after a certain number of days. It appears to me that it's this mechanism that is failing. I dont know enough about it (and don't have the time tonight to go picking through it) so you are going to need Darklama's input on it. Judging from the nature of the error, I would guess that {{Lastedit}} is the culprit here. I assume that under some conditions, this template returns the null string. --Whiteknight (Page) (Talk) 01:10, 12 November 2007 (UTC) Wikibook on Critical Thinking? Critical Thinking is something that I've often found amiss in the last few weeks. I wonder if a Wikibook teaching it would be at all useful. Here's what I could imagine in terms of contents: - Psychology: reading between the lines - Logic: recognizing good and bad arguments - Rhetorics: noticing when you're being influenced - Science: preparing for the untold part of the picture - Media literacy: identifying and counteracting bias - Developing and laying out your opinion Would anybody be interested in developing this Wikibook with me or studying it? Junesun 16:18, 8 November 2007 (UTC) - I don't know enough about critical thinking to write. You might want to look at Effective Reasoning if you haven't already. Hoogli 01:40, 14 November 2007 (UTC) Hello (and a question) Hello everybody! I'm a new user (although I registered almost four months ago I write now) and I have one question - how to upload a PDF file? I have finished two books, but there is a lot formating in them which I don't want to be lost so I think it would be the best that I upload the books and then somebody other can convert it to HTML? Advice anybody?--Vorkalloner 16:04, 13 November 2007 (UTC) - Hi Vorkalloner, welcome to Wikibooks. Under the assumption that you're willing to list the books under the GFDL and would not mind if an editable copy (in the form of HTML) was available (it wouldn't be a simple "conversion" though, it would have to go into the wiki syntax and all of that), PDF files are loaded using the "upload file" link on the toolbar on the left, which takes you to this page. From that page you can not only upload images, but also PDF files. Good luck! Mattb112885 (talk to me) 19:58, 13 November 2007 (UTC) Gita - I wrote Bhagwat Gita in Wiki Books named as "Gita".Earlier I wanted to write Book Name as Srimad Bhagwat Gita or Bhagwat Gita. Later I selected only Gita. Can you suggest right name for this book? - I see some dot lines like -------- and these lines make square. In this square some of my writings of Srimad Bhagwat Geeta or Bhagwat Gita or Gita are written. Can you please help me? What does it mean? Should I delete those lines or Should I modify or Does it mean that these sentences needs modification? Kindly help me. Thanks and regards.Jaipaldatta 19:20, 13 November 2007 (UTC) - The lines that you are talking about with the dashes around them are known as "preformatted text". If a line starts with a space or a tab, it will become preformatted. Make sure that all the paragraphs in your book do not start with a space or a line. As to the name of your book, whichever you think is appropriate is probably the best. "Gita" is very simple and easy to remember, so you may want to use that. --Whiteknight (Page) (Talk) 19:58, 13 November 2007 (UTC) - ThanksJaipaldatta 07:17, 14 November 2007 (UTC) Wikibooks:Census Apparently, people at meta are trying to perform some kind of wikimedia-wide census. I don't know how exactly this is going to work, and I can't find any information about it. However, my inability to find information about this doesnt mean that it isn't really happening. We have been asked to write questions for the census, and we are supposed to have a bunch of questions written up by this Sunday (11 November). A few questions have already been written, although all of them should be open for editing and improvement. When the time comes, I would also like to ask all wikibookians to participate in the census (however they do it) so that we can be properly represented. --Whiteknight (Page) (Talk) 23:35, 4 November 2007 (UTC) Soft redirection for wikiversity materials I'm starting to work on making "small-scope" Subject pages, and while checking links for Subject:Cichorium intybus I noted that I will be running into a lot of links on the Field Guide, which is a long-abandoned book started in '04 by User:TUF-KAT (who seems to have long disappeared from wikibooks). With this in mind, I'm thinking about replacing pages in that book and probably some other long-abandoned stubs with soft redirects to Wikiversity. For that book in particular, the "wildflowers" section has a ton of redlinks and only 4 content pages, and even the content isn't much to look at. I think it might make sense for now to either replace the entire "wildflowers/plants" directory of that book (again, mostly just redlinks) to the Wikiversity bloom clock. In the future we could perhaps instead just import bloom clock materials (such as v:BCP/Cichorium intybus) to either the field guide or dichotomous key (the DK should probably be merged with this book anyway, since making a single DK for all life forms is pretty much impossible). Currently the bloom clock takes advantage of DPL to make regional categories in any case, so the BC keys actually function as field guides quite well (and there are nearly 450 plants on it at the moment, as opposed to the 4 on the Field Guide). Anyway, sound like a good idea? --SB_Johnny | PA! 14:23, 13 November 2007 (UTC) - I worry that the bloom clock is not necessarily a stand-in replacement for the field guide book. Even though both are about plants, I think they are covered in different ways. However, the field guide book is long-abandoned, and I think it's fair to assume that TUF-KAT is never coming back to wikibooks, at least not to contribute like he once did. If the field guide did contain good book-like materials, I think it would be more prudent to merge those into other books. If there are no other suitable books, a better Idea might be to leave the book as a stub (because somebody may eventually expand on it), post several prominant links to Wikiversity (not redirects, but just large links), and find a way to advertise both the field guide and the bloom clock together both on this site, on wikiversity, and in other places as well. I have no problem promoting the bloom clock or any other wikiversity resource, but I am hesitant to sacrifice an entire book in order to do that. --Whiteknight (Page) (Talk) 20:03, 13 November 2007 (UTC) - Actually, the idea is to eventually import the BCP pages to wikibooks, once there has a been a few years of data collection and the dichotomous keys are developed a bit more. The clock's pages could then be transcluded into as many field guides as appropriate, but with additional text explaining local distribution and status. --SB_Johnny | PA! 13:17, 14 November 2007 (UTC) GFDL requirement for book from other source If I translate only one section from other GFDL book, for example,, I must comply with all requirement in GFDL. - 4. In addition, you must do these things in the Modified Version: - D. Preserve all the copyright notices of the Document. - H. Include an unaltered copy of this License: This would make the wikibooks pages flood by big text of the GFDL? --Ans 06:48, 9 November 2007 (UTC) - So far as I know, a link to the original will satisfy the first requirement. The whole Wikibooks project has a copy of the GFDL here; each individual book doesn't need it's own copy. Happy editing! – Mike.lifeguard | talk 15:54, 9 November 2007 (UTC) - Mike is exactly right. Every individual book doesnt need a copy of the GFDL because the entire wikibooks project has a copy already. In this sense, we can think of the entire wikibooks website as a single "aggregate" work. That is, of course, until somebody separates out a single book by printing or something similar, and separates a book from the wikibooks project. In that case, it would need it's own copy. If you are translating from another site, make sure you leave a note about the source of the material. Also, if you want to make the licensing clear, you can use {{GFDL}}. --Whiteknight (Page) (Talk) 17:50, 9 November 2007 (UTC) - But when people click view source (which is "Transparent copy", according to GFDL), they won't get the text of GFDL. Hmm, ok, it's their responsible, to reinsert the GFDL section, if they want to redistribute the individual document. However, the copyright notice (#4D in GFDL 1.1), must be still preserved in all individual documents in this collection. Besides, how about the "History section" (according to GFDL)? --Ans 05:46, 10 November 2007 (UTC) - The view expressed by Whiteknight is his own interpretation and is not consensual, even the "creators" of the system/concept aren't clear how it should be viewed. I have previously disagreed with WK on the view that Wikibooks is an aggregation of works: But agree that Wikipedia is. I have attempted to provide all the works I have contributed here with it's own copy of the GFDL on the version intended for printing (as it is intended to create a stand alone version), and an copyrights/author attribution section; As for any other version (for use online) the bottom of a page will informs users that all pages are under GFDL and link to the license should satisfy the requirements. - We should keep in mind that Wikibooks isn't licensed under the GFDL but under the GFDL with other limitations (check the copyright section); Translations have a special section on the GFDL. They qualify as a modification and have to comply with that section 4 you partially indicated; must have a distinct name, list authors of the original document and the modification, etc... if you only fallow Mike indication, any hardcopy of the modification would violate the GFDL (even using the other limitations Wikibooks use), the best way is to preserve all the information of the original work in any modified version or at least attempt to; This seems to be a fair requirement. --Panic 16:27, 10 November 2007 (UTC) - The only limitations to the GFDL imposed by Wikibooks is in regard to what is allowed to be hosted on Wikibooks. The limitations have nothing to do with what anyone is allowed to do with the books/documents if hosted or redistributed elsewhere, or printed. I could for example take a book from this website, create a cover page for it, add sections to it which cannot be freely copied, make a note of those sections, in the history section, print it and sell it for profit. Alternatively I could create a book from scratch under the GFDL with sections not covered by the GFDL and host it on some website. Anyone could use the sections covered by the GFDL from my book as a bases for a book on Wikibooks. The limitations just doesn't allow non-GFDL sections to be added to Wikibooks. --darklama 17:17, 10 November 2007 (UTC) - That is incorrect, it suffices to take a look into the extended limitations to the GFDL as written on Wikibooks:Copyrights to read "Use in hardcopy" (not controlled by Wikibooks or Wikimedia) and "Use on the Internet" (that doesn't cover only Wikimedia controlled content). - What is "imposed" by Wikibooks is the use of the GFDL with those extra limitations/considerations, not only on Wikibooks but on every subsequent derivation/modification, copy or distribution in whatever form it is created or displayed inside or outside of Wikibooks and Wikimedia control. - If you make a modification/translation for distribution, you would have to comply with the section Ans indicated, that defines some limitations to the coverpage you could use, title and other data. If you add any text to a GFDL text it must comply to the GFDL, so in the example you give all the content is up for grabs (as in usable for GFDL distribution or uses defined on the license). And in the last phrase you are also incorrect non GFDL content can be used on GFDL works if a compatible license was used or if the copyright holder (not the authors, as seen on the VfD discussion on the UNESCO work) agree to it, but from that moment on it would indeed be all under the GFDL (that was probably what you intended to state). --Panic 18:39, 10 November 2007 (UTC) - Another interesting discussion would be if other GFDL content (not originated on Wikimedia under those limitations) and even in part in opposition to the extra limitations/considerations could be used... - My view is that if no direct stated opposition, or collision with the required limitations is present it can be used; This creates the problem that not every GFDL content is compatible with "our" GFDL + limitations license and viceversa for future iterations since the limitations would apply. --Panic 19:49, 10 November 2007 (UTC) - My "views" on this topic are not just my personal interpretations, they are the way things are here, even if you don't agree with me. In fact, I dont remember anybody asking you what your opinion was on the issue, although you are more then happy to tell us your "version" of it repeatedly at every available opportunity. This website represents a single "work", from a technical level this entire site is served from a single database. This is the only way in which the Wikibooks website remains compliant with the GFDL. Using a flawed interpretation that every individual book and page is a separate work means that this entire site is a copyvio. Since this is not the case, you can stop saying otherwise, especially to users who are new and possibly confused enough already. Considering that your minority view has been shown on numerous occasions to be faulty, it would probably be in everybody's best interests if you excused yourself from this and future discussions on the topic. --Whiteknight (Page) (Talk) 01:53, 12 November 2007 (UTC) - Please be civil. If you wish to contest my opinion or validate yours you may start if so inclined by providing some information to validate and instruct us non believers about your claims "This website represents a single "work", from a technical level this entire site is served from a single database." doesn't make sense even at a technical level. --Panic 03:30, 12 November 2007 (UTC) - I have nothing to validate, it's not my "opinion", it's the fact of our project. There is simply no other way to see it. How many times have you done this? You say things that are bogus, you belittle people who are trying to be rational by calling thruths "opinions", you refuse to understand the explanations that people give you, and the list goes on. I'm not being uncivil, i've grown tired of your particular brand of trolling, and i'm not going to allow you to spread misinformation to people who genuinely need advice about licensing. --Whiteknight (Page) (Talk) 03:44, 12 November 2007 (UTC) - reset That affirmation is not correct, this view that Wikibooks is a single work is not a fact, it has no base in any available record or even Wikimedia statements. As far as I know I'm not the only one that contests this view (and not the only Wikibookian that thinks so) on the other hand you are the only one that has so far defended the other "theory". I'm no zealot and can accept that you may be correct or at least have some points that would support your view, but it irks me that you can claim to have a superior and better understanding only because you claim so. Since this has no bearing on the first posters question (but relates to the global discussion), I don't see any harm in adding a bit more here (but we have already discussed this without any conclusion), I'm as free as yourself to defend a different viewpoint and don't like your attempt to force your interpretation as gospel and how you react to different opinions. We can take a simple example the project name is in plural (Wikibooks) in contrast to Wikipedia or Wikidicionary that in itself provides some clues that the intention was to have the project around several independent works. Then there is the legal framework the GFDL provides I call your attention that you may be confusing or have worded things wrong, an aggregation of independent works is not the same as "This website represents a single "work" ", all works continue to be independent and each with his own license and copyright statement (I grant you that pages outside of the books could be seen as single work, a collection, but I can't claim to be as certain as you on that regard), this aggregation view has implications on how pages have/can been moved from work to work. This is why I disagree with your view that "Every individual book doesn't need a copy of the GFDL because the entire wikibooks project has a copy already." this is just not so. If you can't accept that you may be wrong and feel that this discussion should extend any further I will happily continue to argue my point but taken in consideration our past discussion I doubt it would lead anywhere and only be a re-hash of what has been said, but please be more open to others having different ideas and the right to express them. txs... (if you can't remember what we have said on the subject I think you can find it on Rob's talk page history, on your's and mine) --Panic 15:17, 12 November 2007 (UTC) - Fine, let's play this game, again. First, the fact that "Wikibooks" is a plural name doesnt indicate anything about the intentions of the founders of this project with regard to licensing. Wikibooks was based, technologically and ideologically on Wikipedia, which is considered to be a single work for the sake of licensing (with the addition of non-GFDL images, which technically makes it an aggregate). There is no reason to make the assumption that somehow Wikibooks must be any different from the Wikipedia model, regardless of the fact that our name sounds like a plural. "Wikibooks" is a proper noun, and the trailing 's' does not imply plurality. Second, the fact that this website only contains a single copy of the GFDL means that it must either be a single work, or a single aggregation. The only reason this would be an aggregation is if we have a GFDL document combined with a non-GFDL document, such as the CC-BY-SA images. Images aside, the textual components of this website form a single work under the GFDL. Combinations of multiple GFDL documents form a "collection", which is in itself a new single GFDL work with the caveat that that individual sections can be removed with their individual invariant sections. Since Wikibooks is released with no invariant sections, that distinction is moot. You say that pages outside of books could be considered a single work, but you are making the arbitrary distinction that some pages are "in" a book, and some are "not in" it. This is just an artifact of our naming convention, that pages are named so that they appear to have a hierarchical relationship with other similarly named pages. However, all such naming schemes share a common root, which makes the distinction of page groups as books more tenuous. Multiple pages under a single copy of the GFDL must be either a single document or a collection of documents, and without invariant sections the two are the same thing. Section 1 says "A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.", that is any "work" (not "document") is considered a single "modified version" if it contains the document. In short, the Wikibooks website represents a single modified version containing all pages. QED. --Whiteknight (Page) (Talk) 18:42, 12 November 2007 (UTC) - I don't see this as a game, we aren't competing (at least I didn't sign in for that) at best we are challenging each others views on the subject and I'm taking something from it, knowledge in general and better understanding about your side of the problem, I already have a good understanding on your stance in several points so this exercise is useful if not to you to me and if we reach a conclusion maybe even to the first poster and community. - I start by agreeing that what I said about the name is my interpretation and is as valid as yours. I agree also to what you said about the project conception, but on the scope and objectives the project is very different from the others probably the only one closely related would be WikiSource, it would be funny to have this discussion there :) - For what I understand you have "changed you view" or at least modified it a bit so to admit that for you (lets keep the universe reduced to you and me to be easier to address each side) can now accept that Wikibooks is an aggregate of works (even considering that you now do it because of the different licenses used on the images); We can even say that this was you viewpoint from the start and that "This website represents a single "work" " was a generalization of that concept. Hope I got this supposition right, this will reduce a bit my objection but I will continue on disagreeing with you and will address this as you position so far. - Ok, from that new insight I can agree and confirm that I'm in concordance with that general view in part but still think a single license doesn't cover all (lets say all GFDL) content on Wikibooks. Why? Because to your extra considerations to images with a different licensee, I add that each book also has it's own license and licenser, that it is not as generic as the one that covers all the site (this can be challenged in part and probably we will not reach a conclusion because of the submit clause, in any case the namespace were the submission is being made could serve to enforce my side but lets skip that discussion), beyond that, you forget that several works/pages don't have the submitter as author or copyright holder, and even if not using the GFDL (in the original form) no violation is being made by the contributor that is in fact relicensing a work (lets consider only valid works with proper licenses, remember that GFDL is a license for distribution). As support to this view and if we are using the aggregate definition we can read on the GFDL "When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.", it seems to be clear to me that each work can't be considered a derivate of the hole site (or even vice versa if we go that far), they are self contained, right holders and content, more each work should have it's own license were the copyright holders grants the contribution under the GFDL license (again the submit clause), and there is the problem of attribution. For instance, to use content from Wikipedia we must give attribution to it in each work that uses content from it (now we use mostly transwiki to solve the problem, I also disagree with using this option skipping the attribution), but each book must give attribution specific and relating only to that single work, referencing also specific extra parts that may have rights on the work and specifically indicating their agreement to license it under the GFDL, this points so far may prove to you that all works should be considered an aggregated work and that the site wide license doesn't apply to those documents, I could point other subtilities that would further advance my view (but would probably raise problems in other areas), as I know you will adamantly defend the submit button I remind you just one more point, most of us Wikibookians are anonymous contributors... - As for the project name :) I only gave you that fact because it fits to what I'm stating (as we were talking about facts and both side miss them), and I still like that example... - I don't disagree that most pages on the site may be considered a "collection" when not part of a book (I gave you several reasons why this should be so and agree that what I'm defending doesn't apply to any other page not even talk pages on the books), I know that you have several other concepts that collide with mine (history pages, authors and others not related to this subject), and all the examples I gave you skip most of that minefield... - If your response is to address the submit clause then the little examples I gave should suffice but even you can grant me that the legalities of such clause is shaky and that it's use is more for protection than anything else, but if you wish to extend the discussion into that (I remember we had also a discussion about that and if my memory doesn't fail you agreed or didn't objected to this understanding)... - In any case, to recenter the discussion, we are only in disagreement here about the view of a site wide license that could substitute every other license (GFDL) or not, that each book "may" need it's own license and must have it on the print version. --Panic 04:43, 14 November 2007 (UTC) - IANAL, but I think that this issue is best resolved by looking directly at the text of the license itself: -. - I think that the Wikibooks project would fall under this category. Mattb112885 (talk to me) 05:03, 14 November 2007 (UTC) - None of us are lawyers (AFAIK) and I doubt one would be willing to make an opinion on the GFDL licensing problem as the license was "tweaked" (so to avoid the abused word :) to cover our (project) specific needs and the evolution of the medium we use. - In any case WK covered the distinction about collection and aggregate (we can have a mix of documents under several setups), the only important distinctions is with the specific requirements (not the Invariant Sections as WK has pointed out since our GFDL is extended to avoid it), licenser mention, attributions etc... - If you take it to a very basic level it is about if every page is a module under the site wide license (rights attribution), and that that suffices for all pages. In other words that stuff like this C++ Programming/Authors should not only be avoided but completely unnecessary as serving no purpose legally (WK opposition here at this point doesn't cover the moral side or contributors liberty to add such things). --Panic 05:30, 14 November 2007 (UTC) - The GFDL is not extended to avoid it or otherwise "tweaked". Wikibooks' Copyright page states only that anyone submitted works to Wikibooks must agree to allow Wikibooks to use it without no invariant sections and no front cover text, as a requirement that must be agreed to before clicking the submit button in order to be used here. It is not listed as a requirement that must be accepted when used, modified elsewhere, or redistributed, regardless if done so on the internet or in print. In both cases it tells you to read the GFDL link for specifics, which does include information on having invariant sections and front cover text. - Anyone is free to include an authors or contributors section, although it should be avoided. However it does serve no legal purpose from the stand point of the Wikimedia Foundation and anyone is free to add there name to it. Wikibooks clearly defines for internet use "linking back" to the book or module being used, modified or redistributed as being enough to satisfy the author requirements of the GFDL license. I think the Wikimedia Foundation stance on hard copy is its up to the person who wants to use, modify or redistribute works of any project to determine the appropriate steps necessary to properly attribute authors/copyright holders based on their local laws, and not the responsibility of any contributors to the Wikimedia projects. I think that makes perfect sense, since laws can vary by country and jurisdiction and only someone familiar with local laws has a good chance of determine who meet those requirements appropriately. None of us are lawyers and even if we were, thats no guarantee that such a person knows the current laws that apply for every place in the world. The responsibility is the person wishing to use, modify and redistribute the works, not Wikibooks or any of its contributors as a whole. --darklama 14:18, 14 November 2007 (UTC) - The fact is that the GFDL had to have some exceptions added (therefore tweaked), and is common knowledge that if it could be replaced it probably would. (other examples of the problem can be learned by studding the need for multiple licensing or comparing it to similar licenses). - Once you license the work under the GFDL with the additions any subsequent version would have to comply to it. Do I understand correctly and you are stating that the exceptions are only valid on Wikibooks ?!? - We have addressed this "anyone is free to include an authors or contributors section" and this is not the issue here. An author is not the same as contributors the distinction has to do about rights ownership not all edits grant you ownership of the contributions and there is a problem of quantity/quality of what constitutes a significant change, this is common knowledge for software developers... - The location of the rights (jurisdiction) are clearly stated, the one that applies here is the location of the server, and I disagree with you on some points further for instance if someone abused the site wide license how would you address it (the submit clause doesn't transmit copyrights to Wikimedia, it only licenses the work under the GFDL to Wikimedia if you go to FSF we can clearly read that only the owner of the copyright can defend the abuse) ? --Panic 16:41, 14 November 2007 (UTC) - That's another point where you are stubbornly wrong, panic. Every person who makes any edit holds copyright over that edit. There is no quantitative nor qualitative distinction what-so-ever between a contributor, an editor, an author or a rights-holder on this project. The GFDL makes no such distinction, the Wikibooks:Copyrights page makes no such distinction. It is a figment of your imagination, and unless you can show us the magical hiding-place where this information is living, you need to give it a break. --Whiteknight (Page) (Talk) 18:45, 14 November 2007 (UTC) - I know you also disagree but lets skip that point for now, if we start mixing it all up we will not ever find a point of consensus were we can build up, since you extended a bit I will also defend a bit my view so third parties can understand our view points (or disagree completely with them). In any case this part is not covered by the license we use by the copyright law in general and specifically on the state the server resides (as I told Darklama), the GFDL concern with this part is minimum as it doesn't deal with copyrights but only on the specific right for distribution. - The view that each edit creates it's copyright and can claim part authorship of a work is flawed in the sense that is self evident that not all edits are contributions (error correction, spelling, reorganization or restructuring of the work etc), and the copyright law stipulates clearly what constitutes a copyrightable change to a work (derivation) and defines the creator of the work (I will not discuss copyright law with you as I think it's pretty evident and if you have problems with it it you should consider carefully your actions, counsels on that field, but again in this respect you have already been challenged and one of the persons talking to you claimed to understand and have a particular relation to the law, and I to am pretty much informed on my local copyright law, European Community discussions and plans. Not only by formation but as a programmer and due to my personal interest on P2P). --Panic 19:08, 14 November 2007 (UTC) - Yes you understand that part correctly, the exception is only valid to works submitted to Wikibooks while it remains on Wikibooks. That exception exists only to insure that all works located on Wikibooks are free to be used, modified and redistributed. Cover text and the invariant sections can have all rights reserved, unlike the rest of a GFDL document, which is not wanted on Wikibooks. As soon as you use, modify or redistribute it off of Wikibooks anyone is free to add cover text and invariant sections to the book which have all rights reserved or have different licensing terms. - Any distinctions if one exists is dependent on locally applied laws, which may include giving jurisdiction to some other country. Not all places are so willing to give jurisdiction to some other country. Its incorrect to assume US laws, Florida or International Laws apply everywhere. If someone abuses the site wide license thats between any concerned parties and whatever laws apply in there location and not Wikimedia nor Wikibooks. You may be very well be interested in a recent case in which someone tried to sue the Wikimedia Foundation for copyright infringement and lost. Wikibooks is just a provider with policies to follow, and enforces local policies, any issues concerning copyright infringement is between the accuser and the accused and has nothing to do with Wikibooks or its location. The case did not take place in the US and did not require considering US copyright laws, Florida copyright laws, nor International copyright laws as you would have us believe must be done. --darklama 21:29, 14 November 2007 (UTC) - reset I disagree with that version and even presume that WK will also disagree with it, after licensing the work or initiating it under it that license will be completely irrevocable "Once a license has been granted to Wikibooks for material, an author may not revoke or alter that license." (even if we use the site wide view), only the copyright owners can relicense it under a different setup. (I remember you again that the GFDL doesn't cover ownership only distribution, for instance even if we use the site wide view, Wikimedia can't relicense the works under an incompatible license without contacting and getting consent from the right owners). --Panic 23:20, 14 November 2007 (UTC) Feedback for Manx Hello! Before I continue on with my Manx book, I want to make sure that everything can be geared and appropriate to all levels of learning. Please view: Manx Lesson 1 and any other parts of the book that are done at the moment. I'd like to see what everyone thinks of it, the level or teaching, format, and so on so I can better this book before I start using lessons as a generalised template for my other chapters and Language books. (By the way, Manx is the language spoken on the Isle of Man). ^^ --Girdi 20:16, 12 November 2007 (UTC) - As a fellow Manxie I love this idea. I've helped develop many of the language books and one thing that would greatly help any of our books would be some kind of pronunciation guide especially if you can make audio files to help pronunciation further. I think the Spanish and German Wikibooks have audio files for listening and pronunciation practice. New to wikibooks Hello everyone. I am new to wikibooks. I look forward to browsing the site. My name is Shannon Horn. I am in a introduction to teaching class.—The preceding unsigned comment was added by Shannon h82 (talk • contribs) . New User Hello! I am also new to wikibooks. I wish to explain that I did not introduce a new page under the name of another user. The page(s), which was lifted bodily from my website Quest for Atlantis, has been on wikibooks for several years and was woefully out of date. I assumed, since I am the real author, that I could bring it up to date so that it would match the corresponding page on my website. Is this Ok? It will be awhile before I can learn all the rules for introducing a new page myself.Firecircle 06:05, 17 November 2007 (UTC) Hello from newbie! Hello there, following a welcome from User:Mike.lifeguard, I've been encouraged to pop in here and say hello! I am in the process on writing a book explaining the basics of Building Services, well actually I've literally just started it. I have found very little info on the internet about the subject so intend to do something about that! I'm fine with writing the text but I need a bit of help with putting the book together and naming conventions etc. Can somebody please tell me in layman's terms the following: 1. I want to create a new page (module) so I create a link with the title of it in the page it is going to come from then click on that link to go to editing the new page but what should it be called to comply with the naming conventions? Say I have a chapter called 'ventilation' and I want to create two modules: 'natural ventilation' and 'mechanical ventilation' with links from the chapter intro page. 2. What about the chapter intro pages? What should they be called? The naming conventions page just confuses me further! If anyone has any tips for putting this book together, that would be great. Thanks. GaryReggae 12:11, 14 November 2007 (UTC) - Hello Gary! welcome to Wikibooks! I've been following some of your progress, and your book looks like it's off to a great start. You may be interested in reading some or all of Using Wikibooks, a book that we are in the process of writing to try and explain some of these details. Specifically, the page on Book Structures trys to cover some of the naming convention issues (although admittedly it's still a short rough draft). To try and answer your question directly, You name pages using a forward-slash, such as "Book name/Chapter/Page". In your case, you would have pages named: - If you wanted to have a page that serves as an introduction to the chapter, you could do it at Building Services/Ventilation, or you could do it at Building Services/Ventilation/Introduction. I hope this answers your question, if you have any more just let us know. --Whiteknight (Page) (Talk) 12:43, 14 November 2007 (UTC) - Thanks for your help, brilliant, I thought that was kind of the case, hence the fact some of the names you suggested as links work. How do I actually rename a page once it has been created? Also, what should I call the main page of the book, ie where the intro and TOC are? At the moment it's just 'Building Services' with nothing in front of or after it, is that right? I'll just have the intro to each chapter on the 'home page' for that chapter, ie Building Services/Ventilation. Hopefully I'll write another chapter or two this evening. - Next question, I'd like to make the book look a bit more interesting with some images but I don't really have many suitable photos or opportunities to take any and I know it is not a good idea to use photos from external sites. Do you know of a good source of free images I could use? Otherwise I'll just have to get Google Sketchup out and draw some models and take screenshots of them. - Thanks, - Gary GaryReggae 13:47, 14 November 2007 (UTC) - There is a move tab at the top of the page. Just hit that, enter the new name, and click the button. You can't move a page to a name already in existence (but an admin could if you ever need that done). Building Services is a good spot to have the intro and a TOC. If you want to give the book a cover you can do that at Building Services/Cover for example. The main page (the top of the hierarchy) is also the page you want to categorize with {{Subject}}. So you can keep track of all the pages in the book easily, you can categorize them all with Category:Building Services. So that last category keeps all the pages of the book together, and the {{Subject}} template on the main page lets the book show up in Subject: pages, for example. - Commons has tons of free images that you can use here. There's no need to upload the images locally, just use the same image syntax as you normally would; the software will search on Commons if the image isn't located here. Hope that helps. – Mike.lifeguard | talk 16:12, 14 November 2007 (UTC) - Great, thanks, I'll have a look at the Commons and all the other tips as well. GaryReggae 19:51, 14 November 2007 (UTC) Use of external links Hi there, I am a big user of wikipedia and just found Wikibooks. Found the Study_Guides:Microsoft_Certified_Professional_Developer_MCPD\CExam_70-536 book, which is fine because I am studying for that certification :-) A question thow, there seems to be MANY pages associated with this book, most of them with only external links (no specific article). How should those kinds of links be arranged?—The preceding unsigned comment was added by Jacques Bergeron (talk • contribs) 04:36, November 17, 2007. - I don't know about that book in particular, but if there are pages which consist solely of external links, then that's no good. If the link is legit, it should be with others on a different page which has actual content. That's my take, at least. - You may be interested in Wikibooks for Wikipedians. – Mike.lifeguard | talk 04:45, 17 November 2007 (UTC) - Thanks Mike. In that particular case the external references are very important for studying so I think they are ligit. I will try to see if wee can put a "reference" section and check with those who started the book. If it works there will be many pages to delete. I will do some of the cleaning and ask if I have any questions.Jacques Bergeron 13:13, 17 November 2007 (UTC) - Not long before I had a question :-) I started to change a section to integrate the external links in the main page so that the "dummy" pages are not required anymore. See section Mannage_data_in_a_.NET_Framework_application_by_using_specialized_collections for the new setup. Question is, how do I delete the pages that are no longer referenced. --Jacques 14:09, 17 November 2007 (UTC) - Pages meeting speedy deletion criteria can get marked with {{delete|reason}}. An admin will come along and take care of it. – Mike.lifeguard | talk 17:23, 17 November 2007 (UTC) Community fire safety book Hi...just like everyone else here, I'm new and looking for a little (some would say a lot!) of help. I'm proposing a book on community fire safety that will cover a wide range of topics related to fire safety. This will include fire protection engineering, fire prevention practices, education, human behavior, building design, fire behavior, etc. In other words, a cross between engineering, social sciences and some other topics. So, I'm not quite sure where to put it. Suggestions or ideas? A draft of a section can be found at which I would like to move from Wikipedia over to Wikibooks. Thank you! Ecomeau 09:20, 18 November 2007 (UTC) - Hi Ecomeau, I think this would be a great addition to Wikibooks, I wouldn't mind importing that page (I'll give you a link once I do it if the import succeeds) into Wikibooks, and then you can move it so that the title is whatever you want it to be (I think "fire safety" would be a good title). Mattb112885 (talk to me) 16:48, 18 November 2007 (UTC) - Done; the page now exists at Transwiki:Campus fire safety; enjoy! Mattb112885 (talk to me) 16:51, 18 November 2007 (UTC) New book: French For Football Hi, I just created this book and copied my early work into it. I'm not sure I've got the Subject and Category tags right, so I would appreciate someone having a look at the front page. Thanks. Recent Runes 20:32, 19 November 2007 (UTC) Looks good to me – Mike.lifeguard | talk 00:14, 20 November 2007 (UTC) help i need to learn hi my name is candice i just found this site yesterday im going on an education beng and i need to read anything that is going to teach me something im not verry book smart or wordly i feel like i don't know what happen who did and how they figured it out i need a list of books thats going to teach me everything about the world life past present and future im bad at math and spelling too i spend most of my days at home and never leave thats another reason why i feel like i missed everything do you have any sugjestions - Want to learn about everything? that's a tall order. Are there any places that you would like to start? Some of our best books are listed at WB:FN. Books in this list cover topics from math and science, computer science, arts, humanities, education, etc. I would say that this is the best place to start reading, if you are looking for a little bit of everything. Another place you can look is at WB:AS, which is the "top" of our organizational system. You can navigate through the various categories until you find books that you are interested in. --Whiteknight (Page) (Talk) 19:02, 20 November 2007 (UTC) MISSING TRY TO FIND INFO ON THESE WORDS NO YES NOTHING EVERTHING CAN'T FIND ANYTHING ???????????????? —The preceding unsigned comment was added by 68.37.119.230 (talk • contribs) 01:48, November 15, 2007. - Those are not subjects that a textbook has been written about. Go fish. – Mike.lifeguard | talk 01:56, 15 November 2007 (UTC) - Maybe try wiktionary? Mattb112885 (talk to me) 15:52, 19 November 2007 (UTC) Logo Selection Process Straw Poll I've started a quick straw poll on meta to see if people are generally in agreement with the rules and the process that have been suggested for selecting a new wikibooks logo. The straw poll is located at meta:Wikibooks/Logo#Should_We_Get_Started.3F_Straw_Poll. The approved rules are: And the suggested process outline is: - Open call for submissions, including posting of messages on commons, and possibly personal invitations to other graphic artists. Also, begin advertisement of process on mailing lists, various wikibooks discussion rooms, etc to get wikibookians involved. This period should last for a significant amount of time (1-2 months) - Voting Round 1: using approval voting, all but the top 10 submissions are removed from the pool. - Discussion can occur on all surviving logo nominations, including suggestions for improvements, modifications, etc. Designers and the community should work together to improve the logo, and to prepare a "treatment". - The top candidates must provide a "proposal" or a "treatment" to include: (a) the logo, (b) the logo with text, (c) a complimentary 16×16px favicon, and (d) a black-and-white or greyscale logo. Artists may also optionally provide suggestions about color schemes or user-interface improvements for the Wikibooks project to accompany the new logo. Candidates who do not provide the necessary images will be disqualified. - Voting Round 2: The best overall proposal is selected using approval voting. I would like to hear what other wikibookians have to say about this process, and if there are any other suggestions. --Whiteknight (Page) (Talk) 17:51, 20 November 2007 (UTC) - I'm confused by "the top 10 submissions are removed from the pool. Discussion can occur on all surviving logo nominations". That is the opposite of what is meant, I hope. ...Selden 18:58, 20 November 2007 (UTC) Mentorship? After commenting on an RfA just now, I got to thinking that perhaps the Wikiversity model of mentorship might serve us a bit better. We've been using it for over a year there, with no problems... and I suspect it probably achieves the same result as our process. The way it works is that someone requests adminship (well, "custodianship" there, but same diff), and rather than doing a vote, they instead just need to attract a custodian (i.e. administrator) to "mentor" them. The mentor is then co-responsible for the "mentee's" administrative actions over the next month, and at the end of the month nominates (or declines to nominate) the user for permanent custodial (administrative) status. In the RfA that I commented on today, my response on wikiversity would have been more like "Flickts, I don't think you're going to find someone willing to mentor you right now." --SB_Johnny | PA! 18:21, 20 October 2007 (UTC) - So what happens at the end of the month? The mentor nominates (or not) this person, and then there's a vote on whether we accept the mentor's recommendation? I'm not sure how I feel about someone running around with admin tools before being approved for them. If they mess up while their mentor isn't around, then...? - I'd be more likely to support a trial run after approval instead. It can still be a mentorship, but after they're already approved - as a way to learn how to use the tools. We could include a mandatory "review" after the first month of having the tools, and we'd request comments from their mentor and whatnot... - All in all, I think our process doesn't need changing though. I expect that Wikibooks is going to enjoy more growth then Wikiversity in the near future, and adding another level of bureaucracy wouldn't be good if that's the case, as it would lead in the direction of Wikpedia's (arguably) broken processes. – Mike.lifeguard | talk 18:54, 20 October 2007 (UTC) - Actually, it's designed to be a step away from the wikipedian process, which has become highly politicized (check out w:WP:RFA). Yes, the field is left open for comments after the one-month trial, though it tends to be a low-key affair. If there were any problems during that month, there would likely be a more heated discussion (or more likely the mentee would just be speedy desysopped... stewards are readily available via irc). Also, they're not exactly running around unapproved, since they have to attract a mentor, and that mentor will be watching their logs. --SB_Johnny | PA! 09:39, 21 October 2007 (UTC) - I admit I like the idea of having a mentor period, the only thing that bugs me about the whole idea is that it limits the tools to people who got the support of at least one person who already has the tools, which removes the community from having any say in it. For example if the community strongly supports giving someone the tools, but there is no current person with the tools willing or having the time to mentor the person, then that would prevent someone from being able to get the tools and would go against consensus and what the community wants. - I think one possible solution would be to make the mentor concept an alternative to getting community consensus right away, where if someone with the tools is willing to mentor a person and there is no strong objections, they can get the tools more quickly and then after a month the community can decide whether the person should continue to have them. --darklama 12:41, 21 October 2007 (UTC) - We talked about this in irc today, and I absolutely agree with darkcode's ideas here (in fact, we're looking into doing the same on wikiversity now that it's come up). The plan we discussed is more or less like this: - Someone asks for admin tools - A mentor may volunteer, but: - If a mentor volunteers, but there is a reasonable objection put forward, it goes to the voting method - If no mentor volunteers, the requestor may ask for a community vote - If the user attracts a mentor, and there's no objection, the 1-month mentoring period begins. If there are reasonable concerns about what the provisional administrator is doing with the tools during that month, there will be a speedy desysopping and it will go to a vote. - This would allow us to avoid any potential cabal problems. --SB_Johnny | PA! 15:13, 21 October 2007 (UTC) - I have a few issues over this idea. An "easy-going" admin could choose to mentor all sorts of unqualified people, effectively opening the door for anybody to get the tools. All it would take is one admin with low standards to force a lowering of standards for the entire community. Voting is an averaging process: some people are very strict, and some people are very easy, and the average result is that nominees of a certain level tend to be promoted. - Also, it essentially gives a single admin the ability to decide for the entire community who can become an admin, without requiring any kind of community approval. At least the way we do things now, we all have an opportunity to weigh in on all new admin nominees. Even though through the new system, we all have the ability to weigh-in after the fact. You should realize that reversing an admin promotion is always going to be harder then choosing not to grant the tools in the first place. It is especially troublesome if a steward is required. - Another issue is that only a bureaucrat can choose to promote an admin, and saying that a candidate has been nominated and has found a mentor, that doesnt mean that any bureaucrat is going to honor the request. Without a standardized voting system in place to help guide the bureaucrats, it becomes completely up to them, without any community input. The system may work well on wikiversity, but I'm not convinced (for these reasons and more) that it will work here. --Whiteknight (Page) (Talk) 21:44, 21 October 2007 (UTC) - Well seems to me like in order to qualify for being mentor a person would need to meet the minimal requirements already in place. Also a short waiting period would exist in case there are any strong objections to someone being mentor, so if there are any strong objections, they would have no choice but use are current method. As a result no standards would be lowered. This would include any objections by bureaucrats, so if a bureaucrat doesn't want to do so, they would not be obligated to do so. This is an addition rather then a replacement for are current system. --darklama 17:08, 22 October 2007 (UTC) - It still gives opportunity for an admin promotion to be made without getting community approval first. And even if you say at great lengths that the granting of the tools is just temporary for a certain period, a person who has not gotten community acceptance is still running around with the tools. What I would like to see is some kind of rundown as to the possible benefits. That is, what do we stand to gain from removing the community from the loop (even if only in a select few cases)? I would be in favor of requireing a mentor for all RFAs after a normal election. Under that kind of system, an admin candidate would need positive community support at RFA and must have a mentor in order to be promoted. That all seems like a waste to me though, because we already do a good job of supporting and teaching our new admins, without having to add another layer of policy onto it. --Whiteknight (Page) (Talk) 19:15, 22 October 2007 (UTC) - Mentoring strikes me as a patronising way of saying 'we dont think you're intelligent enough to use the tools correctly so we'll guide you for a month'. By all means provide mentorship to those who request it or demonstrate that they need some help but it should be the exception rather than the rule. Xania talk 23:17, 26 October 2007 (UTC) I've been mulling over this for a bit, and considering something on textbook-l about what unique software/hardware requirements we may want to suggest to help out Wikibooks. In addition, there was a proposal on Wikipedia awhile back for something akin to an "Apprentice Administrator" that had a number of the tools that an admin uses, but not necessarily all of them. Most noted was the ability to perform a quick revert directly from the "Recent Changes" page, and perhaps one or two other things that might be useful for somebody to help the project but wouldn't cause undo problems. Perhaps something like a "timed" page freeze, where somebody with this level of "authority" could freeze edits for a certain amount of time... normally to cool down an edit war or to stop blatant vandalism. What I'm wondering is if this is something that might be reasonable to experiment with here on Wikibooks? It would require modifying some of the MediaWiki code to make this possible (adding a new class of users with specific functions), and the full extent of what would be allowed for this class of users... or if having an extra level in the "heirarchy" of user privileges is even desirable. The idea here is that we could be much more free with whom we could give this level of privileges (they can't do as much damage as somebody with full admin privileges), and it would also be useful in terms of building trust with the community... as they have the ability to make positive contributions to the community as a whole. Or show they abuse even a little authority once it is given. Wikipedia ultimately rejected the idea entirely, but this isn't Wikipedia...is it? --Rob Horning 18:39, 23 November 2007 (UTC) Amazon's Kindle Has anyone looked into publishing a Wikibook on Amazon's site for the Kindle? If my main project here were ready for publication, I think I'd try this out. The terms of the GFDL will allow this, but I wonder how well Amazon understands the GFDL, if what they're offering has terms that are at odds with the GFDL, or even if they care. Anyone? --Jomegat 01:52, 22 November 2007 (UTC) - Looks interesting! I wonder though if people will pay for content they can get for free from the web? It seems you have to charge for anything you upload. Though I guess perhaps the only way to get content onto one of those things is to buy it through amazon. I hope we'll see a few more devices like this in the next few years; if you imagine the appple itouch, but twice as big... --AdRiley 07:44, 22 November 2007 (UTC) - Yeah, you do hafta charge, and the minimum is $0.25 US. They also reserve the right to add DRM. If you can still get the content for free from Wikimedia though, that might not be an issue, especially if the book flat out says you can do just that in the text. I don't know if there are other routes for getting books onto the Kindle either. It suddenly looks less compelling to me. --Jomegat 15:11, 22 November 2007 (UTC) Sound Samples for Guitar/Metal Hey, I just wanted to know how I could add samples of riffs in audio form to Guitar/Metal. I know I have to upload the recording, but how do I place it on the page so the reader can hear it? Also, what format should it be in? Thank you. --MetalGeoff 00:01, 11 November 2007 (UTC) - We use .ogg (exclusively?). If your software can't do that already, you might try mediacoder to transcode it. As for using them, I think it's the same syntax as an image (only you can't alter the size). Try w:Wikipedia:Media for more info. – Mike.lifeguard | talk 03:16, 11 November 2007 (UTC) --59.93.15.26 10:10, 16 November 2007 (UTC)edited Technical "Wish List" Anthere sent a message to textbook-l asking if we have a "wishlist" of technical developments that are specific to wikibooks. She wasn't very specific about what kinds of things could or could not be considered. Here is an abridged copy of the message: Does Wikibooks have a wishlist in terms of technical developments that might be useful for the project ? ...if there are specific developments which might be super useful, please say so, I might get it added somewhere. Some things immediately come to my mind such as: - . - The wikijunior "read only" domain that Xixtas and I have been talking about. Possibly a "read only" storage location for all stable book versions, which could be updated from Wikibooks when necessary. - The GNU Lilypond extension, for music and other types of displays (we've asked many times, and never got them because of technical reasons I'm sure there are more things I am missing. I would like to send back a reply to anthere ASAP so she doesnt forget about us. Any ideas? --Whiteknight (Page) (Talk) 16:04, 15 November 2007 (UTC) - I've been having trouble generating a print version of my book, because I have a template for chapter headers that rely on SUBPAGENAME. In the print version all my chapter headers become "Print version". I'd like maybe some other keyword that sticks with the transcluded page vs the transcluding page. Print support in general could stand a lot of improvements, such as automatically breaking large books up into separate sections. Better yet, a PDF generator. --Jomegat 16:20, 15 November 2007 (UTC) - Those are both very good ideas. An automatic PDF generator would be great, and better support for print versions would be good too. This could be a side-effect of the "Book organizational meta-pages", that you could generate a printable version automatically based on information about the structure of the book. Templates that can recognize the SUBPAGENAME even after the page has been transcluded would be a big help as well. --Whiteknight (Page) (Talk) 16:23, 15 November 2007 (UTC) - I think someone was working on a pdf generator. I'm hazy on the details, but they had gotten it to the stage where they made a few examples of output. It's not pretty, but with tweaking, could be good. You might poke around meta and see if something pops up. - I definitely like the idea of an automatic TOC-generator tool. Several people have asked how to create new pages; this would help with that by providing a TOC of redlinks for them to work on, and would also foster greater organization of new books right from the get-go. - Search by book is a must-have! - A list of all top-level pages in the mainspace would be great, especially if it can be done dynamically (as opposed to periodically sorting through the database or something). - Some way of getting more flexible layout is a must. For Wikijunior, there is obvious benefit, but even for the rest of the books. I can certainly envision First Aid being reformatted to be far more aesthetically pleasing. A "themed" background (similar to themes in Powerpoint slides etc), more beautiful ways of creating things like {{FA Best Practice}} (this can be done already, I'm just not good at it), using columns and non-linear text for certain parts. The easiest way to do that now is to create each page as an image and upload them - but that's not very freely editable. I don't know what sort of flexibility is possible, but it'll be better than what we have now. - I'm still not sure what I think about the read-only concept (or other versions of quality control being considered), but it's definitely worth discussing. - So that was basically an endorsement of almost all the proposals you mentioned. If prioritizing is required: - Search by book (should be easy to do) - List of top-level pages in the mainspace (ie books) (should be easy to do) - per-book styles (most important thing to do requiring some work) - Good PDF (and/or print version) generation (requires lots of work, and is probably difficult to do properly) - TOC generator-thing (should be easy to do, but we can function just fine without it) - Read-only (needs lots of discussion before anything else) - </random thoughts> – Mike.lifeguard | talk 17:21, 15 November 2007 (UTC) - This is a pretty good list so far, i'm going to try and compile some of it down into a more concise form and mail it to anthere. I'm sure that if more ideas were raised in a relatively sort period of time, that we could send them in as well. I'll try to get more details from her about this whole project as well. --Whiteknight (Page) (Talk) 22:44, 15 November 2007 (UTC) - Yeah, i saw that before I typed anything. you covered most of this pretty well, I guess I dont need to post a follow up. Your points #9 and #10 were maybe a little confusing, I wouldn't be surprised if she came back asking for clarification on them. Other then that, lets cross our fingers and hope we get something nice! --Whiteknight (Page) (Talk) 23:09, 15 November 2007 (UTC) reset I thought of another thing I would like for RC patrolling. It would be nice if there were a way to show only the latest edits to a recently changed module (like the watchlist does). Dunno how many times I've clicked on the diff, saw horrible vandalism, and then noticed that it had already been reverted. Another thing that would be nice in RC would be a "Hide user X" link. After looking at a few edits of a user, you get a pretty good idea of whether he's up to mischief or not. Maybe these things already exist and I just don't know about them. --Jomegat 20:00, 16 November 2007 (UTC) - Try enabling "Enhanced recent changes (JavaScript)" from the "Recent Changes" tab of your preferences. That should at lest make it easier for the first one, because all changes to a module available in recent changes will then be grouped together with the latest change at the top of the list. --darklama 20:11, 16 November 2007 (UTC) - Does anyone have info on the auto-PDF generator that was in the works? I remember reading about it (mailing list perhaps?), and seeing a sample of it's work (hideous, but readable). I'd like to follow development of that project. – Mike.lifeguard | talk 20:21, 23 November 2007 (UTC) In case you didn't notice Our software got updated last night(?). We now have patrolling on Special:Newpages, which should reduce duplication of work. When you go to new pages from that special: page, there is a link at the bottom to mark it as patrolled. That way, people can tell what's already been checked on the new pages feed. Highlighted = not yet patrolled; not highlighted = patrolled (these can be hidden). There may be other cool things that pop up, but this is one that'd definitely useful, and should be used by those of you who sort through the new pages. – Mike.lifeguard | talk 20:08, 16 November 2007 (UTC) - Ermm.. apparently this got turned off? Anyone have deets? – Mike.lifeguard | talk 20:14, 16 November 2007 (UTC) - It was enabled for testing, which is currently incomplete; when the software was updated, they forgot to turn it off. It will be re-enabled once Brion is has taken a look and gives a thumbs-up. FYI, the word "soon" was used :P – Mike.lifeguard | talk 20:23, 16 November 2007 (UTC) - I just looked a the page, and some entries appear to be highlighted to me. I take that to mean that it's active? --Whiteknight (Page) (Talk) 23:46, 16 November 2007 (UTC) - Yeah, looks like they turned it back on. I have to run, but can someone try to find documentation for this? ie. can you mark your own pages as patrolled and/or do certain users (whether sysops only, or maybe we can hand it out to trusted users) automatically have theirs marked as patrolled? – Mike.lifeguard | talk 00:02, 17 November 2007 (UTC) - Documentation here. – Mike.lifeguard | talk 02:30, 17 November 2007 (UTC) - A per-book watchlist function (somehow). I've personally been asked a few times, and I know it's a popular question in these reading rooms. This would be highly useful. This could be done as a "watch all pages below this top-level page" thing, or as a category watchlist (which a)is probably server-heavy and b)relies on the pages being properly categorized). – Mike.lifeguard | talk 01:31, 24 November 2007 (UTC) Protected edit request This protected edit request has been pending for some time. Could someone take care of it? (I'm not familiar enough with the syntax used) Thanks. – Mike.lifeguard | talk 20:19, 23 November 2007 (UTC) Done. At least, I think that should work. Somebody double-check me, i don't have a lot of time today to play around with it. --Whiteknight (Page) (Talk) 15:22, 24 November 2007 (UTC) New user Hi, I'm a new user. I plan to edit mostly in the Motorola DVR page with some my DCT expertise. —The preceding unsigned comment was added by ToddC (talk • contribs) . - Hello, welcome to wikibooks! I'm glad you're looking at the Motorola DVR book, it's basically been abandoned and could use a lot of help. --Whiteknight (Page) (Talk) 01:57, 21 November 2007 (UTC) 'Nother New User Hi. I'm Lisha. I wanted to have a PDF copy of the Arabic book, so I jumped in and started making a Print_Version of the book. I've been poking around, and I think that when I'm done with Arabic, I'll prolly fix up some other Print_Versions around the place. Having a PDF on my laptop gives me something to read on the way into work in the mornings. :) Lishevita 20:48, 24 November 2007 (UTC) Hello As i am invited here, here i am. I am from Italy, and i am already banned from wiki.it (infinite) and wiki.en (one year). So go figure if i am very happy about that. Noteworthy that, before been banned i created almost 2000 new articles for wikis. I have a lot of stuff about aviation, but this is not my only interest. Since in wiki.it i was called NNPOV and so on, and wiki,en banned me because i was 'strangely enough' nervous about continous rollbacks 'due to spell errors', so i am here. I yet to accept to have write around 5 MB in the NS0, doing my best and still, being handled so. No problem if someone notice that i not always write very well and very percisely, but there are best ways to do this than the ones used. Perhaps i'll contribute effectively in this project, perhaps not, the idea is interesting, expecially for me, that usually make a lot of stuff (more as book than as article). But due to those bad experiences, and the trap set everiwhere by fellow wikipedians, i am instead more inclined to contribute just seldomly. This is balanced because from one side i am disgusted by some guys always ready to provoke and then punish, for another side i am inclined to contribute effectively to wikiprojects itselves because i silly believe in this concept of shared knowledge. So i cannot grant nothing about the success or not of my partecipation here. If someone want info from me about military aviation and some other stuff-expecially in Italy- he can ask to me with kindly manners, and be answered as well in the same way. Try to believe.--Stefanomencarelli 22:27, 25 November 2007 (UTC) - It's a shame that you have been blocked on other projects, but that doesnt affect your work here on en.wikibooks. So long as you can follow our WB:PAG, there shouldn't be any problem. We don't mind if you have spelling or grammar errors, but just to make sure it's always good to mark a page for {{Cleanup}} so that other editors can come and double-check any work that you aren't sure of. Let us know if you need any help, and welcome to Wikibooks! --Whiteknight (Page) (Talk) 15:25, 26 November 2007 (UTC) Stupid question on deletions Hi, I have been doing some cleanup and restructuring on a study guide (Exam 70-536) since last week. One of the page that is marked as deleted (AccessRule class) is still referenced on a category page (Microsoft Cetified Developer). How can a deleted page be in a category? OK Probably a caching problem because it is not there anymore :-) --Jacques 04:42, 26 November 2007 (UTC) - Yeah, I just checked and the page isn't there anymore. Must have been a caching problem. --Whiteknight (Page) (Talk) 15:21, 26 November 2007 (UTC) Facebook publicity? I use Facebook, and they've recently enabled the creation of what are essentially organization profiles. On a whim, I started a page for us, but I'm required to be authorized by the organization to create the page. I've taken content from WB:ABOUT to start the profile. a) Should I bother? b) How would I go about getting authorization? It seems like a fairly trivial thing, but if it brings even a few editors to the project, I think it'd be worth it. – Mike.lifeguard | talk 08:21, 22 November 2007 (UTC) - I use facebook myself, and never thought about creating an organization for Wikibooks. So, good idea! I don't know whose authorization you would need to create something like this, although I can send off an email to the foundation about it if you want to be sure. --Whiteknight (Page) (Talk) 14:59, 23 November 2007 (UTC) - Permission granted; page published. If you're on Facebook, you can become a "fan" of Wikibooks now. – Mike.lifeguard | talk 23:30, 23 November 2007 (UTC) - Good work. One question though so far. Why is the logo on the page not the Wikibooks logo? --darklama 23:57, 23 November 2007 (UTC) - Because it is copyrighted. This is the Image:Wikimedia Community Logo.svg. I am trying to figure out if/how I can use our logo. Advice? – Mike.lifeguard | talk 00:02, 24 November 2007 (UTC) - A quick question for future reference, how did you get permission? Who did you contact? was it relatively easy? --Whiteknight (Page) (Talk) 14:40, 24 November 2007 (UTC) - I just emailed Anthere. She basically said I didn't need permission, but thought it was cute that I cared enough to ask :) Also, if anyone else wants to admin the page, you're (probably) welcome to. You can't do anything interesting - just change what the page says etc., but still worth it to have more than just me. – Mike.lifeguard | talk 15:59, 24 November 2007 (UTC) - I forgot about that. I sometimes forget the WMF logos aren't released under a free-license. I don't know Facebook's policy, so you may want to look, but they might allow the use of fair use images, and if so the Wikibooks logo might qualify as fair use. Alternatively you could try getting WMF's permission to use it, make alterations to it before using it as fair-use, or try looking for an existing one on Commons that uses a free license. Using one from Commons is probably your best optional, if you are like me and would rather just avoid any possible issues involved with fair use and you can't get WMF's permission to use it. --darklama 02:09, 24 November 2007 (UTC) - You have to give them a license to use it with basically no restriction whatsoever. I wouldn't want to do that to the real logo (this one is PD). – Mike.lifeguard | talk 15:59, 24 November 2007 (UTC) [reset] Sweet, I'm in! Mattb112885 (talk to me) 06:44, 24 November 2007 (UTC) Stewards election Wikibook 12:03, 26 November 2007 (UTC) - Just a side note, stewards may seem "remote" like herby says, but they do play an important role, especially for smaller wikis. There was also at least one occasion where I has having problems accessing wikibooks (my ISP's DNS server is garbage), but was able to contact a steward on IRC to combat vandalism. Stewards can also be called upon to help with a few special tasks that nobody here has the permissions to do (oversight of sensitive edits, desysopping, etc), and they can also help out when people with the permissions aren't here (admin promotions, user renames, checkusering, etc). This is also another good opportunity for Wikibookians to get involved in WMF-business, and attract a little attention for ourselves. --Whiteknight (Page) (Talk) 15:51, 26 November 2007 (UTC) Logo Selection Logo selection processes for Wikibooks and Wikijunior have started on meta. All Wikibookians are encouraged to join the discussion and help to select new logos for these projects. --Whiteknight (Page) (Talk) 16:52, 26 November 2007 (UTC) Hello, World. Well, figure I'll say whats up since I'm new. I'm downright fascinated with the wikibooks concept and thought I'd start contributing like I should. I'm an engineering student so I'll be editing some math, etc. My current project will be cleanup and completion of the Algebra book. Hope I'm able to be a benefit to the community! Thanks for not being evil. ~Nick Icurays1 07:26, 25 November 2007 (UTC) - Engineering? Great! I'm an engineer (or at least a student of it) myself. What discipline? We actually have lots of engineers around here, but most of them don't want to write about engineering here. I can't blame them, if you do it all day at work, the last thing you want is to do engineering all evening on wikibooks. There are lots of engineering books that need help, so if you want to do something besides algebra, you are welcome and encouraged! Let me know what you need! --Whiteknight (Page) (Talk) 15:29, 26 November 2007 (UTC) - I'm studying manufacturing engineering, which is kind of a mix of mechanical, electrical, and hands-on CAD/CAM. I'd like to get into advanced-technology engineering, nano and anti-gravity kind of weird and wacky stuff - I'd like to see some Tesla inventions resurrected too. I want to start with just one wikibook and then go from there. I'll certainly take a look at some of the engineering texts =) Icurays1 03:48, 27 November 2007 (UTC) hey Hey my name is rawan.Iam a new user in your website and i just have one question, my mom cooks very well and she has an indoor menu,but she doesn't have a website to publish her menu in ... she cooks almost every Egyption cuisines,In addtion to many dessert stuff .... i just wonder if you can help her put her menu on any of the cooking websites if possible. your efforts are highly appreciated if you consider the issue ......... hope to hear soon!!!! —The preceding unsigned comment was added by Rawan (talk • contribs) 27 November, 2007. - As it says above, please sign your messages with four tildes (~~~~), Rawan. Welcome, by the way! Now, in response to your comment, I think it may be better if your mother, say, started a weblog or something of that nature. As far as I know, ... well, to be frank, I don't quite know how Wikibooks varies from Wikipedia, or what its purpose is (I'm also new to Wikibooks; though I'm not too new to Wikipedia). ... maybe you could try Wikihow. Qwerty Binary 13:59, 30 November 2007 (UTC) - Wikibooks has the Cookbook, a great place for you or your mother (and all the rest of your friends and relatives) to publish their home recipes. The cookbook has hundreds of recipes from cuisines all over the world, but there is always room for more. --Whiteknight (Page) (Talk) 17:00, 30 November 2007 (UTC) Phase out Bookshelves We've had the Subject: namespace for a little while now, and I feel like it's been a very successful tool for organizing books. I don't think we've quite reached the full potential of it, but the initial uses look very promising indeed. The "root" of the subject space is located at Subject:All Subjects, and for the moment you can see a complete list of all available subject pages that are available. In the future, as that list becomes larger, it may become impossible to list all of them on that page. Every bookshelf basically has at least one corresponding subject page, and some bookshelves have even been broken down into logical sub-divisions. Art and Music, for instance, no longer need to share the same bookshelf page, because they have been broken down into separate subject pages. Also, these subject pages are category and DPL-based, so we don't need to maintain the lists by hand. What I propose is that we can start phasing out the bookshelf system now. I think that by this time next year they will be completely obsolete as a method of organizing our books. Some steps that I think we should take over time are: - Link all bookshelves to the corresponding subject pages - Ensure all books that are currently on a bookshelf are properly categorized using the {{Subject}} template. - Protect the bookshelves from editing, and redirect all new searches and additions to the Subject pages instead - Redirect the bookshelves to the corresponding subject pages. A gradual phase out like this can happen gradually. We've already basically started the process with the new {{New book}} template, which only asks that new books be tagged with {{Subject}} but not added to a bookshelf. If we do this, of course we are going to want to improve the subject pages aesthetically, something that we can start doing now to make them a more attractive alternative. --Whiteknight (Page) (Talk) 19:53, 17 October 2007 (UTC) Support I think phasing out the bookshelves is a great idea. My only issue right now is that I don't think we should be requiring subject pages to look a specific way or have specific things on them. Instead experimentation should be allowed and encouraged, so long as its relevant to organizing our books and providing related information. I say this as I've been doing things differently for one subject page and at least one other person I think has other ideas of how to present information on subject pages. I believe they can co-exist and should not be changed simply because they don't look like the vast majority of the others that have been created so far. --darklama 23:13, 17 October 2007 (UTC) - I agree entirely, the subject pages should be customized as much as needed, and they should likely be made to look very different from one another. The only reason that they all look the same now is because I made most of them, and my artistic skill is just one step above "absolutely horrible". I think it is very useful to list the books that are in that topic, along with books with PDF and printable versions from that category, but it certainly shouldnt be a requirement. --Whiteknight (Page) (Talk) 23:19, 17 October 2007 (UTC) Support The bookshelves never really worked, and their structure was rather limiting. I strongly support Darklama's idea too: let's not impose any structure on the subject namespace until we've had plenty of time to see how it works (I mean years, not weeks or months). --SB_Johnny | PA! 23:22, 17 October 2007 (UTC) Support - Customized Subject: pages are definitely a good idea. I don't know which ones aren't the same as the others (I think Engineering might be slightly different) - most of them were made with the same templates. We should definitely be going through the bookshelves and making sure everything appears properly on the appropriate Subject: page(s). —The preceding unsigned comment was added by Mike.lifeguard (talk • contribs) . Support I really don't like the bookshelves. I can imagine that they worked well when there were fewer books and a higher editor to book ratio, but currently the bookshelves are ill-maintained, though not through lack of trying. I'd just like to point out my appreciation to everyone who has maintained the bookshelves over the years. It is clear to me that a more automatic system, like the subject pages, is necessary. Urbane (Talk) (Contributions) 18:58, 20 November 2007 (UTC) Comment If this makes things easier for editors and readers then I'll probably support it but do people actually use Subject namespaces or bookshelves? Do we have any stats to show how our users actually find books? I have never found a book using either method and I suspect it's the same for most people. People just enter the name of what they're looking for in the 'search' field and see what they find. Can someone explain the purpose and advantages of this new system. Xania talk 23:58, 17 October 2007 (UTC) - That's a very fair question, and one that I suppose i'm at a loss to answer. We do have the page counter running right now, although the results really need to be viewed with a certain level of suspicion. Unfortunately, only the main namespace is being counted right now, so we dont know how many hits either the bookshelves or the subject pages are getting. I would be surprised if either method was being well utilized by readers, but neither the bookshelves nor the subject pages are directly linked from the sidebar (eventually, I think the subject pages should be). If we accept the premise "books should be organized in some manner" a priori, we can draw a number of conclusions: - Bookshelves and subject pages basically contain the same information (books listed by subject) - Bookshelves are manually updated, subject pages are automatically updated using DPL. This means less hassle for organizers. - Bookshelves are relatively fixed in number. Subject pages are more dynamic. books can be easily cross-listed on multiple subject pages in a more natural way then cross-listing books on bookshelves. - With all this in mind, if we accept the premise (which is certainly open to argument) the subject pages are superior because they contain the same amount of information, but require less effort from organizers to maintain. If the premise is false, we don't need either method (although I would like to have something, personally). --Whiteknight (Page) (Talk) 00:23, 18 October 2007 (UTC) - The purpose of this new system is to organize books by subject with links to related subjects. Related subjects may be more general or more specific subjects. Books are generally added automatically rather then manually through the use of categories, making it much easier for people more familiar with other projects. Since it has its own namespace, if we could have included in the default search and maybe the default action of the go button, would make it much easier for people to find books. When your searching for a book are you more likely to search for a specific subject or a specific book? Think about it. Subject pages are also a way to encourage more interwiki cooperation. Like including links to wikipedia articles for people who want a quick read, or links to wikiversity lessons for people who want a more lesson based approach. Its too early to say all possible advantages, but the possibility is there to be way better, and more expendable then the bookshelf system. - I think another question to ask is what are the disadvantages to the bookshelf system. I think the bookshelf system has reached its breaking point and has outlived its usefulness as a means for people who want to find books by browsing through what books we have. Bookshelves have gone though a lot of metamorphoses since I've been here to try to deal with the growth of the project and the number of books we have. Trying to divide bookshelves into smaller bookshelves and reorganize how bookshelves related to one another and then we started having departments to try to deal with all the bookshelves we had. We've tried to incorporate other systems to help finding books easier, like listing books alphabetically or using a restrictive form of the DDC and LOC system, which favors some types of books over other types, requiring even more dividing in some cases. I think Wikibooks has been mostly applying band aids/patches and for the most part up to now, creating systems to organize systems intended to organize systems. The quality and the usability has over time gradually decreased as well as its maintainability. - Subjects on the other hand related to one another more easily, encourage more cross-linking, organize well with one another by related subject subject, more specific subjects and more general subjects. Since subjects can organize other subjects, there is more possibility for flexibility and expanding much more easily, without having to change a lot of things and without having to invent new systems to keep things organized and functional. --darklama 00:51, 18 October 2007 (UTC) Searching Subject: pages When coming to Wikibooks for the first time, the default search setting is to search only the main namespace (and talk?). Should we consider adding the Subject: namespace to the default as well? For now, it won't be very useful, since there aren't that many pages, but once they proliferate, it'll probably be the easiest way to find books on a particular subject. For now, it can't hurt to enable searching Subject: by default. We should consider this now, while we're thinking about doing away with the bookshelves. – Mike.lifeguard | talk 23:28, 17 October 2007 (UTC) - Maybe we could even set up a google search function, like we have with books. I dont know how to add a new default search namespace, i guess we would have to bother the devs. --Whiteknight (Page) (Talk) 23:36, 17 October 2007 (UTC) - I asked how to change the namespaces that are searched by default. It's settable in LocalSettings. mw:Manual:$wgNamespacesToBeSearchedDefault. We'd have to ask the developers. Do we still think this is a good idea? I think we have a pretty good network of Subject: pages now; enabling searching in that namespace by default seems like a good idea. – Mike.lifeguard | talk 19:43, 27 November 2007 (UTC) Featured books template I have been away for a while and returning have found that the featured book section has had its full descriptions removed and replaced by a library catalogue. I have assumed that this is a mistake and restored the full descriptions (people have gone to some lengths to produce these) but am unsure about whether this had had an adverse effect elsewhere. RobinH 10:07, 27 November 2007 (UTC) - This was not a mistake. All of it was still there, only inside collapsed boxes to make the pages that use it more compact, where you click the down arrow in the right corner of each box to expand it to see the section of book descriptions someone is interested in. --darklama 14:23, 27 November 2007 (UTC) - What exactly do you mean by "Library Catalog", and why is it such a bad thing? I guess I'm confused about your complaint here. Are we talking about the page at WB:FB? --Whiteknight (Page) (Talk) 17:43, 27 November 2007 (UTC) - (concerning Wikibooks:Featured books/Templates) I think Robin should try clicking the downward-pointing triangle at the right hand side of those bars. It will expand to show everything you had there. No content is missing. – Mike.lifeguard | talk 17:48, 27 November 2007 (UTC) - Ha! But I am only averagely stupid. Will new visitors to the site understand the down arrows? Perhaps there should be an explanation. Or maybe it would be better to leave the pictures expanded... RobinH 18:01, 27 November 2007 (UTC) - Yes, it may not be as intuitive as we think. I'm trying to figure out if we can have [show] [hide] as an option for that template. The arrows are default, which is defined in Common.js (I think), but perhaps an option is possible... Maybe the folks who actually understand js could take a look? – Mike.lifeguard | talk 18:07, 27 November 2007 (UTC) - The problem, and one that is getting bigger as we feature more books, is that these blubs take up so much page space. One page just isn't going to be big enough to hold all of these blurbs in a single place, at least not in a practical way. It may not be a serious problem now, and it may not be serious for some time, but unfettered growth of the featured book program will eventually cause this page to become unbearably large. Using these drop-boxes is a solution to the problem, although we can argue about the benefits and implemenations of it all day long. Relegating these blurbs to subject-specific sub-pages is another option that may be worth considering. This really is a good time to stop and think about the long-term of this program: what are we going to do when we have 100 featured books? 500? 1000? I know that we could be so lucky to have 1000 books of featured-quality, and it's hard to think of that as a problem. However, when we are in that situation, how are we going to organize them all? - Causing the boxes to be expanded by default basically defeats the purpose of having the boxes at all. The whole point is to hide the blurbs so that they don't overwhelm the page. --Whiteknight (Page) (Talk) 18:11, 27 November 2007 (UTC) "Successful" book donations I was trying to think of some books that have been donated to Wikibooks in the past, but my brain is being slow and stupid tonight. Anthere is in talks with a representative from the World Bank over the possible donation of another e-book to wikibooks (and possibly more then one, if i am reading between the lines correctly). I think what the World Bank people are interested in, is hearing about books that have been donated in the past, and have since received attention from editors and writers. That is, have there been any books donated to Wikibooks that have been updated/improved? I was going to say the Modern Physics book was at least partially donated, but I can't remember if that's true or not. I also thought that a few computer science books, such as GNU Compiler Collection were partially donated, but I don't know if that's true either. The UNDP-APDIP Books were donated, but they haven't been "updated" or "improved" since they've been here. I can't think off the top of my head what other books (if any) have been donated in the past. If we have high-profile donations from groups like the UN and the World Bank, that might be a good starting point for recruiting more donations and also new contributors. At least, I hope that's what it turns into. --Whiteknight (Page) (Talk) 23:54, 25 November 2007 (UTC)
http://en.wikibooks.org/wiki/Wikibooks:Reading_room/Archives/2007/November
crawl-002
refinedweb
22,879
66.67
Issues ZF-961: Proposed Feature: Enable Zend_Date::now() / Zend_TimeSync to interoperate Description I suggest we consider another integration point between Zend_TimeSync() and Zend_Date(). All code using Zend_Date::now() might potentially benefit, if this function returned an "adjusted" date made more accurate by using Zend_TimeSync. However, several pototential problems must be solved before such a feature could be added: 1) Zend_TimeSync should not be used to query SNTP/NTP time servers frequently (e.g. once per web page request is very bad idea). 2) Feature should be optional, and only enabled if explicitly requested by the develoepr 3) Avoid coupling Zend_TimeSync to Zend_Date as much as possible (e.g. it should remain possible to use Zend_Date without loading / requiring Zend_TimeSync). 4) The Zend_Date::now() function would need enhancement: public static function now($locale = null) { return new Zend_Date(time(), Zend_Date::TIMESTAMP, $locale); } For example, if the static public variable Zend_Date::TIMESYNC === true, then the function above would use Zend_TimeSync() to retrieve an offset needed to "guesstimate" the current time, just like I suggested in ZF-932. However, this proposal is slightly more complex, because we need to avoid making Zend_TimeSync actually query NTP/SNTP servers everytime Zend_Date::now() is called. Also, if this feature is added, it needs to remain optional and not force everyone to {require_once 'Zend/TimeSync.php'}, they use Zend_Date. Thus, Zend_Date::now() would need to be "smart" and require the right classes, if needed, and use caching to prevent abuse and over-using of NTP/SNTP time servers (also an issue with the Zend_TimeSync class whether or not any other ZF classes are used). Example Use Case: $date1 = new Zend_Date(); // $date1 has an *unadjusted* time === time() // global side-effect changing behavior of Zend_Date::now() Zend_Date::nowUsesTimeSync(true); $date2 = new Zend_Date(); // $date2 is adjusted by an offset determined by Zend_TimeSync (i.e. a cached value) // equivalent to new Zend_Date(), and also adjusted by the offset $date3 = Zend_Date::now(); Again, this Jira "issue" is a suggested feature improvement, and discussion is encouraged by all who wish to participate. The idea in this posted issue is to encourage discovery of potential problems and especially to propose solutions for any of these potential problems, so that the value of the feature can be enjoyed without any "cons". Posted by Thomas Weidner (thomas) on 2007-02-23T14:40:28.000+0000 This would not work, because how should Zend_Date know which Timeservers the coupled TimeSync should request... A user would always have to create a TimeSync object to request timeservers... And as soon as you have your TimeSync object you should use Zend_TimeSync->getdate and you will have a date object with the actual time from the timeserver... In my opinion there is no good way to back-couple these two classes. Zend_TimeSync is too problematic to have it directly integrated within Zend_Date. Even if this is made clear within the documentation. Someone who needs timeservers should always use Zend_TimeSync to get the right date object. He will then have to read the docu or the APIdoc of Zend_TimeSync which will lead him automatically in knowing the problems and benefit of timeservers. Posted by Gavin (gavin) on 2007-02-23T16:21:32.000+0000 This could work, if "enabled [when] explicitly requested by the developer". I did not specify the mechanism how this could be accomplished, and there is room for creativity. If a developer wants to TimeSync "enable" an entire ZF application, it could be as easy as this: However, if reasonable precautions were employed to prevent abuse of the time server, we could use and eliminate the client-side code above. Yes, there could be problems if implemented wrong, but there are solutions available for correct implementations. Posted by Gavin (gavin) on 2007-02-23T16:58:16.000+0000 In the most extreme case of keeping these two classes separate, the developer could be forced to do something like this (or maybe use a different Zend_TimeSync method than getInfo() to suggest an offset): The benefit comes from making existing ZF code suddenly use time adjusted dates by merely poking a configuration value into Zend_Date's class. Posted by Gavin (gavin) on 2007-02-23T17:06:31.000+0000 Note that any use of a static class variable holding a time offset (used to adjust time() to the "accurate" time) necessitate the use of this variable by Zend_Date_DateObject::_getTime(), in order to avoid breaking isToday() and friends. Posted by Gavin (gavin) on 2007-02-23T17:32:16.000+0000 I am less concerned by how Zend_Date::now() and Zend_Date_DateObject::_getTime() access a "global" shared offset .. but I'm more concerned that it is possible to make them use this shared time offset, without losing the cool feature of making individual Zend_Date object's have a private offset that take precedence over the shared offset. I am somewhat worried about Zend_TimeSync, because of the danger of abusing NTP servers. If we provide a more complete integrated "solution", there is less chance people will use Zend_TimeSync in bad ways that pound on NTP servers, giving ZF a bad reputation. If we provide the code and solution to make Zend_Date rely on an offset generated by Zend_TimeSync, then we have more control over the use of Zend_TimeSync, and can insure that the offset is cached for a reasonable period of time, instead of a developer literally putting the following code into their bootstrap (very bad, because it pounds on NTP servers, when the ZF app is on a busy website): Posted by Andries Seutens (andries) on 2007-02-24T04:54:12.000+0000 Gavin, I am worried about this too. Perhaps a forced internal caching mechanism (eg Zend_Cache) wouldn't be such a bad idea at all? We could implement this with the possibility of abstraction, which would make it possible for the developer to use his/her own caching mechanism, or totally avoid the caching (if he/she knows what they are doing). I am just brainstorming out loud, and i have no actual use cases yet. I encourage everybody to think with us, and find a proper solution. Posted by Thomas Weidner (thomas) on 2007-02-24T05:17:24.000+0000 Please keep the issues seperated. This issue is not about stealthing or improving Zend_TimeSync... It's a Zend_Date issue. I think it would be better to have an own new issue about improvements for Zend_Timesync. Related to this issue and to write down what we discussed yesterday: 1.) A user must not have the possibility to give an Syncronisation Offset to Zend_Date per hand. This would corrupt the actual implementation of Zend_Date. 2.) It is no problem to have also Zend_Date::now() working with the TimeSync offset but there are some prerequisits which have to be included before this issue can be implemented 2.1) There must be a way to store the Zend_Date object especially the private variables into a framework cache 2.2) Zend_Date must only interoperate with an Zend_Timesync object. What makes problems here is the offset between time() and the returned real time. Working with own generated times already works. Also working with TimeSync object works (see ZF-932). What we speaking of here is having the TimeSync offset stored internally so it can be used when a user creates a Date object afterwards as TimeSync should run only once per usersession or even once per day. 2.3) Zend_Timesync has to be stealthed and improved to prevent problems with the Stratunm servers if they were flooded with Zend Framework requests. 2.4) Zend_Timesync has to implement a caching mechanism to prevent these flooding 3) The actual API of Zend_Date should not change. The offset has to be known automatically, to prevent missuse. Storing it anywhere within the framework is no problem as long as we can make sure that private/protected stored variables can not be changed by other classes. Posted by Thomas Weidner (thomas) on 2007-02-24T05:27:07.000+0000 A way which does not corrupt the API would be you can serialize / deserialize the TimeSync object and use it with Zend_Date... This is how this issue works NOW... this is already implemented by ZF-932. works already... only one more line than what you proposed. And the user has explicit to say that he wants to use the TimeSync offset which is the better way in my eyes than having this done in background. Posted by Gavin (gavin) on 2007-02-28T14:54:53.000+0000 Are there any actual problems supporting the following use case involving {{nowUsesTimeSync()}}? Posted by Thomas Weidner (thomas) on 2007-02-28T15:32:16.000+0000 No cache mechanism implemented within Zend_Date The user does not know that he uses timesync values from now on... Therefor the approach to explicit give the server to Zend_Date is more accurate. Also when you always have to give Zend_Date the server explicit with an parameter you always have to know and recognise that you are not using time() but timeserver. It is no problem also to have implemented. Also for a user it would be no problem when he desides to change from time() to timeserver to change his complete code from now(); to now($server);... just a search and replace within the code, 3 mouseclicks with a modern GUI. $server should be serializeable and deserializeable but this are problems of Zend_TimeSync and not of this issue. Posted by Gavin (gavin) on 2007-02-28T16:19:54.000+0000 Why should we require this: when we can make this work: For a "cache mechanism", all we need to do is: {quote}.. search and replace ..{quote} I think search and replace is not an acceptable solution. What if the developer can not change the code? What if the code is part of another module or library? What if sometimes the code should use the offset, and other times it should not? The solution I've proposed does not have these problems, and could be made to work with Zend_Date. Posted by Thomas Weidner (thomas) on 2007-02-28T16:44:58.000+0000 Why would you have to use 3 date objects with the actual time ??? There will never be as much new date objects that you would have problems with adding $server by creation inmy opinion... {quote} For a "cache mechanism", all we need to do is: {quote} But this does not cache the offset... With this approach you have always to use nowUsesTimeSync before creating a Zend_Date object... And when you create a timeserver you can also work directly with getDate which returns you an offseted Date object. And also to mention... If you want to use several offseted date objects you just have to clone the $result->getDate(); Date object. You have to give the server only once. Zend_Date is already a very huge class... with very much functionallity, even if it's very simple within its API... we should not add much more functionallity for now... it would become too complex for 1.0. Posted by Gavin (gavin) on 2007-02-28T17:02:36.000+0000 {quote}Why would you have to use 3 date objects with the actual time ???{quote} I was trying to show a simple example. In actual code for a real-world web application, there might be many more than 3 date objects in use, scattered throughout the code. One developer might write one part of a web app, and another developer another part, etc. The offset is cached internally by Zend_TimeSync, so that is not a problem. A ZF app only needs to use {{nowUsesTimeSync()}} once, in their bootstrap to enable their entire application to use accurate dates, adjusted using the offset supplied by Zend_TimeSync. This approach is simple, efficient, and does not require "search & replac" on existing code. I don't buy the argument that the proposed {{nowUsesTimeSync()}} is too complex to add to Zend_Date. It is only 3 lines of code. A couple additional lines of code would be needed to enable the existing now() method to use this offset. Posted by Thomas Weidner (thomas) on 2007-03-01T01:18:27.000+0000 Your approach only works if the date object is also used within the bootstrap file. If you have a subclass loading Zend_Date itself and creating a new object it would also not have the offset because it's not cached. This only works if all use the bootstrap file. When we have a object created with its also no problem to have And this would be no problem because then you can decide if you want to have a syncronised object or not. If you say syncronised (which is standard behaviour) and you have not initialised a timeserver before you will get time() because offset is 0. Giving a "false" you would have time() returned. This is a much nicer way then having a function "nowusestimesync()" even if it would have more than 3 lines of code for the implementation. Posted by Gavin (gavin) on 2007-03-01T13:43:18.000+0000 {quote}Your approach only works if the date object is also used within the bootstrap file.{quote} No. All calls to Zend_Date::now() would return an "adjusted" date, after a single call to {{nowUsesTimeSync()}}, which should be made in the application bootstrap, to enable all further usage of Zend_Date to use "synchronized" times for the duration of the current script execution. The offset is cached for the duration of the request by {{nowUsesTimeSync()}}. Why would a subclass of Zend_Date() have problems? I see no problems. Again, we need a way to "time-sync-enable" Zend_Date, without requiring a developer to "search & replace" code (including code they might not have written). Instead of {{ public static function now($syncronise = true) }}, I would suggest: The key here is that a developer can toggle the behavior of Zend_Date component to generate synchronized dates by setting a class property, instead of having to specify this behavior for every single instance object. Posted by Thomas Weidner (thomas) on 2007-03-01T14:47:03.000+0000 I think we are speaking the same but I feel missunderstood by the details you are sticked in... *) I said this only works when Zend_Date is used within the bootstrap. You said no... this has to be done in application bootstrap... my english is not so good, but we are speaking of the same thing in my opinion. *) Please forget "nowusestimesync"... :-( *) My idea with the new approach for now() does not need to search and replace for the developer. The idea is that now() returns the date with offset when the offset is set within Zend_Date or a timeserver is given as parameter. *) We say default is with offset or without offset... these are details we can change simply afterwards. I would say default is use the offset when avaiable. *) now() should be changed to accept a timeserver as input for same behaviour as the constructor. *) Now the user has to do getDate from the timeserver... It's no problem to have this implemented within the constructor and now()... So there is no need for the nowusestimeserver function. This function is what I dont like in the proposed functionality. now() can simply be changed to do additionally the same as your proposed nowusestimesync function. now() -> returns new date object with offset if set now(false) -> returns new date object with time() without offset now(true, TimeServer) -> returns new date object with setting new offset from this timeserver for future use now(true, RESET_OFFSET) -> resets offset to 0 in future use returning new date object Posted by Gavin (gavin) on 2007-03-01T15:27:20.000+0000 My example does not use a Zend_Date object in the bootstrap. I proposed using {{nowUsesTimeSync()}} to set the offset used by the Zend_Date class for future calls to any of the Zend_Date methods needing the current time. I purposely chose a descriptive name for this function for this JIRA issue, but I expect the final name of the function to be different. I suggest we follow the slowly emerging pattern of using "setOptions()" class methods with Zend_Date, instead of overloading now() with functionality related to setting options in the class. See {{setOptions()}} in Zend_Session or Zend_Console_Getopt. Combining a factory method ({{now()}}) with a method altering class behavior ({{nowUsesTimeSync()}}) is not a common practice. Can we keep these two methods separate, with descriptive function names? If they are combined into one function as you proposed, then the bootstrap would require the creation an instance object of Zend_Date in order to set an option in Zend_Date. Also, my use of {{now()}} was just an example. Setting the Zend_Date option to use time synch should affect all methods (including {{_gettime()}}) that require the current time(). The main idea should be supporting toggling a config "switch" in the Zend_Date class to make all Zend_Date methods use the offset to return time synchronized dates, when the current time is needed or used. With this feature, developers can then set a simple configuration option in Zend_Date (one line of code in their application bootstrap), and then know that all relevant dates will be adjusted with a time offset determined by Zend_TimeSync. Posted by Thomas Weidner (thomas) on 2007-03-01T17:28:32.000+0000 Why is now($timeserver); a problem... From Now on use the timeserver offset... I would expect this is standard behaviour. And you do not have to create an object. Zend_Date::now($timeserver); also sets the offset without that you will have to create a date object... I see no problem on this approach. All methods then use the stored offset afterwards... you have not to set it once more... just one call of Zend_Date::now() is all you have to do in your bootstrap file. This IS one line of code. And it effects ALL 4 methods that use _gettime(). Anyway... we are discussing here massive for nothing because this issue will not be implemented before Zend_Timesync is not save to do so... we have enough other opened issues which we shall target and solve... As soon as Zend_TimeSync is as save as it should be, we can drive this issue further... it costs me 1h per day and I have only 2 hours per day... this makes me unhappy :-/ Posted by Gavin (gavin) on 2007-03-01T20:37:51.000+0000 It is a problem because Zend_Date::now() is supposed to create an instance of Zend_Date having the current time. If the function returns true/false on some input and returns an instance object for no input .. that is mixing things in a confusing way. Users should know that now() simply returns an instance object with the current time, and that class options can be set using {{setOptions()}}. Adding unrelated functionality to this function ({{now()}}) is a problem. Adding functionality to {{now()}} that modifies the behavior of future uses of _getTime(), now() and other methods directly or indirectly dependent on these combines unrelated functionality into the same method. Other ZF components use {{setOptions()}} to set options on the component. Why not use {{setOptions()}}? Also, the {{usePhpDateFormat()}} can become an option supported by {{setOptions()}}. Keeping a single, consistent API approach for all options reduces learning curves, simplifies integration with applications, and other benefits. In addition to {{Zend_Session::setOptions}}, for an idea of what might be possible in the long-term, see: Yes, there is no "Fix Version" yet for this issue. "Fix Versions" provide important guidelines for priority. Posted by Thomas Weidner (thomas) on 2007-03-02T01:24:36.000+0000 There is no "fix version" avaiable... Zend_Date was never proposed to work internally with Zend_TimeSync because of the problems which Zend_Timesync produces by heavily useage of the Stratum Servers. Zend_Date was only changed to allow Zend_TimeSync to return a proper date object. IF the problems within Zend_TimeSync and user missuse can be solved it would be no problem to implement this feature. But I will not implement it with the actual problems of Zend_TimeSync and users not knowing what they exactly do. This would lead to a negative image of Zend Framework because of flooding Stratum Servers. A strict NO from me if this can not be solved. I see no problem in having static setOption() integrated. I misliked to implement the usePhpDateFormat also... but it was told and it seemed to be necessary. But I am strictly against nowUsesTimeSync()... Next would be a function "toStringUsesPhpDateFormatButOnlyReturningEnglishLocalizedValues" ??? Nonono.... this can not be our way... WHEN we decide for now not to support a timeserver parameter then also the constructor should not accept it. BUT this would also mean that the getDate() function of Zend_Timesync is useless... Also to mention... It seems nice to have Zend_TimeSync strong coupled with Zend_Date... BUT we loose all possibilities of Zend_TimeSync this way. No way to know what server was used, no setting of the namespace and no calling of a defined server are only a few things which came in my mind. Posted by Gavin (gavin) on 2007-03-05T20:56:51.000+0000 {quote}"IF the problems within Zend_TimeSync and user missuse can be solved it would be no problem to implement this feature." {quote} So far, I have not seen or heard anyone disagree about the importance of solving ZF-987, before any sort of integration between Zend_Date and Zend_TimeSync. Earlier, I added ZF-987 as a dependency of this issue (i.e. this issue can not be adequately solved until after ZF-987). If ZF-987 is solved, then it should be possible to: Just to throw out another idea for consideration, if a reasonable use case exists where computations are complex, then Zend_Date could simply accept a callback, instead of an instance of Zend_TimeSync. A developer would then be responsible for implementing the callback, possibly using Zend_TimeSync. For example: In both alternatives above, the developer is in control, and has the ability to determine which time servers to use. I've also spoken with Andries about the possibility of developer-supplied algorithms for selecting amongst a set of time servers to use, based on information dynamically gathered by Zend_TimeSync* classes. For example, developers could select the time servers with the lowest latency. I do not see any problems including this functionality with the two alternatives shown above in code. Posted by Thomas Weidner (thomas) on 2007-12-01T14:04:34.000+0000 Integrated with SVN-7015. Now there is a own option which can be set. This sets the given offset for all new instances of Zend_Date independently of the way it is created.
http://framework.zend.com/issues/browse/ZF-961?focusedCommentId=13155&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-35
refinedweb
3,760
63.7
On Wed, Apr 30, 2008 at 05:22:22PM -0700, Dave Leskovec wrote: > Hi Dan, > > I updated today to the latest CVS and can no longer connect to the lxc driver. > I've tracked it down to this check in doRemoteOpen() in remote_internal.c: > > if (( > #ifdef HAVE_XMLURI_QUERY_RAW > uri->query_raw = > #else > uri->query = > #endif > qparam_get_query (vars)) == NULL) goto failed; > > Looking at the recent VirBuffer changes, it looks like they changed the behavior > of qparam_get_query. With the old VirBuffer, qparam_get_query returned a > non-NULL result because virBufferNew allocated space. The new VirBuffer doesn't > allocate space until something is added and hence this function returns NULL if > nothing is ever put in the buffer. I'm not familiar enough with the intended > behavior to know what the fix should be here. So two things - with the old code it was impossible for qparam_get_query to return NULL, so the NULL check was redundant. Aside from that, it looks like it is valid for uri->query to be set to NULL anway to indicate that no variables are set. So I'd suggest you try just removing the NULL check & goto failed. If that doesn't work, then modify get_query to return "", if the buffer is NULL. :|
https://www.redhat.com/archives/libvir-list/2008-May/msg00002.html
CC-MAIN-2015-14
refinedweb
203
69.01