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
System.Dzen.Colour Description Support for colours. This module is entirely based on the colour package, so we strongly recommend that you at least import qualified Data.Colour.Names as C which will import various aliases for creating Colours. Note changing the colours using the functions below do not hinder the use of automatic padding. Synopsis Changing colours fg :: Transform a => DColour -> a -> aSource Set the foreground colour. Note that the foreground colour is changed only inside the transformed DString or Printer, unlike using "^fg" which may affect subsequent strings. So you may write fg and it works like you expect it to. black (fg lime (str "lime") +++ str "black") Reseting to the defaults defFg :: Transform a => a -> aSource Set the foreground colour to be the default one, which is specified as a parameter to dzen (outside the control of the printers). Change or reset changeFg :: Transform a => Maybe DColour -> a -> aSource
http://hackage.haskell.org/package/dzen-utils-0.1.1/docs/System-Dzen-Colour.html
CC-MAIN-2016-07
refinedweb
152
63.29
#include <Line.h>Line line();void setup() { // put your setup code here, to run once: line.set(1, 2, 3, 4);}void loop() { // put your main code here, to run repeatedly: }This is my error message:ColourSphereCode.cpp: In function 'void setup()':ColourSphereCode:6: error: request for member 'set' in 'line', which is of non-class type 'Line ()()'ColourSphereCode.cpp: In function 'void loop()':ColourSphereCode:11: error: request for member 'm' in 'line', which is of non-class type 'Line ()()'And this is my Line.h:/**/#ifndef Line_h#define Line_h#include "Arduino.h"class Line{ public: Line(); void set(double x1,double y1,double x2,double y2); double m(); double c(); private: double _x1; double _y1; double _x2; double _y2;};#endifand this is my Line.cpp:#include "Arduino.h"#include "Line.h"Line::Line(){}// define the two end points of the linevoid Line::set(double x1, double y1, double x2, double y2){ _x1 = x1; _y1 = y1; _x2 = x2; _y2 = y2;}// return the slope of the linedouble m(){ return 1.1;}// return the offset of the linedouble c(){ return 2.3;} Line line(); Line line;
http://forum.arduino.cc/index.php?topic=91220.msg684933
CC-MAIN-2018-17
refinedweb
184
63.39
Systematic Content Validation with Varnish Systematic Content Validation with Varnish Sometimes, doing the unthinkable is necessary. Varnish indeed can solve some problems in twisted (yet still effective) ways.. "Can Varnish go to the backend and check the content freshness for every single request?" Sometimes, when someone wants to do something unusual with Varnish, I tend to reply like a true developer with, "Let me explain to you why you don't need it." The problem with this is that we don't operate in an ideal world, and most of the time, architecture isn't dictated by what should be done, but by what must work NOW! (Here's a depressing read, if you need one.) I'm telling you this because in this post, we are going to solve a problem in a twisted way — but, given your specific requirements, it may be the best way. Along the way, I obviously won't resist the urge to explain why it's twisted and what the other solutions are, but feel free to skip those parts. The Issue (and the Issue With the Issue) The Etag header is an opaque string returned by the server that should uniquely identify a version of an HTTP object. It's used for content validation, allowing the client to say to the server, "I have this version of the object; please either tell me it's still valid or send me the new object." What we would like is for Varnish to leverage this Etag header and systematically ask the backend if the object we are about to deliver is fresh — something along those lines: I have a conceptual problem with this. It goes against the cache's goal of shielding your server. With the proposed setup, we have to bother the backend for every request, even if using 304 responses or something similar will largely reduce the load since they have no body. There's also a functional problem; it's synchronous, so if your backend fails or slows down, your users will suffer delays, which is, again, against the idea of a caching layer. The Purge — Actually a Good Solution (Unlike the Movie) We need to backtrack a bit here and think about what our issue really is. It's not that we want to go to the backend all the time, but rather that we don't want to deliver outdated content — a commendable goal. The backend knows about content freshness, so it's definitely the right source of information, but what if, instead of asking it, we could make it tell us directly when something changes? Using purges, bans, or xkey, it's possible to remove content from the cache based on URL, regex, or semantic tags. If your backend is able to trigger an HTTP request when its content changes, you're good to go! A lot of CMS do it, such as eZ Publish, WordPress, or Magento, among others. With this, you can set your TTLs to weeks or months to ensure super high hit ratios, almost never fetching from the backend, and still deliver up-to-date content. This seems to be the perfect solution. So, why isn't everybody using it? The first thing is that the backend needs to be aware of all the Varnish caches to purge, obviously. This generally means that adding a new Varnish server triggers a reconfiguration of the backend. Using the Varnish Administration Console (and the bundled Super Fast Purger), this becomes a non-issue because new Varnish servers will register to it when created, allowing the VAC to know about all the caches: Then, instead of having the backend purging the Varnish boxes directly, it sends only one purge request to the VAC that will broadcast it: If your backend supports it, this is definitely the best option. Saving Grace However, your backend may not be able to trigger those HTTP requests, or you may not have access to said backend. In this case, the previous solution is out of your reach, sadly. Fret not, though. I do have another choice to offer you, and it doesn't involve cache invalidation. It's actually super simple: sub vcl_backend_response { set beresp.ttl = 0s; /* set ttl to 0 second */ set beresp.grace = 1d; /* set grace to 1 day */ set beresp.keep = 1d; /* keep the content for 1 extra day allowing content revalidation */ } Grace is Varnish's implementation of HTTP's stale-while-revalidate mechanism. Very simply, this is the period of time Varnish can keep an expired object and still serve it if it has nothing better to offer. Since Varnish 4.0 grace is totally asynchronous, the backend fetch is happening in the background, taking advantage of the If-None-Match header to minimize bandwidth. In the (extreme) VCL example above, the object gets a TTL of zero seconds, meaning it's already expired. Varnish will get a new version as soon as it's requested — but in the background. At this point, you may wonder how that could be awesome — by removing the synchronousness we just rob ourselves of on-time updates, right? That's correct, but we gain something that may be more important: request coalescing. For one request or URL, Varnish will only trigger one background fetch at a time, allowing your backend to survive sudden surges of traffic, notably if requests take a long time. However, you can object that if your object changes and you can't afford to deliver a single out-of-date request, that's not a viable solution. Again, you'd be right. I would, however, ask, "Can you really ever ensure this?" The object may very well change on the backend right after the response is sent and before it is received. This is part of the weakness of HTTP, and we have to be aware of it. With that said... A Developer's Gotta Do What a Developer's Gotta Do At the risk of being horrible, I need to hammer this point home: Make sure this is your last resort because you won't be taking the easy path. We now arrive where Varnish shines: uncharted territory. Varnish is great because it's fast and efficient, but above all, it refuses to define policies. This is the whole idea behind the VCL: the user can have almost full control over what's going on instead of being limited to the path chosen by the tool. That allows us to abuse the system and twist its arm to do our bidding. We can do it with a pure VCL solution! However, before we do that, let's have a brief reminder of what the VCL is and does (skip that one if you already know). The Varnish Configuration Language basically maps to state-machine processing requests from the moment they are received to the moment they are delivered. At each step, the VCL is called, asked what should be done (tweak headers, remove query strings, etc.) and what the next step is. A simple representation of the state machine could be as shown in this flowchart: The problem is, that doesn't really map with the flowchart we came up with the first time: No worries. We'll make it work. To do so, we'll use restarts extensively, allowing us to go back to vcl_recv and start processing the request again without resetting it. We basically have two paths to cover: MISS — object is not in cache: - Proceed as usual. We'll fetch the object, put it in the cache, and deliver. It'll obviously be fresh. Yes, that was the easy one. HIT — object is in cache: - Save the Etag. - Restart because we need to go to the backend. - Pass because we don't necessarily want to put the object in the cache. - Set the method to HEAD because we don't care about the body — only the Etag header. - If the backend replies with an Etag differing from the one we have, kill the object. - Restart. - Once there, just proceed as normal. The HIT path will look like this when mapped on the state-machine: Note: We could use If-None-Math and test the status code (200 or 304) instead of comparing Etags, but we'd still want to use HEAD to make sure only headers are sent. This is where things get a bit ugly. Since we'll be going through some steps multiple times, we have to keep track of what state we'll be in and route accordingly. Now, here's what you have been waiting for this whole post — the VCL: sub vcl_recv { if (req.restarts == 0) { set req.http.x-state = "cache_check"; return (hash); } else if (req.http.x-state == "backend_check") { return (pass); } else { return (hash); } } sub vcl_hit { if (req.http.x-state == "cache_check") { set req.http.x-state = "backend_check"; set req.http.etag = obj.http.etag; return (restart); } else { return (deliver); } } sub vcl_backend_fetch { if (bereq.http.x-state == "backend_check") { set bereq.method = "HEAD"; set bereq.http.method = "HEAD"; } } sub vcl_backend_response { if (bereq.http.x-state == "backend_check") { if (bereq.http.etag != beresp.http.etag) { ban("obj.http.etag == " + bereq.http.etag); } } } sub vcl_deliver { if (req.http.x-state == "backend_check") { set req.http.x-state = "valid"; return (restart); } } This is obviously a minimal version of it and you will have to work a bit to adapt it to your own setup, as always with code using restarts. I also took a few shortcuts for the sake of clarity, such as banning only based on the Etag, or systematically returning, hence bypassing the built-in VCL code. Faced with such a piece of code, your first instinct should be skepticism. Does that even work? It does work, and I have the test case to prove it! Actually, I built the VCL directly in the VTC, making development super easy. A Matter of Choice Part of the appeal I find in Varnish is explained in this blog. Every time a strange use case appears, my reptilian brain screams, "Nah, you shouldn't do that! That is not the way!" Then, the dev neurons fire up, asking, "Yeah, but if I had to, could I do it?" Pretty much invariably, the answer is, "Sure, just put some elbow grease into it, and that'll work." Varnish is not a complex tool but rather is composed of a lot of simple cogs. Once you know how they are articulated together, well, the weird requests become fun challenges. Through this long post, we've seen how to answer the original question, but, I hope, we also expanded our horizons a bit by touching on quite an array of subjects such as: - VCL. - Varnish Administration Console. - Purging. - Objects in grace. Download the ‘Practical Blueprint to Continuous Delivery’ to learn how Automic Release Automation can help you begin or continue your company’s digital transformation. Published at DZone with permission of Guillaume Quintard , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/systematic-content-validation-with-varnish
CC-MAIN-2018-34
refinedweb
1,852
71.95
Up to [cvs.NetBSD.org] / src / lib / libc / gen Request diff between arbitrary revisions Default branch: MAIN Revision 1.8.56.1 / (download) - annotate - [select for diffs], Tue Apr 17 00:05:19 2012 UTC (3 years ago) by yamt Branch: yamt-pagecache CVS Tags: yamt-pagecache-tag8 Changes since 1.8: +4 -5 lines Diff to previous 1.8 (colored) next main 1.9 (colored) sync with head Revision 1.9 / (download) - annotate - [select for diffs], Tue Mar 20 16:36:05 2012 UTC (3 years ago) by matt.8: +4 -5 lines Diff to previous 1.8 (colored) Use C89 definitions. Remove use of __P Revision 1.8 / (download) - annotate - [select for diffs], Thu Aug 7 16:43:00 2003 UTC .7: +3 -7 lines Diff to previous 1.7 (colored) Move UCB-licensed code from 4-clause to 3-clause licence. Patches provided by Joel Baker in PR 22280, verified by myself. Revision 1.7 / (download) - annotate - [select for diffs], Sat Jan 22 22:19:13 2000 UTC (15 years, 2.6: +3 -3 lines Diff to previous 1.6 (colored) Delint. Remove trailing ; from uses of __weak_alias(). The macro inserts this if needed. Revision 1.6 / (download) - annotate - [select for diffs], Mon Jul 21 14:07:48 1997 UTC (17 years, 9: +8 :27 1997 UTC (17 years, 9 months ago) by christos Branch: MAIN Changes since 1.4: +3 -2 lines Diff to previous 1.4 (colored) Fix RCSID's Revision 1.4.4.1 / (download) - annotate - [select for diffs], Thu Sep 19 20:04:29 1996 UTC (18 years, 7 months ago) by jtc Branch: ivory_soap2 Changes since 1.4: +7 -2 lines Diff to previous 1.4 (colored) next main 1.5 (colored) snapshot namespace cleanup: gen Revision 1.3.4.1 / (download) - annotate - [select for diffs], Tue May 2 19:35:28 1995 UTC (19 years, 11 months ago) by jtc Branch: ivory_soap Changes since 1.3: +2 -1 lines Diff to previous 1.3 (colored) next main 1.4 (colored) #include "namespace.h" Revision 1.4 / (download) - annotate - [select for diffs], Sat Feb 25 15:40:11, keep local changes. clean up id usage Revision 1.1.1.2 / (download) - annotate - [select for diffs] (vendor branch), Sat Feb 25 09:13:23 1995 UTC (20 years, 1 month:27 1993 UTC (21:24:09 1993 UTC (21.
http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/gen/wait.c
CC-MAIN-2015-18
refinedweb
396
78.45
). Modules without a back light are not so common but it is still worth checking before you buy. LCDs without the adaptor require 8 or 12 connections (see 4bit / 8bit below) and screens with the adaptor only need 4 connections. This makes the modules with the I2C adaptors far easier to wire up. One final thing to look out for is the character set. HD44780s can have one of two different character sets; European or Asian. Arduino Libraries A key benefit of using a library is that we do not need to care that much about the technical details or timings when using the display. The library happily does all of this for us. On the downside, when different libraries try to use the same resources it can be very difficult to find the problem. The Arduino IDE comes with a basic LiquidCrystal library pre installed. This works with parallel interfaces only. It works fine but has some limitations. There are various other Character LCD libraries available. The two I use and recommend are NewLiquidCrystal by Francisco Malpartida and Bill Perry’s Extensible hd44780 LCD library. NewLiquidCrystal is a collection of libraries that can handle almost all HD44780 compatible displays. It has a number of benefits over the default library, including the ability to handle screens with an I2C adapter. NewLiquidCrystal is a replacement for the default library so the default library has to be removed from the Arduino’s libraries folder. Extensible hd44780 LCD library is still fairly new but seems to work well. Download the NewLiquidCrystal library. From the main wiki page click the Download link. On the download page, download the latest version. Which at the time of writing this update is 1.3.4. The download is a zip file. From inside the zip archive extract the NewLiquidCrystal folder Go to your Arduino library folder and delete the default LiquidCrystal library Then copy the NewLiquidCrytal library to the Arduino library folder If the Arduino IDE is open you will need to restart it to make the new library accessible. Commands The following command examples assume the lcd object has been called lcd. For example LiquidCrystal lcd(12, 11, 5, 4, 3, 2); Parallel Interface: Getting Started with a JHD162A 16×2 display To get started we will use a 16×2 JHD162A display in 4bit mode with the HelloWorld example from the Arduino IDE. The JHD162A is a very popular, cheap and easy to source 16×2 display. JHD162A Pins HD44780 compatible displays like the JHD162A display have 16 pins (14 plus 2 for a backlight). - VSS is GND - VCC is voltage in. - VEE is the display contrast pin. - The RS pin is the Register Select pin. The HD44780 can accept 2 kinds of data; text and commands. The RS pin tells the HD44780 which type data the current value is. Set the pin LOW for command data and HIGH for ascii character data. The pin actually controls where in the LCDs memory data is written to. There are 2 options. - 1 – The data register. This holds values intended for the screen. - 2 – An instruction register. This is used to pass instructions to the screen. IE the current data is a command. - The R/W pin is a Read/Write pin. Apart from writing to the screen you can also read from it and the R/W pin controls which one you are doing. Set R/W LOW for write and HIGH for read. Note: the default Arduino LCD library only allows you to write and why most getting started circuits show this pin connected directly to GND (mine included). - E is the Enable pin, this enables writing to the registers. It tells the LCD there is data available on the data pins - BD0 to BD7 are data pins. These are used to pass the value you wish to write to a register. Or to read when you are checking the value of a register. - LED+ and LED- are used to power the back light LED if one is available VEE controls the screens contrast and is generally connected to a potentiometer allowing the contrast to be adjusted. In these examples I am using a fairly large 10K pot but small trimmers can also be used. 4bit and 8Bit HD44780 compatible displays can use 4bit mode or 8bit mode. In 4bit mode 4 pins are used for the data and in 8bit mode 8 pins are used. In 4bit mode the 8bits are split in to 2 4bit values and sent to the lCD separately. This takes extra time. Of course, we are talking milliseconds so you are unlikely to notice any difference. Update: There does not appear to be any speed difference between 4bit mode and 8bit mode when using the default LiquidDisplay library. This may be due to the library not using the R/W pin correctly or it may be due to how the Arduino maps pins. Have now found further reference over at PRJC. The page also lists the LiquidDisplayFast library. So if you really need the screen to update quickly the LiquidDisplayFast library or the NewLiquidCrystal library (5 times faster) may be the way to go. There is also a difference when using the NewLiquidCrystal library which appears to use the RW flag correctly and can be up to 5 times faster than the default library. It all comes down to pins, if you want to have an LCD but need the pins for other things go 4bit. If speed is important and you don’t need the pins, go 8bit. If pins are really important and you can’t spare even the ones required for 4bit then you should consider using a I2C adapter. This is slower still but uses far fewer pins (just 2). See below for more. Connecting to an Arduino The chances are you will need to solder header pins to the display, after this create the following circuit. Because we are using 4bit mode, the R/W pin is pulled LOW by connecting it to GND. Sketch The sketch we are starting with is the Hello World example found on the Arduino website. Open the IDE, copy the below sketch and paste in to the IDE and upload. If everything is OK you should see the LCD come to life and display “hello, world!” on the top line. On the bottom line you should see a count slowly count up in seconds. If you are using an older IDE you may get a “No such file or directory” compile error: D:\ProgsII\arduino-163\libraries\NewliquidCrystal\I2CIO.cpp:36:21: fatal error: Wire.h: No such file or directory #include <Wire.h> ^ compilation terminated. Error compiling. If you do, either download the latest IDE or edit the library file. To edit the library file, go to the NewLiquidCrystal library folder, find the I2CIO.cpp file, open in a text editor, find the following (will be near the top of the file) #if (ARDUINO < 10000) #include <../Wire/Wire.h> #else #include <Wire.h> #endif and change it to #include <Wire.h> The sketch should now compile. Sketch Main Parts This is a fairly simply sketch so there are not too many key parts. Tell the compiler you want to add the LiquidDisplay library Create a instance of the lcd object using 4bit mode by only specifying 4 data pins (5,4,3,and 2). Initialize the LCD and specify the size. Display “hello, world!” at the current cursor position. Since this is the first thing printed the cursor is at the default 0,0 position. Move the cursor to position 0,1. This is the first place on the second line (x,y). Display the number of seconds since the Arduino started or was reset (millis() divided by 1000 equals seconds). numeric values are automatically converted to ascii before displaying. This means the number 1 is played as “1”. Parallel interface back light When using a LCD with a parallel interface you have full control over the back light. This not only includes turning it on and off but also dimming it. Turning on and off is simply a case of connecting to power or not. To make back light appear dimmer we can use another potentiometer or PWM. A potentiometer offers manual control. PWM offers automated control. The back light of the JHD162A is a LED matrix, this means we can make them dimmer by increasing the resistance, either by using different resistor values or by using a potentiometer. Here is the bread board example with an added potentiometer connected to LCD pin 15. This is the back light power + pin. Turning the potentiometer increases or decreases the back light brightness. To allow the Arduino to control the back light we use a PWM signal. The PWN signal turns the LED back light on and off very quickly which, to the human eye, makes it look dimmer. It is tempting to connect the back light power connector directly to an Arduino pin and this may work. But we don’t know how much current the back light draws and the data sheet does not always say. So you shouldn’t do it. Although Arduino pins can supply a maximum of 40mA, 40mA is the maximum for very short periods of time. Arduino pins cannot provide the full 40mA for any length of time. A better way is to use a transistor as a switch. In this example I am using a 2N222 NPN transistor on the LOW side (GND side). You could also use a PNP transistor on the HIGH side (+5V side). Connect the back light plus pin to 5V via a 220 ohm resistor (or similar). Connect the back light minus pin to the collector (C) pin of the 2N222. Connect transistors emitter pin (E) to GND. Connect the transistors base pin (B) to a 1K ohm resistor and then the resistor to Arduino pin 6. I chose pin 6 because it can be used for PWM. I modified the Hello World sketch to add PWM control. The following sketch increases the PWM value by 10 every loop. This increases the back light brightness (0 is off, 255 is full on). You may notice that the value of brightness never gets to 255! After you have added the 2N2222 transistor to the circuit upload the sketch. Here we are using D6 to control the back light brightness and changing the value of brightness in analogWrite(backLightPWMpin, brightness) changes the back light intensity. Automatic dimmer control using PWM. If you have read through the commands in the above table you may have noticed that the NewLiquidCrystal library has this function built in. The setBacklight() command does exactly the same thing in the same way. First let the library know what pin you are using with setBacklightPin() then set the brightness using setBacklight(). As with analogeWrite 0=off and 255 = full on. I2C Interface: Getting Started with a 20×4 display with I2C daughter board The I2C daughter board is a small add on that converts I2C communication to parallel communication. Among the various different I2C adapters there are two common ones. One with a fixed address and one with jumpers/solder pads that allow you to change the address. The small trimmer/pot is connected to VEE on the LCD and is used to adjust the contrast. Modules with fixed addresses usually have an address of HEX 27 (0x27) but can also have 0x20 or 0x3F (one of the first adapters I bought was set to 0x3F but I haven’t come across any since). Modules with jumpers/pads normally have 3 jumpers, A0, A1 and A2. If none of the jumper are closed the address is 0x27 (normal status when purchased). If you cannot get the screen to work and you think you have the wrong address use an I2C scanner to find the screen’s address or use the diagnostic tool within the Extensible hd44780 LCD library (see below). The adapters have 6 pins. 2 for power, 2 for communication, and 2 for the back light. Power and communication pins GND goes to GND VCC goes to +5V SDA goes to Arduino pin A4 SCL goes to Arduino pin A5 I2C works best with pull up resistors, therefore A4 and A5 should be pulled HIGH to 5V with 4.7k ohm resistors. Back light pins On the I2C adaptor, the back light is controlled by two pins. Short the pins with a jumper to enable the back light. Remove the jumper to disable the back light. On some adapters the positive pin connects directly to the controller chip and on others it goes to a transistor. On LCDs with the I2C adapter, the back light cannot be dimmed. It can be on or off only. To enable the Arduino to control the back light, connect the back pins on the I2C board to a transistor and then the transistors base pin to the Arduino (via a 1K ohm resistor). All the I2C boards I have use the PCF8754 chip, either the Philips PCF8754T or the NXP PCF8574/PCF8574A. The devices without an ‘A’ in the suffix have a base address of 0x20 and a range from 0x20 to 0x27. The devices with an ‘A’ in the suffix have a base address of 0x38 and a range from 0x38 to 0x3F. Philips PCF8754T data sheet. NXP PCF8574/PCF8574A data sheet. Once you have everything connected, LCDs with a I2C adaptor act pretty much like those without. Using the library is the same and the commands are the same. Circuit diagram Hello World Here is a very quick hello world sketch. It simply displays “Hello World!” on the screen. If you look at the library wiki you may notice that the example they give shows the constructor with just the address, no pin data. When the pin data is not given, the library will add the default pin mapping for the LCDXIO LCD/expander backpack sold by Francisco Malpartida’s ElectroFun company and unfortunately this is not the same as other I2C adapters and so we need to specify the pins. If your LCD shows faint solid blocks with one of the blocks flashing (and usually no back light) it means you have the wrong pin definitions. Back light Control When using an I2C adaptor, we can turn the back light on and off with the lcd.backlight() and lcd.noBacklight() commands. No extra connections are required. The following sketch displays Hello World on the LCD and then flashes the back light on and off every second. This uses the same circuit as above. Just SDA and SCL on pins A4 and A5. Dimming the back light is not possible when using a I2C adapter unless you modify the hardware. 20×4 LCD memory map and line overflow Due to how the memory is allocated inside the LCD device, characters may not over flow as you expect. When characters over flow from line 1 they continue on line 3. When line 2 over flows the text continues on line 4. Custom Characters Most HD44780 compatible LCDs have 8 memory locations that can be used for creating user defined characters. You create a custom character by putting the character data in to a byte array then passing the array to the library using createChar() command. Each character occupies a 5×8 grid If you use binary when defining the array you can see the character you are creating. For example, a smily face :) and a sad face :( lcd.createChar(1, chr1); creates character 1 using the data in the array named chr1. To display this character simply use lcd.write(1); Although only 8 characters can be created at any one time, the characters can be redefined at anytime and creating new characters on the fly can give the appearance that more than 8 exist, although only 8 can be displayed at any one time. If you redefine a character while it is being displayed on screen then the character will change to the newly created character. Online Custom Character Generator Omer Kilic has created a nice custom character generator that automatically produces the Arduino code. maxpromer has another, similar, generator here. Large Fonts Using custom characters it is possible to create large fonts. These were created by digimike on the Arduino forum Over at AVR Freaks, china92 posted an Excel based design guide. There are many many more and googling “Arduino LCD large font” will give you a lot of places to look. Custom Character Demos Arduino demo: Non Arduino : Extensible hd44780 LCD library Bill Perry’s Extensible hd44780 LCD library looks very promising. Extensible hd44780 LCD library can be downloaded from github. The library covers all the regular commands and includes a diagnostic sketch in the examples. Have an HD44780 LCD but can’t get it working or not sure how to initialise the library, run the diag sketch and it will tell you. Install the library in the usual way. Load the “I2CexpDiag” sketch from the library examples Compile, run and open the serial monitor. Notes Resetting the Arduino does not reset the LCD Using clear() is very slow. In many cases filling the screen with spaces is quicker. If speed is important, only update the parts of the screen that need updating and don’t write data if it has not changed. Using home() is also slow. There is an issue with the back light on some LCD shields. See this post in the Arduino forum. The Extensible hd44780 library works around the problem in software. Further information & links Francisco Malpartida’s New LiquidCrystal wiki and download. Good information about LCDs with I2C adapters at Arduino Info. The I2C LCD page also has information about other types of adapters. It is worth while checking out the whole site. Lots of good information about Arduino and Arduino compatible modules. Reducing Arduino Pins: If you don’t have a I2C adaptor but have a 74HC595 and want to use less pins have a look at Juan Hernandez’s library that uses SPI and a 74HC595. A new HD44780 LCD library by Bill Perry looks very promising. Extensible hd44780 LCD library can be downloaded from github. The library covers all the regular commands and includes a dianostic sketch in the examples. Have a HD44780 LCD but not sure how to initialise the library, run the diag sketch and it will tell you. Programming Electronics Academy has a good beginner guide to LCD character displays that covers character positions. Arduino forum post about back light brightness. Want to really get to understand how these screens work? The 8-Bit Guy has an excellent video showing how to build a non microprocessor control box for an HD44780 LCD. I remember programming 6800 based boards like this many many years ago. Very nice page and writeup. A couple of things worth noting. With fm’s library setBackLightPin() is obsolete. It was left in for backward compatibility but the intent is that the pin and polarity are now set in the constructor. My reasoning for doing this (yes I did lots of work on that library) was to ensure that the only differences between i/o interfaces is handled in the constructors and the main line sketch code would work across all h/w without modifications. One of the big advantages of hd44780 is that it can be installed from the IDE library manager. Another advantage for the LCDs that use i2c backpacks is that auto configuration. So unlike with fm’s library the sketch does not have to specify the i2c address, pin mappings, or backlight control information. The backpack class also supports backpacks that use MCP23008 chips like the adafruit #292 board. In terms of 8 bit vs 4 bit speed. Yes 8 bit is faster. In terms of using the r/w line, in reality it will typically be slower since it requires flipping all the i/o pins around from output to input mode and then back again. If not using direct port i/o that will definitely make things slower, particularly on the AVR platforms since the AVR core library functions like digitalWrite()/digitalRead() use poor semantics and are using very simplistic code that is quite slow. hd44780 does very smart command execution processing. It allows the Arduino to run in parallel with the LCD commands. i.e there are no blind/dumb fixed period delays. hd44780 only delays if the processor attempts to talk to the LCD before the command execution for the previous has not passed. And even then it will only delay the remaining portion of time vs the entire amount of time like other libraries. This allows it to hide the overhead of many things like the i2c byte transfer times, and the the overhead of operations like digitalWrite(). It also allows the sketch to configure command execution times for LCDs that might be slower than the default reference design or for displays that are faster for those that want a bit more performance. hd44780 has been tested on many different platforms, pic32, ARM, AVR, ESP8266 and the intent is that it “just works’ on all platforms. I’ve got a bunch of stuff planned for hd44780, including handling line endings and display scrolling. But as of right now since it isn’t, hd44780 will crash the compiler with an error if println() is every used in a sketch for the lcd object. Excellent tutorial. Got me going in a few minutes. I really appreciate the detailed information on the library commands as well. Great job! Thanks so much for the comprehensive tutorial.. Here’s a simple sketch to demonstrate this: #include #define BRIGHTNESS_PIN 6 // Must be a PWM pin LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); byte brightness = 0; bool sense = 1; void setup() { } lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(“Here’s some text”); void loop() { analogWrite(BRIGHTNESS_PIN, brightness); delay(10); if(sense) { } } } if(brightness 0) { brightness–; } else { sense = 1; Is it possible , for i2c equipped display, to be connected to pins other than A4 and A5 on the Arduino? yes but you need to use a software i2c library such as SoftI2CMaster. Have a look at Many thanks, your tutorial is great, it’s been very helpful to my understanding of this device. Great tutorial. Just one question: it’s okay to do the exact same same thing to control contrast by code, isn’t it? Same resistors, same transistor ?
https://www.martyncurrey.com/arduino-with-hd44780-based-lcds/
CC-MAIN-2022-21
refinedweb
3,771
73.27
CodePlexProject Hosting for Open Source Software A quote from Chapter 4: Modular Application Development () "It may also ask the container to resolve an instance of a type it needs." What is the best way to achive this? I have a concrete example of this worked out. It is a small extension on top of the Modularity with MEF Quickstart. It can be found here: Summary of the changes: - new assembly LibforModuleE with Class1.cs, has [Export] attribute - ModuleE references Class1 in LibforModuleE.dll (LibForModuleE.dll is copied along ModuleE in it's post-build step) - Class1 logs and therefore [Import]s the ILoggerFacade - During the initialisation of ModuleE, a call is made into Class1 (ModuleE.cs line 54) - Since the ILoggerFacade never got imported in Class1, the application crashes during the initialization of ModuleE (Class1.cs line 15) Given: - I cannot add a hard reference from the main ModularityWithMef.Desktop assembly to the LibForModuleE assembly (then I could - in ConfigureAggregateCatalog - add that assembly to the AggregateCatalog ) - the LibforModuleE.dll is not in the DirectoryModules sub folder (then the DirectoryCatalog would have picked it up) These 2 solutions would void the on-demand aspect of ModuleE (and its dependencies) What is the canonical way of getting the ILoggerInterface imported into Class1, in other words: how to ask the container to resolve the ILoggerFacade? Bonus question: next to importing the necessary ILoggerFacade into Class1, it there a way to add Class1 itself into the container during the initialisation of ModuleE, so that some other class (e.g. Class2) can then import an instance of the exported Class1? Thanks in advance! Jan Verley Hi, We checked the sample you provided, and we found that the cause of this problem is that the parts of the LibforModuleE.dll are not being discovered by MEF, and therefore you won't be able to resolve an instance of Class1 from the container. Hence, you might have to discover the parts in your LibforModuleE.dll assembly explicitly. As you mentioned, this could be achieved using the AggregateCatalog class provided by MEF. In my opinion, to avoid loosing the on-demand aspect of ModuleE (not overriding the ConfigureAggregateCatalog), you could retrieve the AggregateCatalog instance as a dependency in your ModuleE's constructor. This way you could register the missing parts from the LibforModuleE.dll when the module is loaded. An example of this could be like in the following code snippet: [ModuleExport(typeof(ModuleE))] public class ModuleE : IModule { (...) private readonly AggregateCatalog catalog; (...) [ImportingConstructor] public ModuleE(IModuleTracker moduleTracker,AggregateCatalog catalog) { this.catalog = catalog; this.catalog.Catalogs.Add(new AssemblyCatalog(typeof(Class1).Assembly)); (...) Once the part is added to the catalog you will be able to retrieve the exported types from the container. For example in ModuleE, Initialize method or from other class that requires it. To retrieve the desired exported class you could access the container via the ServiceLocator. For example like this: public void Initialize() { var testInstance = ServiceLocator.Current.GetInstance<Class1>(); testInstance.Test(); (...) Note that if you don't retrieve the class from the container, the imports will not be satisfied. Additionally for more information you could check the MEF Programming Guide. I hope you find this useful, Agustin Adami I was aware of the root of the problem: the non-discovery by MEF of Class1. Your proposed solution works indeed! I was not aware that - the AggregateCatalog was available as a part in the Container (it feels a bit circular/recursive) - adding types to the AggregateCatalog was possible/made sense at this moment, long after the bootstrapper had finished. 1 final question: Is it possible to avoid the dependency on the ServiceLocator to retrieve the class from the container and use a more pure MEF method? And if not, is the use of the static ServiceLocator.Current not an issue when writing unit tests? As far as I understand, this makes it impossible to inject the dependency? Thanks! Jan Hi Jan, Based on my understanding you will be able to retrieve the Class1 from the container using MEF conventional methods from any class in the module's project as long as it is resolved after the library assembly is discovered (i.e. when the module's constructor completes). For example any view or view model classes which have a dependency to Class1 should be able to resolve it without problems. Although, this will not be possible if you need to resolve a class which contains a dependency to the exported Class1 in your IModule's class; as far as I now, for this case you will have to do it through the ServiceLocator. Also, if you wish to test the aforementioned module class using the ServiceLocator will involve having an additional dependency to mock (i.e. the service locator). Regards, Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://compositewpf.codeplex.com/discussions/352043
CC-MAIN-2017-30
refinedweb
829
55.24
Example 2-1 shows a class that represents a rectangle. Each instance of this Rect class has four fields, x1, y1, x2, and y2, that define the coordinates of the corners of the rectangle. The Rect class also defines a number of methods that operate on those coordinates. Note the toString( ) method. This method overrides the toString( ) method of java.lang.Object, which is the implicit superclass of the Rect class. toString( ) produces a String that represents a Rect object. As you'll see, this method is quite useful for printing out Rect values. package je3.classes; /** * This class represents a rectangle. Its fields represent the coordinates * of the corners of the rectangle. Its methods define operations that can * be performed on Rect objects. **/ public class Rect { // These are the data fields of the class public int x1, y1, x2, y2; /** * The is the main constructor for the class. It simply uses its arguments * to initialize each of the fields of the new object. Note that it has * the same name as the class, and that it has no return value declared in * its signature. **/ public Rect(int x1, int y1, int x2, int y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } /** * This is another constructor. It defines itself in terms of the above **/ public Rect(int width, int height) { this(0, 0, width, height); } /** This is yet another constructor. */ public Rect( ) { this(0, 0, 0, 0); } /** Move the rectangle by the specified amounts */ public void move(int deltax, int deltay) { x1 += deltax; x2 += deltax; y1 += deltay; y2 += deltay; } /** Test whether the specified point is inside the rectangle */ public boolean isInside(int x, int y) { return ((x >= x1)&& (x <= x2)&& (y >= y1)&& (y <= y2)); } /** * Return the union of this rectangle with another. I.e. return the * smallest rectangle that includes them both. **/ public Rect union(Rect r) { return); } /** * Return the intersection of this rectangle with another. * I.e. return their overlap. **/ public Rect intersection(Rect r) { Rect result =); if (result.x1 > result.x2) { result.x1 = result.x2 = 0; } if (result.y1 > result.y2) { result.y1 = result.y2 = 0; } return result; } /** * This is a method of our superclass, Object. We override it so that * Rect objects can be meaningfully converted to strings, can be * concatenated to strings with the + operator, and can be passed to * methods like System.out.println( ) **/ public String toString( ) { return "[" + x1 + "," + y1 + "; " + x2 + "," + y2 + "]"; } }
http://books.gigatux.nl/mirror/javaexamples/0596006209_jenut3-chp-2-sect-1.html
CC-MAIN-2019-13
refinedweb
402
66.84
Hide Forgot Not sure whether this is gdb or valgrind issue. I wanted to write myself small automatic sanity test to make sure feature (bug 672959) is working (that's why the c code is a bit contrived). And I hit the following problem. --- something.c --- #include <stdio.h> void f (int x); int main (int argc, char *argv[]) { int a; f(a); return 0; } void f (int x) { static int var __attribute__ ((used)) = 42; if(x) puts("hello, world"); } --- something.c --- --- script.gdb --- target remote | vgdb b 10 c set (a=5) c q --- script.gdb --- 1. gcc -g something.c 2. valgrind --vgdb-error=0 ./a.out 3. gdb -x ./script.gdb ./a.out ... relaying data between gdb and process 17458 [Switching to Thread 17458] 0x00000036d2400b00 in _start () from /lib64/ld-linux-x86-64.so.2 Breakpoint 1 at 0x4004d3: file something.c, line 10. Breakpoint 1, main (argc=1, argv=0x7ff000348) at neco.c:10 10 f(a); ./script.gdb:5: Error in sourced command file: Remote connection closed (gdb) Tha same thing happens when I let the valgrind hit the bug. I was unable to reproduce something like that with gdb-gdbserver, that's why I'm filing this against valgrind, but I might be wrong, when copy pasted these commands work just fine. # rpm -q valgrind gdb valgrind-3.8.1-2.1.el6.x86_64 gdb-7.2-59.el6.x86_64 The issue is that the valgrind gdbserver doesn't report final process exit. gdb is waiting for a reply after the continue but doesn't get anything, sees the remote connection gone and freaks out. A not really correct patch (it reports exit was just fine no matter what) to get the sample script working would be: Index: coregrind/m_gdbserver/server.c =================================================================== --- coregrind/m_gdbserver/server.c (revision 13022) +++ coregrind/m_gdbserver/server.c (working copy) @@ -730,6 +730,12 @@ void gdbserver_terminate (void) { + if (resume_reply_packet_needed) { + resume_reply_packet_needed = False; + prepare_resume_reply (own_buf, 'W', 0); + putpkt (own_buf); + } + /* last call to gdbserver is cleanup call */ if (VG_MINIMAL_SETJMP(toplevel)) { dlog(0, "error caused VG_MINIMAL_LONGJMP to gdbserver_terminate\n"); $ gdb -x ./script.gdb ./a.out [...] Reading symbols from /usr/local/src/tests/vgdb/a.out...done. relaying data between gdb and process 3729 [Switching to Thread 3729] 0x0000003e77a01530 in _start () from /lib64/ld-linux-x86-64.so.2 Breakpoint 1 at 0x4004eb: file something.c, line 10. Breakpoint 1, main (argc=1, argv=0x7feffff68) at something.c:12 12 f(a); [Inferior 1 (Remote target) exited normally] I'll report upstream and see if we can get the proper exit code of the process reported to gdb before final termination..
https://bugzilla.redhat.com/show_bug.cgi?id=862795
CC-MAIN-2019-47
refinedweb
436
66.13
The XML sitemap index is a file that contains many XML sitemap files for your website, where you can use it to submit it to Google Search Console rather than submitting multiple files. The best use of the XML sitemap index is for dynamic sites with many new pages every day that you need to include in the XML sitemap. You can submit up to 50,000 URLs in a single XML sitemap file, referring to Google's guidelines and rules on building XML sitemap files, plus their last updated date, images, and caption for the images. There are many reasons to get the URLs from the XML sitemap for your site or any other website, such as: When performing a competitor analysis, knowing how many pages they have is very important for building a content strategy and the frequency of publishing new content that you can use to compete with them. Think of it; having hundreds or thousands of URLs with titles and categories in an Excel sheet can help you develop or upgrade your content strategy. Knowing how many published pages are on your website and comparing them to the number of indexed pages on Google is one of the first steps in the indexed pages audit. After comparing the number of published pages and the number of indexed pages on Google, your next step is to compare these numbers with the valid pages from Google Search Console and start analyzing what is happening to your URLs and which URLs to remove or fix. To make the requests on the XML site map index of the WordPress website. To parse and read the XML sitemap content. To save the output in a CSV or XLS format. To encode the Arabic URLs To see the execution progress of your script. First, we'll start with importing the libraries in our Jupyter Notebook or any other Python IDE. import pandas as pd from urllib.parse import unquote import requests from bs4 import BeautifulSoup as bs from tqdm.notebook import tqdm You can get the path of the XML sitemap index for Yoast SEO Plugin by typing /sitemap_index.xml after the domain name, for example: Then a list of XML files will show up to you. In this tutorial, we'll focus on the posts files. As you can see from the image, there are three posts files. The number of the files will help us in our loop. The default naming for the posts files in the Yoast SEO plugin is post-sitemap{index}.xml, where the {index} is the number of the file. xml_list = [] urls_titles = [] for i in range(1,4): xml = f"{i}.xml" ua = "Mozilla/5.0 (Linux; {Android Version}; {Build Tag etc.}) AppleWebKit/{WebKit Rev} (KHTML, like Gecko) Chrome/{Chrome Rev} Mobile Safari/{WebKit Rev}" xml_response = requests.get(xml,headers={"User-Agent":ua}) xml_content = bs(xml_response.text,"xml") xml_loc = xml_content.find_all("loc") for item in tqdm(xml_loc): uploads = item.text.find("wp-content") if uploads == -1: xml_list.append(unquote(item.text)) urls_titles.append(unquote(item.text.split("/")[-2].replace("-"," ").title())) xml_data = {"URL":xml_list,"Title":urls_titles} xml_list_df = pd.DataFrame(xml_data,columns=["URL","Title"]) xml_list_df.to_csv("xml_files_results.csv",index=False) You can find the results in a file named xml_files_results.csv, where you can open it in Excel or Google sheets.
https://www.nadeem.tech/how-to-get-wordpress-xml-sitemap-urls-using-python/
CC-MAIN-2022-27
refinedweb
553
64.3
The Java Specialists' Newsletter Issue 1372006-12-28 Category: Tips and Tricks Java version: JDK 1.4+ GitHub Subscribe Free RSS Feed Welcome to the 137th edition of The Java(tm) Specialists' Newsletter. The JavaPolis conference was a huge success, with lots of interesting talks, exhibitors and people. Well done to Stephan Janssen and his team! At the conference, Bill Venners interviewed me for his website. You will especially enjoy the "blooper segment", where Bill could not compose himself :-) Let me know what you think ... So, here is wishing you a fantastic 2007. May you discover hidden paths through the JDK 1.6. NEW: Please see our new "Extreme Java" course, combining concurrency, a little bit of performance and Java 8. Extreme Java - Concurrency & Performance for Java 8. A few months ago, Thomas Vogler from Software AG pointed out an ugly idiom that has been creeping into Java code. In both Log4j and the java.util.logging frameworks, it is typical that when we construct the logger, we use the name of the class as the name. You could, for example, see code like this: package com.cretesoft.tjsn; import java.util.logging.Logger; public class Application { private final static Logger logger = Logger.getLogger(Application.class.getName()); public static void main(String[] args) { Application m = new Application(); m.run(); } public void run() { logger.info("Hello"); } } Every time we make a new class, we habitually put a static logger variable at the top. This is typically copy & pasted from another class, so we have to remember to change the class to be correct, otherwise the logging is incorrect and thereby confusing. There are probably AOP and IoC ways of doing this easily and elegantly. Ideally I would never want to define a "logger" variable - that should automatically be inside my class, and I should be able to just use it. We wanted to be able to define an idiom that we could copy & paste without having to change it. However, the static context for some reason does not know in which class it is being called. When you are in a non-static context, you can call the getClass() method. getClass() One approach would be to do the following. Leave the static logger undefined, and initialize it in an initializer block: package com.cretesoft.tjsn; import java.util.logging.Logger; public class CleverApplication { private static Logger logger = null; { logger = Logger.getLogger(this.getClass().getName()); } public static void main(String[] args) { try { logger.info("static Hello"); } catch (NullPointerException e) { System.out.println( "failed to call Logger from static context"); } CleverApplication m = new CleverApplication(); m.run(); } public void run() { logger.info("Hello"); } } There are several reasons why this is a not a good idea. First off, the logger is not available from a static context. Secondly, every time a new instance is created, we make a new logger. This could be avoided if we used the lazy initialization idiom, but that would then introduce contention. Thirdly, the class name of the instance might be a subclass of CleverApplication. Another approach is to create a LoggerFactory that uses the method call stack to determine from where it is being called. It then returns a logger instance depending on who called it. Here is how you could use it: package com.cretesoft.tjsn; import java.util.logging.Logger; public class BetterApplication { private final static Logger logger = LoggerFactory.make(); public static void main(String[] args) { BetterApplication m = new BetterApplication(); m.run(); } public void run() { logger.info("Hello"); } } The LoggerFactory can use several approaches for determining who called it. It could see the call stack by generating an exception (the approach I use below). It could use the security manager to determine the context. There might be more approaches, but this one works well enough. package com.cretesoft.tjsn; import java.util.logging.Logger; public class LoggerFactory { public static Logger make() { Throwable t = new Throwable(); StackTraceElement directCaller = t.getStackTrace()[1]; return Logger.getLogger(directCaller.getClassName()); } } There is one little problem with this method. A method should ideally not be dependent on who calls it. There is probably a law for it, whose name I could not remember. Using this idiom will make it easier to get the logger correct per class, without too much effort. Kind regards from the Island of Crete Heinz P.S. I got my 5-year residence permit for Greece today. We have moved into our rental property, so if you come to Crete, make sure you visit us in Chania. The roads are not that fast-moving - our poor new car is averaging 30 km/h according to the navigational system. The best map available here is Google Earth. My daughter Connie and I discovered a little backroad down to the beach by looking at satellite pictures :-) Tips and Tricks Articles Related Java Course
http://www.javaspecialists.eu/archive/Issue137.html
CC-MAIN-2016-30
refinedweb
802
59.4
Inspired by cubism and various projects using genetic algorithms to paint the Mona Lisa here a method for teaching your computer to be an artist! I bring you the artificial artist! The idea is to use regression to "learn" what an image looks like and then draw the learned image. By choosing the parameters of the regressor carefully you can achieve some interesting visual effects. If all this artsy talk is too much for you think of this as a way to compress an image. You could store the weights of the regressor instead of the whole image. First some standard imports of things we will need later: %matplotlib inline from base64 import b64encode from tempfile import NamedTemporaryFile import numpy as np import scipy import matplotlib.pyplot as plt from matplotlib import animation from IPython.display import HTML from sklearn.ensemble import RandomForestRegressor as RFR from skimage.io import imread from skimage.color import rgb2lab,lab2rgb from skimage.transform import resize,rescale from JSAnimation import IPython_display lakes = imread('') f,ax = plt.subplots(figsize=(10,6)) ax.xaxis.set_ticks([]); ax.yaxis.set_ticks([]) ax.imshow(lakes, aspect='auto') <matplotlib.image.AxesImage at 0x11e47a850> newfie = imread('') f,ax = plt.subplots(figsize=(10,6)) ax.xaxis.set_ticks([]); ax.yaxis.set_ticks([]) ax.imshow(newfie, aspect='auto') <matplotlib.image.AxesImage at 0x122aadf50> The Artificial Artist: a new Kind of Instagram Filter¶ The artificial artist will be based on a decision tree regressor using the $(x,y)$ coordinates of each pixel in the image as features and the RGB values as the target. Once the tree has been trained we ask it to make a prediction for every pixel in the image, this is our image with the "filter" applied. All this is taken care of in the simple_cubist function. Once you see the first filtered image you will understand why it is called simple_cubist. We also define a compare function which takes care of displaying several images next to each other or compiling them into an animation. This makes it easy to see what we just did. def simple_cubist(img): w,h = img.shape[:2] img = rgb2lab(img) xx,yy = np.meshgrid(np.arange(w), np.arange(h)) X = np.column_stack((xx.reshape(-1,1), yy.reshape(-1,1))) Y = img.reshape(-1,3, order='F') min_samples = int(round(0.001 * len(X))) model = RFR(n_estimators=1, n_jobs=6, max_depth=None, min_samples_leaf=min_samples, random_state=43252, ) model.fit(X, Y) art_img = model.predict(X) art_img = art_img.reshape(w,h,3, order='F') return lab2rgb(art_img) def compare(*imgs, **kwds): """Draw several images at once for easy comparison""" animate = kwds.get("animate", False) if animate: fig, ax = plt.subplots(figsize=(8,5)) ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) anim = animation.FuncAnimation(fig, lambda x: ax.imshow(imgs[x%len(imgs)], aspect='auto'), frames=len(imgs), interval=1000) fig.tight_layout() return anim else: figsize = plt.figaspect(len(imgs)) * 1.5 fig, axes = plt.subplots(nrows=len(imgs), figsize=figsize) for a in axes: a.xaxis.set_ticks([]) a.yaxis.set_ticks([]) for ax,img in zip(axes,imgs): ax.imshow(img) fig.tight_layout() # Take the picture of the Lake District and apply our # simple cubist filter to it simple_lakes = simple_cubist(lakes) compare(lakes, simple_lakes, animate=True)
http://betatim.github.io/posts/artificial-artist/
CC-MAIN-2018-30
refinedweb
535
52.66
i have a question......i have a program that i am using two dimensional arrays to store words. for example for an array[10][10], the first subscript will contain a word and the second subscript will contain the characters of trhe word. i have decided that i would rather be using a linked list instead of an array, is there any way to take the words stored in each subscript and put them into one place in a linked list. here is some example code that i came up with trying to do this. #include <iostream.h> #include <fstream.h> #include <string> struct StackFrame { char data; StackFrame *link; }; typedef StackFrame* StackFramePtr; void main() { char array[1][5]; array[0][0] = 'h'; array[0][1] = 'e'; array[0][2] = 'l'; array[0][3] = 'l'; array[0][4] = 'o'; StackFramePtr top; top = new StackFrame; top->data = array[0]; top->link = NULL; cout << top->data; }
http://cboard.cprogramming.com/cplusplus-programming/35961-question.html
CC-MAIN-2015-48
refinedweb
153
69.21
Opened 9 years ago Closed 7 years ago Last modified 4 years ago #2145 closed defect (fixed) list_filter not available if model contains OneToOneField Description If a model is related to via a OneToOneField (even if it's not used in the admin list), the list_filter block doesn't appear on the admin list page. The offending code appears to be in django.contrib.admin.views.main 571 def get_filters(self, request): 572 filter_specs = [] 573 if self.lookup_opts.admin.list_filter and not self.opts.one_to_one_field: 574 filter_fields = [self.lookup_opts.get_field(field_name) \ 575 for field_name in self.lookup_opts.admin.list_filter] Commenting out "and not self.opts.one_to_one_field" in line 573 reinstates the functionality and appears to have no ill effects. I don't know what it is supposed to be testing for, though, so don't know if it breaks something somewhere else. Attachments (3) Change History (37) comment:1 Changed 9 years ago by anonymous - Cc gary.wilson@… added comment:2 Changed 8 years ago by remco@… comment:3 Changed 8 years ago by anonymous - Resolution set to fixed - Status changed from new to closed comment:4 Changed 8 years ago by ubernostrum - Resolution fixed deleted - Status changed from closed to reopened Please don't modify ticket status anonymously, and if you close a ticket leave a note explaining the rationale. comment:5 Changed 8 years ago by Gary Wilson <gary.wilson@…> - Triage Stage changed from Unreviewed to Accepted comment:6 Changed 8 years ago by alex@… We have a absolutely duplicate ticket:2718 on the same issue with same patch suggested. I hope nobody will be angry on me, I closed ticket:2718 and kept this one as being "earlier" :) This is very trivial fix and I have to maintain it on all my Django powered severs. I am voting to push this change into main tree. comment:7 Changed 8 years ago by bram.dejong+django@… I experience the same trouble, and independently found the same fix... When is this planned to be included in trunk? comment:8 Changed 8 years ago by Simon G. <dev@…> I'll move this to ready to checkin once someone works up a patch. --Simon comment:9 Changed 8 years ago by Simon G. <dev@…> - Needs tests set - Patch needs improvement set ...and some tests would be nice too. Changed 8 years ago by alex@… trivial patch comment:10 Changed 8 years ago by alex@… I've attached the trivial patch which I am using last months on all django installs. comment:11 Changed 8 years ago by Jeremy Dunck <jdunck@…> - Has patch set I've tried to work up a test, but have run into trouble due to tight coupling. I think it may be possible using the web client, but a simple model-based regression test doesn't seem possible. It looks like no other tests require the web client, so I'm reluctant to add the first one. I think the trivial patch given is wrong, in that it misses the point. I think the real problem is that one_to_one_rel is being contributed to the related class, e.g. "place" when it ought to be contributed to the referencing class (e.g. restaurant). I think one_to_one_field is basically just supposed to be a well-known name, like self.pk. I'll attach a different patch in a moment, but note the patch solved two problems for me: this one, and the fact that limit_choices_to on Restaurant was causing the *Place* change list to be filtered based on the limit_choices_to kwargs. This pointed me in what I think is the right direction: one_to_one_field should be contributed to restaurant, not place. All existing tests still pass with the new patch. Changed 8 years ago by Jeremy Dunck <jdunck@…> Contribute to restaurant, not place. comment:12 Changed 8 years ago by Ilya Semenov <semenov@…> +1 on this patch, just run into the same issue and did the same fix. I see absolutely no rationale behind this limitation (list_filter disabled if there's at least one OneToOneField). comment:13 Changed 8 years ago by sgt.hulka@… What needs to be done to push this into trunk? comment:14 Changed 8 years ago by Jos@… I've run into the same problem, waiting for this to be pushed to trunk. comment:15 Changed 8 years ago by anonymous - Needs tests unset - Patch needs improvement unset - Triage Stage changed from Accepted to Ready for checkin Hmm.. not sure why I was so eager for tests. I've moved this on, and thanks for reminding me :) comment:16 Changed 8 years ago by mtredinnick - Patch needs improvement set - Triage Stage changed from Ready for checkin to Accepted Something's not right about this patch. With current trunk ([5983]) and the following two models: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return u"%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField(Place) serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() class Admin: list_display = ('place', 'serves_hot_dogs', 'serves_pizza') list_filter = ('serves_hot_dogs', 'serves_pizza') def __unicode__(self): return u"%s the restaurant" % self.place.name the list filtering displays and works correctly without the patch and is broken when the patch is applied. Current behaviour looks to be correct for this particular example case. On the surface, Jeremy's logic in comment 11 looks correct. In practice, something is going wrong. comment:17 follow-up: ↓ 18 Changed 8 years ago by baumer1122 - Resolution set to worksforme - Status changed from reopened to closed list_filter appears to be working in current svn with OneToOneField. Jeremy's patch no longer breaks Malcolm's example above. Neither svn nor Jeremy's patch fix the other issue with limit_choices_to. comment:18 in reply to: ↑ 17 Changed 8 years ago by anonymous comment:19 Changed 8 years ago by jos@… - Resolution worksforme deleted - Status changed from closed to reopened I still see this problem in svn (revision 6463) It can be recreated with the following model: from django.db import models class System(models.Model): name = models.CharField(maxlength=255) class Admin: list_filter = ( 'name', ) class SystemDeploy(models.Model): system=models.OneToOneField(System) currentversion = models.IntegerField() When system=models.OneToOneField(System) is commented the filters show up. The initial patch created by alex works for me comment:20 Changed 8 years ago by jdunck FWIW, I've stopped using OneToOneField in favor of ForeignKey(unique=True, related_name='<some singular>_one'). OneToOneField is to be dropped some day, if I remember the mail thread correctly (can't find it now). I think it's a bug that ForiegnKey(unique=True) results in a related queryset rather than a single object descriptor. But that's another matter. For now, this works (omitted as before): class Restaurant(models.Model): place = models.ForeignKey(Place, unique=True, related_name='restaurant_one') .... ... >>> p=Place.objects.all()[0] >>> r = p.restaurant_one.all()[0] A bit ugly, but not buggy. comment:21 Changed 8 years ago by semenov I don't think the 1-to-1 relation will be dropped away. It's one of the fundamental database concepts, and officially replacing it with unique-1-t-m would be just plain wrong (since in many times that's like replacing O(1) complexity to O(N)). Still hoping for the bugfix to be applied. I'm also wondering why the 1-to-1 problem was not arised during September Sprint - personally, I forgot about it, using the proposed patch and "empty" records instead of 1-to-1 NULLs for several months. comment:22 Changed 8 years ago by jdunck @semenov: The fact that it didn't rise to attention in the Sept sprint suggests that not that many people (particularly core committers) are using OneToOne. As for 1-1 being cheaper than 1-m, in practical application, accessing the descriptor of a 1-1 field goes and fetches the related record by it's primary key, as does a FK descriptor access. Even if you're talking about querying across the table, it usually goes something like Related.objects.get(o2osomeattribute='x'), which IIRC, Django doesn't munge into a subquery, but rather uses a join anyway. (Arguably another bug.) The fact is that 1-1 is an edge case in lots of code, and fixing the bugs isn't very easy. It needs a champion for it to live, I think. (I'm not a committer, but my tea-reading skills are fairly good.) comment:23 Changed 8 years ago by remco@… "The semantics of one-to-one relationships will be changing soon, so we don’t recommend you use them. If that doesn’t scare you away, keep reading." -- @jdunck: I don't know exactly how the 1-1 not being part of the sprint would suggest that not too many people are using it, as I can equally well state that maybe there was a lot of other stuff to improve and change during the sprint. But I agree with semenov that 1-1 relationships is a fundamental part of defining relationships in data models. So I for one hope this issue get's fixed over time. comment:24 Changed 8 years ago by semenov As for 1-1 being cheaper than 1-m, in practical application, accessing the descriptor of a 1-1 field goes and fetches the related record by it's primary key, as does a FK descriptor access That is only correct in the current (broken) implementation, where a 1-to-1 relation effectively can not have null=True (well you can describe it as NULL, but the ORM code would break on fetching, and I didn't manage to find a simple way to fix that). Once the 1-to-1 is (hopefully) fixed to allow NULL values, it becomes zero time to fetch a missing 1-to-1 value, and a separate database lookup to fetch a missing unique-1-to-m value. Besides of that, it degrades the code readability to have a collection rather than a value where it just doesn't make sense. For example, consider User and Profile models: if user.profile: phone = user.profile.phone else: phone = DEFAULT_PHONE The 1-to-m approach would lead to unneeded overhead (in terms of both effeciency and the code clarity): if user.profile_set.count(): phone = user.profile_set.get().phone # and you always pray it doesn't crash with an AssertionError for 2+ objects else: phone = DEFAULT_PHONE comment:25 Changed 8 years ago by alex@… This discussion needs to be moved to django-developers, because otherwise we add too much unrelated theoretical information to ticket. comment:26 Changed 8 years ago by alex@… comment:27 Changed 7 years ago by gwilson - milestone set to 1.0 comment:28 Changed 7 years ago by tyson - Keywords OneToOneField ModelInheritance editable parent_link added I've just experienced similar problems in trunk (now that the ModelInheritance branch has been merged). I noticed that the OneToOneField.init has kwargseditable?=False hard coded, which breaks how we were using OneToOneFields. The patch I'm submitting restores OneToOneField behaviour to pre ModelInheritance status by checking if the field has parent_link=True before setting editable=False. Changed 7 years ago by tyson Patch to allow editing OneToOneFields comment:29 Changed 7 years ago by tyson comment:30 Changed 7 years ago by anonymous - Keywords MultiTableInheritance added Because multi-table inheritance is achieved using implicit OneToOneFields, any non-abstract parent model classes will not have the list_filter functionality: class Place(models.Model): name = models.CharField(max_length=50) city = models.CharField(max_length=50) class Restaurant(Place): serves_pizza = models.BooleanField() In the example above, Restaurant will have filter functionality, but Place won't! This issue needs to be resolved!!! comment:31 Changed 7 years ago by brosner I am going to commit the original patch. There has been a ton of refactoring since the queryset-refactor branch landed completely overhualing OneToOneFields. I have tested the first patch and it works. I would rather close this as fixed with that change (to me it doesn't seem correct to limit the filtering on that condition). Then if any new bugs surface lets clean those up in new tickets. comment:32 Changed 7 years ago by brosner - Resolution set to fixed - Status changed from reopened to closed comment:33 Changed 7 years ago by brosner For the record, that should have read "that prevented" and not "to prevent" :) comment:34 Changed 4 years ago by jacob - milestone 1.0 deleted Milestone 1.0 deleted Any changes concerning this ticket? I still get the feeling that though for some relationships OneToOneField is conceptually nicer to use, one is better off using a ForeignKey field within django.
https://code.djangoproject.com/ticket/2145
CC-MAIN-2015-22
refinedweb
2,116
64.1
24 November 2010 17:09 [Source: ICIS news] (adds updates throughout with Canadian, Mexican and overall North American shipment data) ?xml:namespace> Canadian chemical railcar loadings for the week ended on 20 November were 15,504, up from 13,334 in the same week last year, according to data released by the Association of American Railroads (AAR). The increase for the week came after a 19.2% year-over-year increase in Canadian chemical carloads in the previous week ended 13 November. The weekly chemical railcar loadings data are seen as an important real-time measure of chemical industry activity and demand. In For the year-to-date period to 20 November, Canadian chemical railcar shipments were up 23.1% to 668,892, from 543,390 in the same period in 2009. The association said that chemical railcar traffic in For the year-to-date period, Mexican shipments were down 1.8%, to 50,739, from 51,684 in the same period last year. Mexican railcar shipments were hindered by flooding in past weeks. The AAR reported earlier on Wednesday that Overall chemical railcar shipments for all of North America - US, For the year-to-date period to 20 November, overall North American chemical railcar traffic was up 13.3% to 2,047,877, from 1,807,297in the year-earlier period. Overall, the From the same week last year, total US weekly railcar traffic for the 19 carload commodity groups tracked by the AAR rose 3.9% to 297,990 from 286,902, and was up 7.2% to 13,207,976 year-to-date to 20 Nove
http://www.icis.com/Articles/2010/11/24/9413624/canadian-weekly-chemical-railcar-traffic-rises-16.3.html
CC-MAIN-2014-15
refinedweb
269
55.54
nanosleep - pause execution for a specified time #include <time.h> int nanosleep(const struct timespec *req, struct timespec *rem); nanosleep(2) 999 999 999. Compared to sleep(3) and usleep(3), nanosleep has the advantage of not affecting any signals, it is standardized by POSIX, it provides higher timing resolution, and it allows to continue a sleep that has been interrupted by a signal more easily. In case of an error or exception, the nanosleep system call returns -1 instead of 0 and sets errno to one of the following values:. POSIX.1b (formerly POSIX.4). sleep(3), usleep(3), sched_setscheduler(2), timer_create(2)? 5 pages link to nanosleep(2):
http://wiki.wlug.org.nz/nanosleep(2)
CC-MAIN-2015-27
refinedweb
110
65.73
Reversing. Python Node Class for Linked List Here is a simple Python Node Class we will be using to represent each node in the linked list. Each node in the linked list contains an integer as a value and a pointer to the next node. The __repr__ method is a bit different from my other tutorials as it only returns the value of the node. This is done to simplify unit testing. class Node(object): def __init__(self, value: int, next_node: "Node" = None): self.value = value self.next = next_node def __repr__(self): return self.value Custom Python LinkedList Class Typically the programming challenge provides a custom LinkedList Class with a member variable, called head, that points to the head node of the linked list. The class also contains an empty reverse method that needs to be completed by the developer. class LinkedList(object): def __init__(self, head: Node = None): self.head = head def reverse(self) -> None: # Write the Algorithm Reverse Linked List in Python Now let's code the algorithm to reverse the linked list in Python. First, if the linked list is empty, let's not go any further. We don't need to waste any cycles reversing an empty linked list. Next, we need to loop through the nodes in the linked list and modify their next pointers so that they point to the previous node in the current loop as opposed to the next node. To do this, we track 3 nodes as we iterate through the list: previous node, current node, and next node. We will stop looping when we have reached the last node in the linked list. When we have reached the last node in the linked list, we set it as the new head node and adjust its next pointer to point to the previous node. def reverse(self) -> None: if self.head is None: return previous_node = None current_node = self.head next_node = current_node.next while next_node is not None: current_node.next = previous_node previous_node = current_node current_node = next_node next_node = current_node.next self.head = current_node self.head.next = previous_node Unit Tests for Reversing Linked List Let's use Python's Unit Testing Framework to test the reverse method of the LinkedList Class. We will test it for an empty linked list, linked list with only 1 node, and a linked list with multiple node. Let's also test to make sure calling reverse on a linked list twice returns the original linked list. Here is a test case with the 4 unit tests. class LinkedListTests(unittest.TestCase): def test_empty_list(self): linked_list = LinkedList() linked_list.reverse() values = list(linked_list) self.assertListEqual(values, []) def test_one_node(self): linked_list = LinkedList(Node(1)) linked_list.reverse() values = list(linked_list) self.assertListEqual(values, [1]) def test_multiple_nodes(self): linked_list = LinkedList(Node(1, Node(2, Node(3, Node(4))))) linked_list.reverse() values = list(linked_list) self.assertListEqual(values, [4, 3, 2, 1]) def test_double_reversal(self): linked_list = LinkedList(Node(1, Node(2, Node(3, Node(4))))) linked_list.reverse() linked_list.reverse() values = list(linked_list) self.assertListEqual(values, [1, 2, 3, 4]) To make the testing easier, I coded an iterator for the LinkedList Class. The iterator allows us to call list(linked_list) to get a list of values in proper order in the linked list. We will compare that list of values to the expected list of values in our unit tests. def __iter__(self): current_node = self.head while current_node is not None: yield current_node.value current_node = current_node.next Of course, we also need to make sure we add import unittest to the top of the Python file. For convenience I also kick off the unit tests whenever someone runs the Python script. if __name__ == '__main__': unittest.main(verbosity=2) Running the unit tests will produce something like the following. $ python main.py test_double_reversal (__main__.LinkedListTests) ... ok test_empty_list (__main__.LinkedListTests) ... ok test_multiple_nodes (__main__.LinkedListTests) ... ok test_one_node (__main__.LinkedListTests) ... ok ---------------------------------------------------------------------- Ran 4 tests in 0.000s OK Process finished with exit code 0 Conclusion We covered a lot of concepts in this tutorial and wrote a fair amount of code. The algorithm for reversing a linked list is pretty simple once you understand how it works. The additional code we wrote to 1) create an iterator for the LinkList Class and 2) test the algorithm using the Python Unit Testing Framework was fun and useful. I hope this helps you when you come across this question during a technical job interview or programming challenge.
https://www.koderdojo.com/blog/reverse-a-linked-list-is-a-popular-technical-interview-question
CC-MAIN-2021-39
refinedweb
734
67.55
NAME pmLoadASCIINameSpace - establish a local PMNS for an application C SYNOPSIS #include <pcp/pmapi.h> int pmLoadASCIINameSpace(const char *filename, int dupok); cc ... -lpcp DESCRIPTION If the application wants to force using a local Performance Metrics Name Space (PMNS) instead of a distributed PMNS then it must load the PMNS using pmLoadASCIINameSpace or pmLoadNameSpace(3). If the application wants to use a distributed PMNS, then it should NOT make a call to load the PMNS explicitly.. The default local PMNS is found in the file $PCP_VAR_DIR/pmns/root unless the environment variable PMNS_DEFAULT is set, in which case the value is assumed to be the pathname to the file containing the default local PMNS. pmLoadASCIINameSpace returns zero on success. FILES $PCP_VAR_DIR/pmns/root the default local PMNS, when the environment variable PMNS_DEFAULT is unset ``Error Parsing ASCII PMNS: ...''. PM_ERR_DUPPMNS It is an error to try to load more than one PMNS, or to call either pmLoadASCIINameSpace and/or pmLoadNameSpace(3) more than once. PM_ERR_PMNS Syntax error in an ASCII format PMNS.
http://manpages.ubuntu.com/manpages/oneiric/man3/pmLoadASCIINameSpace.3.html
CC-MAIN-2015-18
refinedweb
171
53.31
A. Circuit Operation Q1, Q2 forms the initial differential amplifier stage which appropriately raises the 1vpp sine signal at its input to a level which becomes suitable for initiating the driver stage made up of Q3, Q4, Q5. This stage further raises the voltage such that it becomes sufficient for driving the mosfets. The mosfets are also formed in the push pull format, which effectively shuffles the entire 60 volts across the transformer windings 50 times per second such that the output of the transformer generates the intended 1000 watts AC at the mains level. Each pair is responsible for handling 100 watts of output, together all the 10 pairs dump 1000 watts into the transformer. For acquiring the intended pure sine wave output, a suitable sine input is required which is fulfilled with the help of a simple sine wave generator circuit. It is made up of a couple of opamps and a few other passive parts. It must be operated with voltages between 5 and 12. This voltage should be suitably derived from one of the batteries which are being incorporated for driving the inverter circuit. The inverter is driven with voltages of +/-60 volts that amounts to 120 V DC. This huge voltage level is obtained by putting 10 nos. of 12 volt batteries in series. The Sinewave Generator Circuit The below given diagram shows a simple sine wave generator circuit which may be used for driving the above inverter circuit, however since the output from this generator is exponential by nature, might cause a lot of heating of the mosfets. A better option would be to incorporate a PWM based circuit which would supply the above circuit with appropriately optimized PWM pulses equivalent to a standard sine signal. The PWM circuit utilizing the IC555 has also been referred in the next diagram, which may be used for triggering the above 1000 watt inverter circuit. Parts List for the sine generator circuit = 0-60V/1000 watts/output 110/220volts 50Hz/60Hz The proposed 1 kva inverter discussed in the above sections can be much streamlined and reduced in size as given in the following design: How to Connect Batteries The diagram also shows the method of connecting the battery, and the supply connections for the sine wave or the PWM oscillator stages. Here just four mosfets have been used which could be IRF4905 for the p-channel, and IRF2907 for n-channel. Complete 1 kva inverter circuit design with 50 Hz sine oscillator In the above section we have learned a full bridge design in which two batteries are involved for accomplishing the required 1kva output. Now let's investigate how a full bridge design could be constructed using 4 N channel mosfet and using a single battery. The following section shows how a full-bridge 1 KVA inverter circuit can be built using, without incorporating complicated high side driver networks or chips. Using Arduino The above explained 1kva sinewave inverter circuit can be also driven through an Arduino for achieving almost a prefect sinewave output. The complete Arduino based circuit diagram can be seen below: Program Code is given below: //code modified for improvement from //connect pin 9 -> 10k Ohm + (series with)100nF ceramic cap -> GND, tap the sinewave signal from the point at between the resistor and cap. float wav1[3];//0 frequency, 1 unscaled amplitude, 2 is final amplitude int average; const int Pin = 9; float time; float percentage; float templitude; float offset = 2.5; // default value 2.5 volt as operating range voltage is 0~5V float minOutputScale = 0.0; float maxOutputScale = 5.0; const int resolution = 1; //this determines the update speed. A lower number means a higher refresh rate. const float pi = 3.14159; void setup() { wav1[0] = 50; //frequency of the sine wave wav1[1] = 2.5; // 0V - 2.5V amplitude (Max amplitude + offset) value must not exceed the "maxOutputScale" TCCR1B = TCCR1B & 0b11111000 | 1;//set timer 1B (pin 9) to 31250khz pinMode(Pin, OUTPUT); //Serial.begin(115200);//this is for debugging } void loop() { time = micros()% 1000000; percentage = time / 1000000; templitude = sin(((percentage) * wav1[0]) * 2 * pi); wav1[2] = (templitude * wav1[1]) + offset; //shift the origin of sinewave with offset. average = mapf(wav1[2],minOutputScale,maxOutputScale,0,255); analogWrite(9, average);//set output "voltage" delayMicroseconds(resolution);//this is to give the micro time to set the "voltage" } // function to map float number with integer scale - courtesy of other developers. long mapf(float x, float in_min, float in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } The Full-Bridge Inverter Concept Driving a full bridge mosfet network having 4 N-channel mosfets is never easy, rather it calls for reasonably complex circuitry involving complex high side driver networks. If you study the following circuit which has been developed by me, you will discover that after all it's not that difficult to design such networks and can be done even with ordinary components. We will study the concept with the help of the shown circuit diagram which is in the form of a modified 1 kva inverter circuit employing 4 N-channel mosfets. As we all know, when 4 N-channel mosfets are involved in an H-bridge network, a bootstrapping network becomes imperative for driving the high side or the upper two mosfets whose drains are connected to the high side or the battery (+) or the positive of the given supply. In the proposed design, the bootstrapping network is formed with the help of six NOT gates and a few other passive components. The output of the NOT gates which are configured as buffers generate voltage twice that of the supply range, meaning if the supply is 12V, the NOT gate outputs generate around 22V. This stepped up voltage is applied to the gates of the high side mosfets via the emitter pinouts of two respective NPN transistors. Since these transistors must be switched in such a way that diagonally opposite mosfets conduct at a time while the the diagonally paired mosfets at the two arms of the bridge conduct alternately. This function is effectively handled by the sequential output high generator IC 4017, which is technically called Johnson divide by 10 counter/divider IC. The Bootstrapping Network The driving frequency for the above IC is derived from the bootstrapping network itself just to avoid the need of an external oscillator stage. The frequency of the bootstrapping network should be adjusted such that the output frequency of the transformer gets optimized to the required degree of 50 or 60 Hz, as per the required specs. While sequencing, the outputs of the IC 4017 trigger the connected mosfets appropriately producing the required push-pull effect on the attached transformer winding which activates the inverter functioning. The PNP transistor which can be witnessed attached with the NPN transistors make sure that the gate capacitance of the mosfets are effectively discharged in the course of the action for enabling efficient functioning of the entire system. The pinout connections to the mosfets can be altered and changed as per individual preferences, this might also require the involvement of the reset pin#15 connection. Waveform Images The above design was tested and verified by Mr. Robin Peter one of the avid hobbyists and contributor to this blog, the following waveform images were recorded by him during the testing process. 187 thoughts on “Make This 1KVA (1000 watts) Pure Sine Wave Inverter Circuit” Howdy, Friend! Interested to Learn Circuit Designing? Let's Start Discussing below! Need clarification for following points: 1. In comment section it was mentioned that 50% of AH should be multiplied by battery volts to obtain power output. Does it mean that if we use 48 V battery, then output by this inverter configuration is 2400 W (2.4 kW). 2.Since dual supply is used, does it imply that though 2 batteries are used, for power output considerations only one battery is considered. 3. For backup time calculations, whether only one battery should be accounted for or 2 1) Actually the maximum power output from a battery should the ideal discharge rate multiplied with its voltage. For a lead acid battery it’s voltage multiplied by 1/10 or 1/5 of its Ah value. If this is not maintained the battery can deteriorate very quickly. 2) Yes according to me since it’s a full bridge system the output power should be equivalent of both the batteries combined. 3) for backup only two battery parameter should be considered since they work alternately. can we multiply the mosfets by 3 yo obtain high power say 3000w? yes you can…. sir , please can you give me a link where i can found 1000kva square wave inverter because the one i build from other site is not working. i have 12v 1000watt centre tap transformer and 230v as the output , 12v 62ah battery just a diagram that can fit my specification i just want to start with square wave, although i have came across some of your pure sine wave inverter but i want to start with square wave . i hope my request will be put into consideration . thanks Youngking, you can use any square wave design, and modify it for getting 1kva output by appropriately upgrading its mosfets, transformer and battery for handling 1000 watts. Good day Mr Swagatam, pls can you show how to fix a relay on1kva using sg3525 so that when light comes it wil be automatically charging the battery. God bles you sir. Yusuf, you can use a simple relay driver stage using a transistor and a double contact relay, then connect the pair of center poles of the relay to the appliance, connect the pair of N/O contacts with the mains AC phase/neutral….and connect the pair of N/C contacts with the inverter mains phase/neutral. for the relay driver stage connect the emitter of the transistor with negative supply of a 12V adapter connected with mains AC, positive of the relay with the positive of the adapter output, and the base also with the positive of the adapter…the base resistor can be calculated from the following article: Hello friend, I am trying to make a 100W inverter with a 12V input to 120V output and was wondering what I need to change? Also, are there alternatives for the K1058 and J162 mosfets? Thanks! Hi, you won’t have to change anything in the design expect the number of mosfet which can be limited to just one pair, meaning just one pair of mosfet will be enough to give you the required results. You can use IRF540, IRF9540 mosfets Just recently i purchased an old computer UPS and the transformer had 2 wires on the low voltage side. On the circuit board there was an heat sink with four mosfets attached of the same number. Does it mean that this UPS provides a push pull effect to the 2-wire transformer connected using a full bridge circuit? The UPS was operated from one battery. yes it is using an H-bridge network for operating the two wire trafo in a push pull mode… What is the advantage of using dual supplies with respect to GND in this inverter circuit. Does it affect the output AC waveform? If we compare this circuit with other circuits in your blog that uses one battery to run an inverter, does it have any difference? since it is an audio amp circuit, it had to use a dual supply, because originally the loud speaker had to be operated in a push pull mode. When we are replacing the loud speaker with a trafo we are implementing the same concept, that is using a two wire trafo and achieving a push pull operation on it. Whenever a two wire push pull trafo is used in an inverter, the supply has to be dual, or the circuit has to be an full bridge or H-bridge topology employing 4 mosfets in tandem. if the above concept is to be avoided, a center-tap trafo will come into the picture Dear Sir Swagatam, Most people think circuit ground means negative pole of the battery. That is not true. I’ve seen many negative voltage regulators and can now understand that circuit GND and negative in certain cases can not be the same. When we say circuit Ground we refer to an electrical circuit where AC is involved. In DC circuits there is nothing called ground but still people call that as negative terminal of battery. This page shows the best example of a case where there is a separate positive and separate negative with respect to GND. The GND here is both positive and negative. So people here need to be much more careful as to how they do their battery connection to the inverter in this circuit. Let me first get this clarified from you. THANKS Hi Sherwin, In circuits operating with dual supplies where a separate negative is involved with reference to a ground then this ground becomes different and a critical thing to observe, but in single supplies where there’s no separate negative with reference to a ground then the negative terminal itself is considered as the ground. Therefore in DC circuits with single supply the negative is considered as ground which simply means a common zero voltage line. Such parameters are a matter of understanding and the users must be aware of these facts. SIR PLEASE EXAMPLE HOW CAN I DIMENSION THE MOSFET MAYBE FOR INSTANCE I HAVE A 1KVA TRANSFORMER WITH 12V 100AH BATTERY. NOW HOW DO I THEN KNOW HOW MANY MOSFET TO CASCADE PLS EXPLAIN Christian, check the datasheet of the selected mosfet and find out the Vds(Drain-Source Voltage) and Id(Continuous Drain Current) specs of the mosfet, multiplying them will give you absolute max power or wattage of the mosfet. So you can use this data to calculate how many mosfets you may require to achieve the required inverter wattage output safely. the above figures will be valid only when the mosfets are mounted on adequately large heatsinks. HOW DO WE DETERMINE THE POWER OF AN INVERTER IS IT BY THE AMOUNT OF MOSFET USED OR BY THE TRANFORMER Transformer and battery Ah. according to the above specs you can dimension the mosfets I av a square wave inverter using sg3524, pls help me with circuit Dat we convert it to sine wave you can apply the following concept Hello Sir, I’m still a student and I will do this circuit as my project. If I used 12V battery for this circuit, what will be the possible output? Hello Liezl, you can multiply 12V with 50% of the AH rating of the battery that will give the max power of the inverter…. Hi, I think you can study the concepts explains in the following article and make the design accordingly for your specific application I don't trust simulators therefore i cannot suggest about simulators…because they will mostly give you incorrect/misleading results unless you are an expert and exactly know how to handle them.. Hello Swagatam I want to make a Sine pulse width modulation Inverter which can control the speed of induction motor ..Ihave the 12 V Dc i want it to particular ac for the rating of 1KVA inverter so plz will u guide me which circuit will be the perfect and will i have to simulate it first if yes then which circuit i shall simulate will u plz provide me that circuut Hello Bhushan, Hi, I think you can study the concepts explained in the following article and make the design accordingly for your specific application I don't trust simulators therefore i cannot suggest about simulators…because they will mostly give you incorrect/misleading results unless you are an expert and exactly know how to handle them. I want full 1KVA UPS circuit diagram for simulation veniyan, where do you get your 220V DC from? remember DC in high voltage is lethal and can kill you instantly with AC you still have a chance to get away but not with DC.. My dear brother, I have a reflective capacity of 800 watts , but not enough to run my refrigerator 200 Watt and I want to increase their value to appropriate what is the solution?. Ill try the 3kva sine wave inverter that i see you posted ok probably Ill just try another design, I wanted to complete this but I dont know why I can get any output from the transformer. sure, there are many good designs in this blog, much effective and easier than the above design but will not produce pure sine wave… I got 12 volts accross gate and grounds of each fet…. I tried but still no volt out from the transformer the fets get hot remove the trafo and the input and then check if the fets are getting hot or not. Oops forgot to mention in the tricky challenge………it would be far better if a swich for sinewave,squarewave,traingle and sawtooth wave. if not at all possible,make it sinewave alongwith PAM/PWM/PPM controller……… sir plse can i use irf540n in place of irf2907? thank you. yes it can be used. thank you im going to try it if thats correct which voltage caps should I use.. in the parts list you have a "2µ2" value for C4, C6, C7 I cannot find such a value was that a typo? yes it's a typo from the previous extraction, just remove the  sir please can i use variable resistor to adjust so that i can get 14k3 or 12k1 cos it difficult to get that value can i? yes you can use presets for adjusting the values sir i want to try this circuit again but my problem is the 15pf i search every where but i don't get it, it very difficult daniel, you can try any closer value, it's not so critical please lm555 will produce the same sine wave as tlo72 oscillator? 555 will produce pwm modified pure sine wave, A1, A2 will produce exact pure sine wave how to we can 20 volt dc convert into the ac 220 volt please you can try the following circuit: Transformer = 60-0-60V/1000 watts/output 110/220volts 50Hz/60Hz what do mean 60-0-60? sorry, it should be 0-60V and not 60-0-60 it's the voltage rating of the primary side winding of the inverter transformer.. sir please in this circuit it Q8 AND Q9 N-channel or P-channel? P-channel. ok sir i understand you very well it a good i dear i will do exactly as you said.. …..than compared to two 24V batteries If possible I'll try to design it and post it for you soon That won't be enough, you will need a minimum 200 watt panel for charging a 200 AH battery within 6 hours, please confirm it further with your panel dealer Hi Kabir, 50 watt panel is too low to power an inverter directly, you will need at least a 100 watt solar panel for this. You can try a simple inverter circuit that's explained in the following article: The above circuit will work with 12V supply also, but with 12V supply a 1000 watt inverter will become too heavy with thick wires and huge heatsinks, that's why higher voltage is recommended. To make an UPS you will need to make a inverter first, so you can begin with the above circuit, once you finish this I'll help you to proceed with the further things.
https://www.homemade-circuits.com/make-this-1kva-1000-watts-pure-sine/
CC-MAIN-2019-22
refinedweb
3,297
54.46
Hope this is the correct forum and thanks in advance for reading this. Summary: I'm working on EC (electric conductivity) measurements using a capacitor and the pins of an ESP8266 microprocessor to create an AC current, and using that to measure the conductivity of an ionic solution. What I'm actually measuring is the discharge time of the capacitor, and out of that the electrical resistance is measured. Now when measuring low EC liquids, with long discharge times (long being 15-20 microseconds), the discharge time goes up disproportionally. The same effect I see at short discharge times (in the tune of <1 microsecond) but less strong, at least within the range I am measuring. Each EC probe requires three GPIO ports. One ESP8266 handles three EC probes. Source code of the sketch used at the bottom, see comments in the source for explanation how it works. I strongly believe the measurement method as such is correct - measurements are highly reproducible, and using a high frequency AC is the correct way to measure an ionic liquid. The problem most likely lies hidden inside the ESP8266 - I hope to find out what causes this error, and how to correct for it. The first clear observation is that the ports are not all equal. Of course there are some that have pull-up or pull-down resistors, and GPIO2 is connected to the internal LED, but there are more systemic differences between the ports. I get different discharge times for different groups of ports, but those times are consistent between my two prototypes so it's an ESP thing, not an external component thing. This chart shows the measured EC vs. the reciprocal discharge time - which is a direct measure of the conductivity (fixed C, so t relates to R in an RC circuit, and conductivity is 1/R). There are two boards, 126 and 127, each with three probes. Same software & schematic. There are three groups of two lines that are pretty much on top of one another. This shows the difference in behaviour of the GPIO ports. The capacitors used have a tolerance of 5%. EC should be linear to the square root of the concentration; at diluted solutions like what I use it can be well approximated by making it linear to the concentration itself. This is what I did. Then with the regression results I calculated the measurement error of each point (calculate expected value using the slope/intersect, compare with measured value). This is the result in errors: Again three groups of two lines: the errors are highly consistent between the two boards. This makes me believe there is some kind of systemic error, which should be accounted for - but what could this error possibly be? Source code - relevant parts only (this won't run as is). // Pin connections. #define WIFILED 2 // Indicator LED - on when WiFi is connected. // EC1, capPos: GPIO 12 // EC1, capNeg: GPIO 14 // EC1, ECPin: GPIO 16 // EC2, capPos: GPIO 0 // EC2, capNeg: GPIO 4 // EC2, ECPin: GPIO 13 // EC3, capPos: GPIO 5 // EC3, capNeg: GPIO 1 // EC3, ECPin: GPIO 15 // TX = 1, RX = 3. #if SERIAL // don't try to use the third probe as it messes up the Serial interface. int capPos[] = {12, 0}; // CapPos/C+ for EC probes. int capNeg[] = {16, 4}; // CapNeg/C- for EC probes. int ECpin[] = {14, 13}; // ECpin/EC for EC probes. #define NPROBES 2 #else int capPos[] = {12, 0, 5}; // CapPos/C+ for EC probes. int capNeg[] = {16, 4, 1}; // CapNeg/C- for EC probes. int ECpin[] = {14, 13, 15}; // ECpin/EC for EC probes. #define NPROBES 3 #endif int interruptPin; // stores which pin is used to connect the EC interrupt. // EC probe data #define CYCLETIME 12.5 // the time it takes in nanoseconds to complete one CPU cycle (12.5 ns on a 80 MHz processor) unsigned long startCycle; unsigned long endCycle; float EC[3] = {-1, -1, -1}; // the array in which to store the EC readings. // GPIO registers for EC probing - this is ESP8266 specific. #define GPIO_SET_OUTPUT_HIGH PERIPHS_GPIO_BASEADDR + 4 #define GPIO_SET_OUTPUT_LOW PERIPHS_GPIO_BASEADDR + 8 #define GPIO_SET_OUTPUT PERIPHS_GPIO_BASEADDR + 16 #define GPIO_SET_INPUT PERIPHS_GPIO_BASEADDR + 20 /** * capacitor based TDS measurement * pin CapPos ----- 330 ohm resistor ----|------------| * | | * cap EC probe or * | resistor (for simulation) * pin CapNeg ---------------------------| | * | * pin ECpin ------ 180 ohm resistor -----------------| * * So, what's going on here? * EC - electic conductivity - is the reciprocal of the resistance of the liquid. * So we have to measure the resistance, but this can not be done directly as running * a DC current through an ionic liquid just doesn't work, as we get electrolysis and * the migration of ions to the respective electrodes. * * So this routing is using the pins of the NodeMCU and a capacitor to produce a * high frequency AC current (1 kHz or more - based on the pulse length, but the * pulses come at intervals). Alternating the direction of the current in these * short pulses prevents the problems mentioned above. * * Then to get the resistance it is not possible to measure the voltage over the * EC probe (the normal way of measuring electrical resistance) as this drops with * the capacitor discharging. Instead we measure the time it takes for the cap to * discharge enough for the voltage on the pin to drop so much, that the input * flips from High to Low state. This time taken is a direct measure of the * resistance encountered (the cap and the EC probe form an RC circuit) in the * system, and that's what we need to know. * * Now the working of this technique. * Stage 1: charge the cap full through pin CapPos. * Stage 2: let the cap drain through the EC probe, measure the time it takes from * flipping the pins until CapPos drops LOW. * Stage 3: charge the cap full with opposite charge. * Stage 4: let the cap drain through the EC probe, for the same period of time as * was measured in Stage 2 (as compensation). * Cap is a small capacitor, in this system we use 47 nF but with other probes a * larger or smaller value can be required (the original research this is based * upon used a 3.3 nF cap). The 330R resistor is there to protect pin CapPos and * CapNeg from being overloaded when the cap is charged up, the 180R resistor * protects ECpin from too high currents caused by very high EC or shorting the * probe. * * Pins set to input are assumed to have infinite impedance, leaking is not taken into * account. The specs of NodeMCU give some 66 MOhm for impedance, several orders of * magnitude above the typical 1-100 kOhm resistance encountered by the EC probe. * * This function uses delay() in various forms, no yield() or so as it's meant to * be a real time measurement. Yield()ing to the task scheduler is a bad idea. * With the measurement taking only just over 0.1 seconds this should not be an * issue. * * Original research this is based upon: * * */ void getEC() { int samples = 100; // number of EC samples to take and average. unsigned long startTime; // the time stamp (in microseconds) the measurement starts. unsigned long endTime; // the time stamp (in microseconds) the measurement is finished. unsigned int dischargeTime; // the time it took for the capacitor to discharge. unsigned int chargeDelay = 100; // The time (in microseconds) given to the cap to fully charge/discharge - at least 5x RC. unsigned int timeout = 2; // discharge timeout in milliseconds - if not triggered within this time, the EC probe is probably not there. delay(1); for (int j=0; j<NPROBES; j++) { interruptPin = capPos[j]; int pinECpin = ECpin[j]; int pincapPos = capPos[j]; int pincapNeg = capNeg[j]; Average<unsigned int> discharge(samples); // The sampling results. if (LOGGING) writeLog("Probing EC probe " + String(j+1) + " on capPos pin " + String (pincapPos) + ", capNeg pin " + String (pincapNeg) + ", ECpin " + String (pinECpin) + "."); for (int i=0; i<samples; i++) { // take <samples> measurements of the EC. // Stage 1: fully charge capacitor for positive cycle. // CapPos output high, CapNeg output low, ECpin input. pinMode (pinECpin, INPUT); pinMode (pincapPos,OUTPUT); pinMode (pincapNeg, OUTPUT); WRITE_PERI_REG (GPIO_SET_OUTPUT_HIGH, (1<<pincapPos)); WRITE_PERI_REG (GPIO_SET_OUTPUT_LOW, (1<<pincapNeg)); delayMicroseconds(chargeDelay); // allow the cap to charge fully. yield(); // Stage 2: positive side discharge; measure time it takes. // CapPos input, CapNeg output low, ECpin output low. endCycle = 0; startTime = millis(); pinMode (pincapPos,INPUT); attachInterrupt(digitalPinToInterrupt(interruptPin), capDischarged, FALLING); WRITE_PERI_REG (GPIO_SET_OUTPUT_LOW, (1<<pinECpin)); pinMode (pinECpin, OUTPUT); // Use cycle counts and an interrupt to get a much more precise time measurement, especially for high-EC situations. startCycle = ESP.getCycleCount(); while (endCycle == 0) { if (millis() > (startTime + timeout)) break; yield(); } detachInterrupt(digitalPinToInterrupt(pincapPos)); if (endCycle == 0) dischargeTime = 0; else { // Handle potential overflow of micros() just as we measure, this happens about every 54 seconds // on a 80-MHz board. if (endCycle < startCycle) dischargeTime = (4294967295 - startCycle + endCycle) * CYCLETIME; else dischargeTime = (endCycle - startCycle) * CYCLETIME; discharge.push(dischargeTime); if (LOGGING) writeLog ("sampled dischargeTime: " + String(dischargeTime)); } yield(); // Stage 3: fully charge capacitor for negative cycle. CapPos output low, CapNeg output high, ECpin input. WRITE_PERI_REG (GPIO_SET_OUTPUT_HIGH, (1<<pincapNeg)); WRITE_PERI_REG (GPIO_SET_OUTPUT_LOW, (1<<pincapPos)); pinMode (pinECpin, INPUT); pinMode (pincapPos,OUTPUT); pinMode (pincapNeg, OUTPUT); delayMicroseconds(chargeDelay); yield(); // Stage 4: negative side charge; don't measure as we just want to balance it the directions. // CapPos input, CapNeg high, ECpin high. WRITE_PERI_REG (GPIO_SET_OUTPUT_HIGH, (1<<pinECpin)); pinMode (pincapPos,INPUT); pinMode (pinECpin, OUTPUT); delayMicroseconds(dischargeTime/1000); yield(); } // Stop any charge from flowing while we're not measuring by setting all ports to OUTPUT, LOW. // This will of course also completely discharge the capacitor. pinMode (pincapPos, OUTPUT); digitalWrite (pincapPos, LOW); pinMode (pincapNeg, OUTPUT); digitalWrite (pincapNeg, LOW); pinMode (pinECpin, OUTPUT); digitalWrite (pinECpin, LOW); yield(); float dischargeAverage = discharge.mean(); if(LOGGING) writeLog("Discharge time probe " + String(j) + ": " + String(dischargeAverage) + " ns."); /** * Calculate EC from the discharge time. * * Discharge time is directly related to R x C. * Here we have a discharge time, as we have a fixed capacitor this discharge time is linearly? related * to the resistance we try to measure. * Now we don't care about the actual resistance value - what we care about is the EC and TDS values. The * EC is the reciprocal of the resistance, the TDS is a function of EC. The capacitor is fixed, so the actual * value is irrelevant(!) for the calculation as this is represented in the calibration factor. * * As ion activity changes drastically with the temperature of the liquid, we have to correct for that. The * temperature correction is a simple "linear correction", typical value for this ALPHA factor is 2%/degC. * * Source and more information: * * * Port D8 of NodeMCU leaks charge, this has to be accounted for using the INF time factor. This port should be * avoided later. */ #ifdef USE_NTC // Calculate corrected time. if (dischargeAverage > 0) { float t = dischargeAverage - ZERO[j]; if (INF[j] > 0) t /= 1-dischargeAverage/INF[j]; EC[j] = ECSLOPE[j] / (dischargeAverage * (1 + ALPHA * (watertemp - 25))) + ECOFFSET[j]; } else { EC[j] = -1; } #else EC[j] = dischargeAverage; #endif } } // Upon interrupt: register the cycle count of when the cap has discharged. void capDischarged() { endCycle = ESP.getCycleCount(); detachInterrupt(digitalPinToInterrupt(interruptPin)); }
https://www.queryxchange.com/q/26_302096/water-conductivity-measurements-esp8266-getting-strange-results/
CC-MAIN-2019-43
refinedweb
1,825
54.22
Introduction This blog post is for the two other people in the world that might be remotely interested in rasters/arrays and dimensionality as it can be applied to reshaping for subsequent analysis. The topic was introduced in my previous blog about block statistics. I am gently warming the readers (both of you) to moving/sliding window functions and how they work on a mechanical level. The code below is for the record. This is one incarnation of what is out there on the web. Most of the comments and posts deal with the 'speed' and efficacy of determining what you will see. In my opinion, those discussions don't matter... I have only needed primes and combinations and permutations once outside of an academic environment. I will rely on this code should the need arise again. So here it is with an output example. Nerd Note: As of worlds largest prime as of this date, , the worlds largest prime is ... 274207281-1 .... or 22,338,618 digits the number is called M74207281 which is the 49th Mersenne Prime discovered. In the next post, I will use this foundation to provide more background on working with block and moving window operations. """ Script: primes_combos_demo.py Author: Dan.Patterson@carleton.ca Purpose: Long forgotten, but it is done. """ import numpy as np import itertools def primes(n): '''Returns a array of primes, p < n- all-primes-below-n-in-python/3035188#3035188 ''' assert n>=2 sieve = np.ones(n/2, dtype=np.bool) for i in range(3,int(n**0.5)+1,2): if sieve[i/2]: sieve[i*i/2::i] = False p_num = np.r_[2, 2*np.nonzero(sieve)[0][1::]+1] return p_num def divisor(n, prn=False): """Determine the divisors, products, cumulative products and divisors given a set of primes < n """ p_vals = primes(n) divs = [p for p in p_vals if (n % p == 0)] cump = np.cumproduct(divs).tolist() divs = divs + cump prods = list(set(i*j for i in divs for j in divs)) all_div = list(set(divs+prods)) all_div.sort() if prn: print("all",all_div) return all_div def perm_sums(n,max_dim=3): """Determine the permutations that sum to n for an array of given size. A verbose workflow follows... """ ##divs, subs, prods = divisor(n) perms = divisor(n) p =[] for i in range(1,max_dim+1): p.append(list(itertools.product(perms, repeat=i))) combos = [] for i in range(len(p)): vals = [v for v in p[i] if np.product(v)==n ] combos.extend(vals) #.append(vals) perms = np.array(perms) ppp = np.product(perms,axis=-1) wh = np.where(ppp == n) perm_vals = perms[wh] return combos def demo(n=36, prn=True): """ demo perm_sums""" p = primes(n) print("\nPrimes:...{}".format(p)) all_div = divisor(n) print("Number:...{}\nAll:...{}".format(n, all_div)) ndim = 4 combos = perm_sums(n, max_dim=ndim) if prn: print("\nProducts for... {} - max_dim = {}".format(n, ndim)) for i in combos: print(i) return combos if __name__=="__main__": """primes demo""" n = 36 combos = demo(n, prn=True) For the example in my last post for a 6x6 array for 36 unique numbers, these list the possible ways that that data can be reconfigure. If you specify a minimum window size you can get possible combinations. Minimum window...[3, 3] [(3, 12), (4, 9), (6, 6), (9, 4), (12, 3), (2, 3, 6), (2, 6, 3), (3, 3, 4), (3, 4, 3), (4, 3, 3), (2, 2, 3, 3)] That's all for now. The cases of being able to reshape a raster in 1, 2, 3 or 4 dimensions are given above. Me and Xander?
https://community.esri.com/blogs/dan_patterson/2016/01/21/rasters-and-arrays-backgrounder-on-shapes-and-dimensions
CC-MAIN-2020-10
refinedweb
600
57.37
This article explains how my class CDXSurfaceMgr can be used to facilitate Double Buffered drawing/graphics. Normally when drawing using the GDI you do all your painting straight into the HDC that's provided by either BeginPaint or a CDC (if you are using MFC). Iif you draw a line it immediately appears on the surface of the window you are drawing on. If you draw a lot of graphic items the screen is updated with each item and this can result in flicker or stuttering as the surface is filled with the drawing. Double Buffering can be used to create smooth updates, you build a "frame" of graphics in a non visible place first then copy the whole thing onto the main windows surface. There a lots of ways to implement double buffering, one way is to create a compatible HDC in memory somewhere and draw into that then Blit (copy) that memory into the visible windows HDC. My approach uses a subset of DirectX called DirectDraw which can be used to draw 2d Graphics. CDXSurfaceMgr is written using the DirectDraw interfaces supplied in VC6 (ddraw.h/lib) and should work on 95/98/Me/2k/XP and NT 4.0 (sp3 - I think). CDXSurfaceMgr Create an instance of CDXSurfaceMgr #include "DXSurfaceMgr.h" ... ... CDXSurfaceManager_NBP dxMgr_;Initialise the instance like so int CMfcdxView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; // Initialise CDXSurfaceMgr if(!dxMgr_.Initialise(m_hWnd)) return -1; return 0; }This should be done just once, the parameter to the Initialisemethod is the Handle to the window you want to draw on. Then when handling the WM_PAINTmessage (the place you would normally do the drawing) call the BeginPaintMethod void CMfcdxView::OnDraw(CDC* pDC) { CMfcdxDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here HDC& hdc = dxMgr_.BeginPaint(GetSysColor(COLOR_3DFACE)); if(NULL !=hdc) { .... The parameter to BeginPaint is a COLORREF that BeginPaint will use to fill the background with. BeginPaint returns an HDC that that you can then use to draw things with, either via the standard GDI API; ::SetBkMode(hdc,TRANSPARENT); ::TextOut(hdc,10,10,"Please don't call me reg its not my name", 40);Or if you are using MFC; CDC* cdc = CDC::FromHandle(hdc); cdc->SetBkMode(TRANSPARENT); cdc->(10,10, CString("All aboard Brendas iron sledge")); Note all the usual GDI rules apply - if you select a brush remember to reselect the old one etc. When you have finished drawing, call the EndPaint method like so; dxMgr_.EndPaint(); This will "flip" your drawing onto the main windows surface. and the drawing will instantaneously appear. CDXSurfaceMgrdoes CDXSurfaceMgr creates a primary surface - one that is visible - and a secondary off screen surface that is the same size as the primary one but invisible. When you call BeginPaint an HDC attached to the secondary surface is returned; you do all your drawing into this; then EndPaint Blits(copies) the whole of the secondary surface onto the primary one and it appears on the window. If you have a capable graphics adapter on your machine then the Blit is very very fast, if you don't then the operation is obviously not as fast, but still very functional. There are three demos included one that uses WFC and draws rectangles and ellipses moving up and down the screen, one that uses MFC, and draws a few lines and a bit of text, and one that does exactly the same again but is just a Win32 program. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/directx/dxsurfacemgr.aspx
crawl-002
refinedweb
588
56.89
Zip not supported? Is the "zip" function not supported in Drawbot? Seems to work in Sublime. it seems to be working just fine: L1 = ['a', 'b', 'c'] L2 = ['one', 'two', 'three'] for items in zip(L1, L2): print(items) maybe you’re confused about py2 vs. py3 behavior? - in py2 zipreturns a list - in py3 zipreturns a zipobject you can use list()to convert a zip iterator into a list: print(zip(L1, L2)) print(list(zip(L1, L2))) @bic to make sure which version of Python you are running: import sys print(sys.version) in SublimeText3 you can set the Python version in Tools > Build System. handling of unicode changed radically from py2 to py3. see: hope this helps!
https://forum.drawbot.com/topic/103/zip-not-supported/3
CC-MAIN-2019-13
refinedweb
120
83.05
]], which will emit an IncomingConnection element for each new connection that the Server should handle: val binding: Future[ServerBinding] = Tcp().bind("127.0.0.1", 8888).to(Sink.ignore).run() binding.map { b => b.unbind() onComplete { case _ => // ... } } Next, we simply handle each incoming connection using a Flow which will be used as the processing stage to handle and emit ByteString s from and to the TCP Socket. Since one ByteString does not have to necessarily correspond to exactly one line of text (the client might be sending the line in chunks) we use the Framing.delimiter helper Flow to chunk the inputs up into actual lines of text. The last boolean argument indicates that we require an explicit line ending even for the last message before the connection is closed. In this example we simply add exclamation marks to each incoming text message and push it through the flow: and its upstream to a) connection.join(repl).run() The repl flow we use to handle the server interaction first prints the servers response, then awaits on input from the command line (this blocking call is used here just for the sake of simplicity) and converts it to a ByteString which is then sent over the wire to the server. Then we simply connect the TCP pipeline to this processing stage simply send an initial message. Note: connections.runFore: import akka.stream.scaladsl._ val file = Paths.get("example.csv") val foreach: Future[IOResult] = FileIO.fromPath(file) .to(Sink.ignore) .run().blocking-io-dispatcher, or for a specific stage by specifying a custom Dispatcher in code, like this: FileIO.fromPath(file) .withAttributes(ActorAttributes.dispatcher("custom-blocking-io-dispatcher")) Contents
http://doc.akka.io/docs/akka/2.4/scala/stream/stream-io.html
CC-MAIN-2017-13
refinedweb
279
54.12
fn: A functional web handlers are just plain functions that return IO and parameters are typed arguments. #!/usr/bin/env stack -- stack --resolver lts-3.10 --install-ghc runghc --package fn {-# LANGUAGE OverloadedStrings #-} import Data.Monoid ((<>)) import Data.Text (Text) import Network.Wai (Request, defaultRequest, Response) import Network.Wai.Handler.Warp (run) import Web.Fn data Ctxt = Ctxt { _req :: Request } instance RequestContext Ctxt where getRequest = _req setRequest c r = c { _req = r } initializer :: IO Ctxt initializer = return (Ctxt default= helloor /echo/hello" echoH :: Ctxt -> Text -> IO (Maybe Response) echoH _ msg = okText $ "Echoing '" <> msg <> "'." Provided you have stack installed, you can run this example like a shell script.indicates, and has no Fn monad (necessary context, as well as parameters, are passed as arguments, and the return value, which is plain-old IO, specifies whether routing should continue on). Properties Modules Downloads - fn-0.1.4.0.tar.gz [browse] (Cabal source package) - Package description (as included in the package) Maintainer's Corner For package maintainers and hackage trustees
http://hackage.haskell.org/package/fn-0.1.4.0/candidate
CC-MAIN-2022-40
refinedweb
169
50.53
16224/sending-coap-requests-using-python Just like sending an HTTP request, can I also send CoAP requests with Python? Although I got a lot of errors, this is how I tried to do it first: rec = reuest.get(coap://localhost:5683/other/block) Is there another way? Or am I missing something? It can be done using a library like CoAPython as your CoAP client: from coapthon.client.helperclient import HelperClient client = HelperClient(server=('127.0.0.1', 5683)) response = client.get('other/block') client.stop() 'response' is an instance of the type Response and its available methods are listed in the documentation, which you'll need to build. Whatever you need to do with the response, just use the documentation to figure out its methods and get the desired results. The thing is that IoT Hub is not ...READ MORE So, you can send 234212441325454543595674859764 in ASCII, ...READ MORE Hey, it turns out that the IBM ...READ MORE You need to start an HTTP server ...READ MORE suppose you have a string with a ...READ MORE if you google it you can find. ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE can you give an example using a ...READ MORE You can use a library like CoAPython ...READ MORE Well, I think there are some \r ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/16224/sending-coap-requests-using-python?show=16225
CC-MAIN-2019-43
refinedweb
231
86.81
#include <SFML/System.hpp> // Unsure which one contains sf::Music #include <SFML/Graphics.hpp> // Unsure which one contains sf::Music #include <SFML/Window.hpp> // Unsure which one contains sf::Music int main() { sf::Music WhatEverName; return 0; } it says Process returned - 2147418113 <0x000FFFF> exe... time... 0.154 sec I tried to find mistake but i am unaware whats going on wrong? Did i forget to init something, or do i need to clear/delete the music somehow? why is the return not 0!? EDIT:: Only thing i found is that this error only happens on Win Xp SP3, i am running win7 Edited by BaneTrapper, 29 September 2012 - 03:01 PM.
http://www.gamedev.net/topic/632038-sfml-music-giving-error/
CC-MAIN-2015-18
refinedweb
111
65.73
Recently I started learning python and just about to know more about list and tuple in python. I am a little bit known to the list and tuple and I can add or subtracts elements in a list. I wonder how to multiply all elements in a list python? I tried it in the adding process but it didn’t work for me. Is it doable?Could anybody please show me the way to do it? Yes! Multiplication of all elements in a list of python is doable. You can multiply the elements in a couple of ways. I am trying to make it easier that you can understand the program real quick. Method 1: Traversal def multiList(numList) : value = 1 for n in numList: value = value * n return value list1 = [1, 2, 3] list2 = [3, 4, 5] print(multiList(list1)) print(multiList(list2)) Method 2: Using numpy.prod() import numpy list1 = [1, 2, 3] list2 = [3, 4, 5] value1 = numpy.prod(list1) value2 = numpy.prod(list2) print(value1) print(value2) Both of the case will produce an output: 6 60 Thanks
https://kodlogs.com/38174/how-to-multiply-all-elements-in-a-list-python
CC-MAIN-2021-21
refinedweb
182
75.3
Getting Started with JavaFX 4. Figure 4-1 Login User Interface Description of "Figure 4-1 Login User Interface" This tutorial uses NetBeans IDE. Ensure that the version of NetBeans IDE that you are using supports JavaFX 2.2. See the System Requirements for details. Set Up the Project Your first task is to set up a JavaFX FXML project in NetBeans IDE: From the File menu, choose New Project. In the JavaFX application category, choose JavaFX FXML Application. Click Next. Name the project FXMLExample and click Finish. NetBeans IDE opens an FXML project that includes the code for a basic Hello World application. The application includes three files: FXMLExample.java. This file takes care of the standard Java code required for an FXML application. Sample.fxml. This is the FXML source file in which you define the user interface. SampleController.java. This is the controller file for handling the mouse and keyboard input. Rename SampleController.java to FXMLExampleController.java so that the name is more meaningful for this application. In the Projects window, right-click SampleController.java and choose Refactor then Rename. Enter FXMLExampleController, and click Refactor. Rename Sample.fxml to fxml_example.fxml. Right-click Sample.fxml and choose Rename. Enter fxml_example and click OK. Load the FXML Source File The first file you edit is the FXMLExample.java file. This file includes the code for setting up the application main class and for defining the stage and scene. More specific to FXML, the file uses the FXMLLoader class, which is responsible for loading the FXML source file and returning the resulting object graph. Make the changes shown in bold in Example 4-1. Example 4-1 FXMLExample.java @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml")); Scene scene = new Scene(root, 300, 275); stage.setTitle("FXML Welcome"); stage.setScene(scene); stage.show(); } A good practice is to set the height and width of the scene when you create it, in this case 300 by 275; otherwise the scene defaults to the minimum size needed to display its contents. Modify the Import Statements Next, edit the fxml_example.fxml file. This file specifies the user interface that is displayed when the application starts. The first task is to modify the import statements so your code looks like Example 4-2. Example 4-2 XML Declaration and Import Statements <?xml version="1.0" encoding="UTF-8"?> <?import java.net.*?> <?import javafx.geometry.*?> <?import javafx.scene.control.*?> <?import javafx.scene.layout.*?> <?import javafx.scene.text.*?> As in Java, class names can be fully qualified (including the package name), or they can be imported using the import statement, as shown in Example 4-2. If you prefer, you can use specific import statements that refer to classes. Create a GridPane Layout The Hello World application generated by NetBeans uses an AnchorPane layout. For the login form, you will use a GridPane layout because it enables you to create a flexible grid of rows and columns in which to lay out controls. Remove the AnchorPane layout and its children and replace it with the GridPane layout in Example 4-3. Example 4-3 GridPane Layout <GridPane fx: <padding><Insets top="25" right="25" bottom="10" left="25"/></padding> </GridPane> In this application, the GridPane layout is the root element of the FXML document and as such has two attributes. The fx:controller attribute is required when you specify controller-based event handlers in your markup. The xmlns:fx attribute is always required and specifies the fx namespace. The remainder of the code controls the alignment and spacing of the grid pane. The alignment property changes the default position of the grid from the top left of the scene to the center. The gap properties manage the spacing between the rows and columns, while the padding property manages the space around the edges of the grid pane. As the window is resized, the nodes within the grid pane are resized according to their layout constraints. In this example, the grid remains in the center when you grow or shrink the window. The padding properties ensure there is a padding around the grid when you make the window smaller. Add Text and Password Fields Looking back at Figure 4-1, you can see that the login form requires the title “Welcome” and text and password fields for gathering information from the user. The code in Example 4-4 is part of the GridPane layout and must be placed above the </GridPane> statement. Example 4-4 Text, Label, TextField, and Password Field Controls <Text text="Welcome" GridPane. <Label text="User Name:" GridPane. <TextField GridPane. <Label text="Password:" GridPane. <PasswordField fx: The first line creates a Text object and sets its text value to Welcome. The GridPane.columnIndex and GridPane.rowIndex attributes correspond to the placement of the Text control in the grid. The numbering for rows and columns in the grid starts at zero, and the location of the Text control is set to (0,0), meaning it is in the first column of the first row. The GridPane.columnSpan attribute is set to 2, making the Welcome title span two columns in the grid. You will need this extra width later in the tutorial when you add a style sheet to increase the font size of the text to 32 points. The next lines create a Label object with text User Name at column 0, row 1 and a TextField object to the right of it at column 1, row 1. Another Label and PasswordField object are created and added to the grid in a similar fashion. When working with a grid layout, you can display the grid lines, which is useful for debugging purposes. In this case, set the gridLinesVisible property to true by adding the statement <gridLinesVisible>true</gridLinesVisible> right after the <padding></padding> statement. Then, when you run the application, you see the lines for the grid columns and rows as well as the gap properties, as shown in Figure 4-2. Figure 4-2 Login Form with Grid Lines Description of "Figure 4-2 Login Form with Grid Lines" Add a Button and Text The final two controls required for the application are a Button control for submitting the data and a Text control for displaying a message when the user presses the button. The code is in Example 4-5. Add this code before </GridPane>. Example 4-5 HBox, Button, and Text "/> An HBox pane is needed to set an alignment for the button that is different from the default alignment applied to the other controls in the GridPane layout. The alignment property is set to bottom_right, which positions a node at the bottom of the space vertically and at the right edge of the space horizontally. The HBox pane is added to the grid in column 1, row 4. The HBox pane has one child, a Button with text property set to onAction property set to handleSubmitButtonAction(). While FXML is a convenient way to define the structure of an application's user interface, it does not provide a way to implement an application's behavior. You implement the behavior for the handleSubmitButtonAction() method in Java code in the next section of this tutorial, Add Code to Handle an Event. Assigning an fx:id value to an element, as shown in the code for the Text control, creates a variable in the document's namespace, which you can refer to from elsewhere in the code. While not required, defining a controller field helps clarify how the controller and markup are associated. Add Code to Handle an Event Now make the Text control display a message when the user presses the button. You do this in the FXMLExampleController.java file. Delete the code that NetBeans IDE generated and replace it with the code in Example 4-6. Example 4-6 FXMLExampleController.java package fxmlexample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.text.Text; public class FXMLExampleController { @FXML private Text actiontarget; @FXML protected void handleSubmitButtonAction(ActionEvent event) { actiontarget.setText("Sign in button pressed"); } } The @FXML annotation is used to tag nonpublic controller member fields and handler methods for use by FXML markup. The handleSubmtButtonAction method sets the actiontarget variable to You can run the application now to see the complete user interface. Figure 4-3 shows the results when you type text in the two fields and click the Sign in button. If you have any problems, then you can compare your code against the FXMLLogin example. Figure 4-3 FXML Login Window Description of "Figure 4-3 FXML Login Window" Use a Scripting Language to Handle Events As an alternative to using Java code to create an event handler, you can create the handler with any language that provides a JSR 223-compatible scripting engine. Such languages include JavaScript, Groovy, Jython, and Clojure. Optionally, you can try using JavaScript now. In the file fxml_example.fxml, add the JavaScript declaration after the XML doctype declaration. <?language javascript?> In the Buttonmarkup, change the name of the function so the call looks as follows: onAction="handleSubmitButtonAction(event);" Remove the fx:controllerattribute from the GridPanemarkup and add the JavaScript function in a <script>tag directly under it, as shown in Example 4-7. Example 4-7 JavaScript in FXML <GridPane xmlns: <fx:script> function handleSubmitButtonAction() { actiontarget.setText("Calling the JavaScript"); } </fx:script> Alternatively, you can put the JavaScript functions in an external file (such as fxml_example.js) and include the script like this: <fx:script The result is in Figure 4-4. Figure 4-4 Login Application Using JavaScript Description of "Figure 4-4 Login Application Using JavaScript" If you are considering using a scripting language with FXML, then note that an IDE might not support stepping through script code during debugging. Style the Application with CSS The final task is to make the login application look attractive by adding a Cascading Style Sheet (CSS). Create a style sheet. In the Project window, right-click the login folder under Source Packages and choose New, then Other. In the New File dialog box, choose Other, then Cascading Style Sheet and click Next. Enter Login and click Finish. Copy the contents of the Login.cssfile attached to this document into your CSS file. For a description of the classes in the CSS file, see Fancy Forms with JavaFX CSS. Download the gray, linen-like image for the background in the background.jpgfile and add it to the fxmlexample folder. Open the fxml_example.fxmlfile and add a stylesheets element before the end of the markup for the GridPanelayout as shown in Example 4-8. The @ symbol before the name of the style sheet in the URL indicates that the style sheet is in the same directory as the FXML file. To use the root style for the grid pane, add a style class to the markup for the GridPanelayout as shown in Example 4-9. Create a welcome-textID for the Welcome Textobject so it uses the style #welcome-textdefined in the CSS file, as shown in Example 4-10. Run the application. Figure 4-5 shows the stylized application. Figure 4-5 Stylized Login Application Description of "Figure 4-5 Stylized Login Application" For information about how to run your application outside NetBeans IDE, see Deploying Your First JavaFX Application. Where to Go from Here Now that you are familiar with FXML, look at Introduction to FXML, which provides more information on the elements that make up the FXML language. The document is included in the javafx.fxml package in the API documentation at. You can also try out the JavaFX Scene Builder tool by opening the fxml_example.fxml file in Scene Builder and making modifications. This tool provides a visual layout environment for designing the UI for JavaFX applications and automatically generates the FXML code for the layout. Note that the FXML file might be reformatted when saved. See Getting Started with JavaFX Scene Builder for more information on this tool. The Skinning with CSS and CSS Analyzer section of the JavaFX Scene Builder User Guide also give you information on how you can skin your FXML layout.
http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm
CC-MAIN-2015-11
refinedweb
2,033
55.74
Implementing that that was after most mixin-using Python code was designed. Here’s how you would mix in classes with foo and bar methods the old-fashioned way: class FooMixin(object): def foo(self): pass class BarMixin(object): def bar(self): pass class FooBar(FooMixin, BarMixin): pass You then have to deal with the complexities of multiple inheritance. Some have even argued that this should be considered harmful. Here’s a better way to do it. You use class decorators, which are simply functions that take a class and return a class. We don’t want the decorator to affect the behavior of other instances, so we return a subclass instead of monkey patching the class itself. To give the subclass the same name as the class that was passed in, we use a type constructor to create it. def add_foo(klass): def foo(self): pass return type(klass.__name__, (klass,), {'foo': foo}) def add_bar(klass): def bar(self): pass return type(klass.__name__, (klass,), {'bar': bar}) @add_foo @add_bar class FooBar(object): pass Now you’re only dealing with single inheritance. You have a class, FooBar, with foo and bar methods. You have a clear method resolution order (check with inspect.mro) leading from a class with both foo and bar, to a class with just bar, to a class with neither. In other words, you just read the class definition from top to bottom to figure out the mro. >>> import inspect >>> from pprint import pprint >>> pprint(inspect.getmro(FooBar)) (<class '__main__.FooBar'>, <class '__main__.FooBar'>, <class '__main__.FooBar'>, <type 'object'>) >>> methods = lambda i: [x for x in dir(inspect.getmro(FooBar)[i]) if not x.startswith('__')] >>> methods(0) ['bar', 'foo'] >>> methods(1) ['bar'] >>> methods(2) [] I think this is better. For one thing, your head won’t explode from trying to figure out the method resolution order that you get when you use multiple inheritance.
http://duganchen.ca/implementing-pythonic-mixins-with-class-decorators/
CC-MAIN-2021-17
refinedweb
318
66.94
corejava - Java Beginners corejava pass by value semantics Example of pass by value semantics in Core Java. Hi friend,Java passes parameters to methods using pass by value semantics. That is, a copy of the value of each of the specified CoreJava Project CoreJava Project Hi Sir, I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account hi Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava What is the use of friend function? What is the use of friend function? What is the use of friend corejava - Java Beginners corejava - Java Interview Questions CoreJava - Java Beginners How to find out the friend user between two columns in sql database How to find out the friend user between two columns in sql database Hi, Can any one please tell me ..how to find out the friend user between two columns in sql database? In other words i wanted to get the corresponding data from... friend, A unicast packet is the completely different from multicast.In this,machine... once it's on the network Thanks Hi friend, Unicast means autentication & authorisation - JSP-Servlet /interviewquestions/corejava/null-marker-interfaces-in-java.shtml Thanks...autentication & authorisation wt is the diffarence between authentication and authorisation ? Hi friend, Difference between hint - Java Interview Questions hint Dear roseindia, i want the java interview question and the corresponding question answers. Hi Friend, Please visit the following link: Here you will get lot java - Java Server Faces Questions java Java Server Faces Quedtions Hi friend, Thanks core java - Java Beginners Core Java interview Help Core Java interview questions with answers Hi friend,Read for more information. java - Servlet Interview Questions java servlet interview questions Hi friend, For Servlet interview Questions visit to : Thanks Ask Programming Questions and Discuss your Problems Ask Programming Questions and Discuss your Problems Dear Users, Analyzing your plenty of problems and your love for Java and Java and Java related fields, Roseindia Technologies Hello - Java Beginners Hello Hi Friend, I want to java objective type... send me url. Correct url Thanks Hi friend, To visit this link.... Thanks IMP - Struts for me Thanku Ray Hi friend, Visit for more information: Java Interview - Java Interview Questions Java Interview Please provide some probable Java interviewe Question. Thanking you. Pabitra kr debanth. Hi friend, I am sending.... Thanks java - JSP-Interview Questions java hi.. snd some JSP interview Q&A and i wnt the JNI(Java Native Interface) concepts matrial thanks krishna Hi friend, Read more information. Friend, For interview questions, visit the following link: Thanks Creating a MySQL Database Table to store Java Types Creating a MySQL Database Table to store Java Types Dear user, consider a case where we need to store a java types in our database table. Now one question may arise in your HOW TO BECOME A GOOD PROGRAMMER HOW TO BECOME A GOOD PROGRAMMER I want to know how to become good programmer Hi Friend, Please go through the following link: CoreJava Tutorials Here you will get lot of examples with illustration where you can What is Locale - Java Beginners What is Locale Hi, What is Locale? Write example to show the use of Locale. Thanks Hi Friend, A locale is the part...:// Java Locale Java Locale How will you load a specific locale? Hi Friend, A locale is the part of a user's environment that brings together.../corejava/javatext/parseAndFormatDateUsingLocale.html Thanks hi all - Java Beginners friend, I am sending you a link. This link will help you. Please read for more information. java - Struts . Hi Friend, Please visit the following link: Thanks Java - Java Interview Questions Interview interview, Tech are c++, java, Hi friend, Now get more... link. java questions - Java Interview Questions .....!!! :) Hi Friend, Please visit the following link: Thanks JList JList pls tell me about the concept the JList in corejava? and tell me a suitable example GPS fleet tracking system People running fleet businesses know how much the information of every single moment is critical. GPS fleet tracking system is their best and trustworthy friend in this field, as it not only aids them to know the whereabouts java - Struts java Can you pl. tell me what is the exact meaning of "DESIGN PATTERN". Where will use. What are the types in it? Hi friend, Design.../interviewquestions/design-patterns/design-patterns-interview-questions1.shtml web application web application Dear friend, could u plz tell me wats difference bt web server,application server,container with thanks praveen Inter Thread Communication Inter Thread Communication what is inter thread communication? hi friend, Inter thread communication is a process of communication...:// how to count words in string using java how to count words in string using java how to count words in string using corejava Hi Friend, Try the following code: import java.util.*; class CountWords{ public static void main(String[] args Fleet vehicle tracking system Fleet vehicle tracking system has become a great friend of the manger and owner giving them security and sense of relief as they can any time checks how the work is going on. Fleet system vehicle tracking systems that mostly use is GPS Calculator Calculator Dear Friends, I need code (or advice) for to calculate the value based on my policy name,policy value and policy duration for my mini project in jsp-servlet. Help Me to solve. Advance thanks you dear friend interview questin of java - Java Interview Questions :// Thanks & Regards Amardeep java - Java Interview Questions Friend, Please visit the following link: Here you will get lot of interview questions Java - Java Server Faces Questions Java I want complete details about Java Server Faces. Hi friend, Java Server Faces is also called JSF. JavaServer Faces is a new...:// MSN Web Messenger , at a friend's house or anywhere you can't install the MSN Messenger software. Read JAVA - Struts :// the above link Hi Every One , please give me some idia to opning audio File . please Help .. Hi Every One , please give me some idia to opning audio File . please Help .. hi Dear Friend , please give me a program to opening audio file... (Button),and play agian by Replay (Button) . thinks so much Dear . please ans core java - Java Beginners core java how to create a login page using only corejava(not servlets,jsp,hibernate,springs,structs)and that created loginpage contains database(ms-access) the database contains data what ever u r enter and automatically date servlet config servlet config Dear friend plz tell the Purpose of ServletConfig?? supose if v write sample application .say... hello world in this wat could be the init parameter need to pass !!r plz expalin some sample app where u used all c library functions all c library functions hi dear c coders, i need all c library functions with a detailed explanation. Who can give me usefull link? thanks beforehand! Hi Friend, Please go through the following link: C Tutorials Inserting data in Excel File - Java Beginners Inserting data in Excel File Dear Sir, How can we fill the excel with fetched data from the database like Oracle, DB2? Is it possible to create........ Thanks & Regards, Karthikeyan. K Hi friend, Code to solve code protection - Java Beginners code protection dear friend Please help me, This is importent for me I want to protect my java class and jar file from decompiler software, I think that what you know what is decompiler; please please help me i want JDBC - JDBC JDBC DEAR SIR, HOW TO RUN JDBC PROGRAMS AND TELL ME HOW SET ENVIRONMENTAL PATH IN CONTROL PANNEL..... Hi Friend, Please visit the following link: Thanks load and upload. - JSP-Servlet load and upload. dear sir, plz give me the sol for my problem.i m waiting for u r reply. why u not replying .. Hi Friend, We haven't remember your problem. So please send it again. Thanks WEBLOGIC - Java Beginners WEBLOGIC DEAR SIR, HOW TO RUN THE PROGRAMS IN WEBLOGIC AND TELL HOW TO GIVE ENVIRONMENTAL PATH IN CPNTROLPANNEL. Hi Friend, Please visit the following link: Program error - WebSevices Program error Dear all, How i insert checkbox values into my database without using array. Anyone know the code. Hi friend, Code to help in solve the probelm : Insert CheckBox Java Programs - Java Beginners Java Programs Dear Sir, Could you give me the syntax for HIERARCHIAL INHERITANCE and give sample program for the same?(if possible with an output) Hi Friend, Please visit the following link: http about c and java :// java - Java Beginners multiple classes) Hi friend, Some points to be memember difference.../interviewquestions/corejava.shtml static factory pattern? What is static factory pattern? Hello, please tell me what is static factory pattern? Thank you.. Dear friend, you can go through the following links to better understand the static factory pattern - Factory What is Hibernate one to one relation?Any example.. What is Hibernate one to one relation?Any example.. Hello, What is Hibernate one to one relation? Is there any example of it.. Thanks.. Dear Friend, Here are detailed tutorials and examples of Hibernate One-to-one
http://roseindia.net/tutorialhelp/comment/34693
CC-MAIN-2014-42
refinedweb
1,514
53.71
README complexjscomplexjs This is a library for complex numbers calculations in javascript using plain objects immutably. It has been designed to be used for geometry applications, for which a little API has been included. Complex numbers APIComplex numbers API Any object with the properties re or im (or r and arg) qualifies as a complex number for this API, so there are no creation methods for them. Geometry APIGeometry API Complex number calculations examplesComplex number calculations examples Creating a complex number is as simple as: // Cartesian form const c_cartesian = { re: 1, im; 0 }; // Polar form const c_polar = { r: 1, arg: Math.PI / 2 }; Both forms can be mixed, and the form of the first number will be preserved: import {csum} from 'complexjs'; csum(c_cartesian, c_polar); // => {re: 1, im: 1} csum(c_polar, c_cartesian); // => {r: 1.414, arg: 0.785} All the basic functions are provided. All of them are pure functions: import { cmul, cdiv, cmod, conjugate } from 'complexjs'; cmul(c_cartesian, c_polar); // => {re: 0, im: 1} cdiv(c_cartesian, c_polar); // => {re: 0, im: -1} cmod(c_cartesian); // => 1 conjugate(c_polar); // => {r: 1, arg: - 1.5707} Using plain objectsUsing plain objects The API is designed so that any object can be passed to the functions, and any property other than re and im (or r and arg) will remain unchanged. This can be useful to compose plain objects. const c_object = { rgb: [255, 255, 255], re: 1, im: 1 }; const c_number = { re: 5, im: -1 }; csum(c_object, c_number) // => {rgb: [255, 255, 255], re: 6, im: 0} In case both objects have properties, they will be merged. The first parameter will override the second one if the have a property with the same name. Geometry applications examplesGeometry applications examples Complex numbers serve as an elegant representation of 2d geometry. To make its use even simpler, some methods have been created to wrap the algebra to match its geometric meaning. vector(1, 2) // => {re: 1, im: 2} const square = [ vector(0, 0), vector(1, 0), vector(1, 1), vector(0, 1) ]; const scaledSquare = square.map(c => scale(c, 2)); const translatedSquare = scaledSquare.map(c => translate(c, vector(-1, -1))); const rotatedSquare = translatedSquare.map(c => rotate(c, Math.PI / 2)); // => [ // vector(1, -1), // vector(1, 1), // vector(-1, 1), // vector(-1, -1) // ];
https://www.skypack.dev/view/complexjs
CC-MAIN-2022-33
refinedweb
373
53.21
( *.*instead of an explicit text/html) which can cause undesired behavior in Rails. Someone suggested manually setting the format in a before_filter: params[:format] ||= 'text/html' This was discouraged because it can cause problems elsewhere. A better solution was to put the html format at the top of any `respond_to` blocks: def show respond_to.html # run by default when type cannot be determined respond_to.js end The Ruby MySQL Gem version 2.7 leaks memory for very large queries. The solution is to remove the 2.7 gem and manually install version 2.8 from source. This library is no longer a gem and must be installed from the mysql-ruby-2.8 tarball. Ask for Help “As a followup to Firefox SSL certificate problems…” It turns out that our server running nginx had an old version of OpenSSL installed. Upgrading OpenSSL solved the problem.
http://pivotallabs.com/standup-11-11-2008-firefoxen-goodness/?tag=geminstaller
CC-MAIN-2014-10
refinedweb
145
68.57
Agenda See also: IRC log <scribe> ACTION: Steven to make a reg page for Boston FtF [recorded in] Steven: Note we are meeting Wed/Thu/Fri <scribe> ACTION: Steven to ensure there is a chair for next week [recorded in] Steven: I can't be here next week, at a W3C.de day Steven: The GRDDL people would rather we kept @profile ... but the problem is that even if we kept it, people would still be able to use rel="profile" Shane: I'm not willing to give up rel="profile"; that would be a mistake ... there is also a problem is they are co-opting @profile Steven: Do the different uses, like microformats and GRDDL, bite each other? ... can they work in combination? Mark: I think they have their own URL in the profile attribute as one of the urls ... and then seeing that they know they need to process the document ... then they use rels (maybe) to discover the transformation ... They use namespaces ... there's no use of profile at all in the example I'm looking at <markbirbeck> <html xmlns="" xmlns: <head> (2. Adding GRDDL to well-formed XML) Mark: It just happens that they used xhtml for their xml example 4. Using GRDDL with valid XHTML <html xmlns=""> <head profile=""> <link rel="transformation" href="" /> Shane: If we were nice, we would add 'transformation' to our list of rels Steven: Good idea ... and @grddl:transformation to the html element ... Why not use the grddl namespace declaration to detect a grddl document? Mark: At the least we should be saying that @profile is too flaky ... it doesn't give you the connection between the profile url and the rel values ... it doesn't give you anything actually Shane: We ought to have worked with them to produce a rel="grddl" ... But it is already a Rec Mark: Are we going to preserve this in XHTML2 ... they argue yes for backwards compatibility ... but it is not an issue really Shane: Let me play devil's advocate ... they want the same processor to work on HTML and XHTML2 Mark: But other document types don't have the profile attribute ... why should we? ... We should use the other technique in XHTML2 ... We should reply "Given you have another mechanism, why should we use the legacy mechanism, which is flaky anyway?" Shane: Say it in a different way. "Hey, we are generic XML, and we'll even build a GRDDL module for you, so you can use the generic mechanism" Mark: We need to think about this for RDFa too Shane: Since rdfa takes a CURIE in rel, it just works ... you have to devclare the GRDDL namespace, but they do that anyway Mark: And in XHTML+RDFa they should be using the generic method too ... rel="grddl:transformation" Steven: But isn't their pain point that they want to be able to identify a GRDDLE doc from the root, or otherwise head element? Shane: The GRDDL namespace should be good enough for them <scribe> ACTION: Steven to reply to GRDDL people about techniques for identifying GRDDL docs [recorded in] <markbirbeck> The spec says "This method [using @profile] is suitable for use with valid XHTML documents which are constrained by an XML DTD." In other words they are saying that this is _not_ the preferred method. <markbirbeck> So it seems legitimate to me to say that we feel no need to try to support the @profile technique, in situations where the @xmlns technique is supported. Mark: Their doc does seem to say that the profile technique is a fallback when the XML technique isn't suitable, so that backs up our position <markbirbeck> For example: "To accomodate the DTD-based syntax of XHTML[XHTML], which precludes using attributes from foreign namespaces, we use as a metadata profile (cf. section 7.4.4.3 Meta data profiles of [HTML4])." Shane: These are defined as far as I know. Let me check ... Yes, in the frame module Mark: Maybe they are missing in the schema, but not in the spec Shane: Oh, he's right ... we need to reissue ruby ... oh wait ... they are in here too ... oh, he maybe right <scribe> ACTION: Shane to fix missing elements in M12N [recorded in] <scribe> ACTION: Shane to reply to ht [recorded in] <scribe> ACTION: Group to reissue Ruby with schema additions [recorded in] Steven: The abstract says that the poresentation module is included Shane: And we list hr too <!ENTITY % InlPres.class "| %tt.qname; | %i.qname; | %b.qname; | %big.qname; | %small.qname; | %sub.qname; | %sup.qname;" > <ShaneM> b, big, hr, i, small, sub, sup, tt Shane: I'll link it in Steven: This will have to be a CR comment <scribe> ACTION: Shane to link hr into Basic 1.1 [recorded in] <scribe> ACTION: Steven to reply to hr comment, and make it a CR comment [recorded in] Steven: Didn't you have a testfest revently Yam? Yam: Starting tomorrow ... and November in Slovenia ... but I'll check Shane: Well, this is a technique to get round bugs in browsers ... we shouldn't document that ... we use this technique too ... but it shouldn't be part of a spec <yamx> OMA test fest 20 was from Sep 7 to Sep 14, so I will check the test reports. <scribe> ACTION: Steven to reply to script+cdata mail, saying we don't want to document it [recorded in] Steven: I have requested a last call publication ... awaiting a reply about a suitable date ... when that comes in, we can publish with that date Steven: We have gone through last call, so we should move to CR with this ... do we have a DoC? <scribe> ACTION: Shane to ensure we have a M12N DoC [recorded in] <scribe> ACTION: Steven to take M12N to CR [recorded in] ADJOURN This is scribe.perl Revision: 1.128 of Date: 2007/02/23 21:38:13 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/ought/ought to have/ Succeeded: s/SHane/Shane/G Succeeded: s/we/they/ Succeeded: s/THe/The/G Succeeded: s/o it/So it/ FAILED: s/TH/Th/ Succeeded: s/rpofile/profile/ Found Scribe: Steven Inferring ScribeNick: Steven Default Present: yamx, Steven, [IBM], Rich, Alessio, markbirbeck, McCarron, +046708aaaa, Tina, ShaneM Present: yamx Steven [IBM] Rich Alessio markbirbeck McCarron +046708aaaa Tina ShaneM Agenda: Got date from IRC log name: 19 Sep 2007 Guessing minutes URL: People with action items: group shane steven[End of scribe.perl diagnostic output]
http://www.w3.org/2007/09/19-xhtml-minutes
crawl-002
refinedweb
1,086
70.02
Provided by: leiningen_2.9.0-1_all NAME lein - Automate Clojure projects SYNOPSIS lein [-o] [-U] [TASK [ARGS]] lein [-h|--help] lein [-v|--version] DESCRIPTION Leiningen is for automating Clojure projects without setting your hair on fire. Working on Clojure projects with tools designed for Java can be an exercise in frustration. With Leiningen, you just write Clojure. TASKS lein help will show the complete list of tasks, while lein help TASK shows usage for a specific one. lein help tutorial has a detailed walk-through of the various tasks, but the most commonly-used are: lein new NAME generate a new project skeleton lein test [TESTS] run the tests in the TESTS namespaces, or all tests lein repl launch an interactive REPL session in a networked REPL server lein uberjar package up the project and its dependencies as a standalone .jar file lein install install a project into your local repository lein deploy [REPOSITORY] deploy a library to a remote repository Other tasks available include: lein change Rewrite project.clj by applying a function. lein check Check syntax and warn on reflection. lein classpath Print the classpath of the current project. lein clean Remove all files from project's target-path. lein compile Compile Clojure source into .class files. lein deps Download all dependencies. lein do [TASK], ... Higher-order task to perform other tasks in succession. lein jar Package up all the project's files into a jar file. lein javac Compile Java source files. lein pom Write a pom.xml file to disk for Maven interoperability. lein release Perform :release-tasks. lein retest Run only the test namespaces which failed last time around. lein run Run a -main function with optional command-line arguments. lein search Search remote maven repositories for matching jars. lein show-profiles List all available profiles or display one if given an argument. lein trampoline [TASK] Run a task without nesting the project's JVM inside Leiningen's. lein update-in Perform arbitrary transformations on your project map. lein vcs Interact with the version control system. lein version Print version for Leiningen and the current JVM. lein with-profile [PROFILE] [TASK] Apply the given task with the profile(s) specified. OPTIONS -o Run a task offline. -U Run a task after forcing update of snapshots. -h, --help Print this help or help for a specific task. -v, --version Print Leiningen's version. CONFIGURATION Leiningen reads its configuration from the project.clj file in your project root. Either use lein new to create a fresh project from which to work, or see the exhaustive list of configuration options with lein help sample. You can customize your project map further with profiles; see lein help profiles. BUGS Check to see if your problem is a known issue. If not, please open a new issue on that site or join the mailing list at. Please include the output of lein version as well as your project.clj file and as much of the relevant code from your project as possible. COPYING Copyright (C) 2009-2017 Phil Hagelberg and contributors. Distributed under the Eclipse Public License, the same as Clojure uses. See the file /usr/share/doc/leiningen/copyright. AUTHOR This manpage is written by Phil Hagelberg <technomancy@gmail.com> 2017 August 10 LEININGEN(1)
http://manpages.ubuntu.com/manpages/eoan/man1/lein.1.html
CC-MAIN-2019-47
refinedweb
546
68.57
import "go/build" Package build gathers information about Go packages. The Go path is a list of directory trees containing Go source code. It is consulted to resolve imports that cannot be found in the standard Go tree. The default path is the value of the GOPATH environment variable, interpreted as a path list appropriate to the operating system (on Unix, the variable is a colon-separated string; on Windows, a semicolon-separated string; on Plan 9, a list). Each directory listed in the Go path Go path, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a" (or, for gccgo, "DIR/pkg/gccgo/foo/libbar.a"). The bin/ directory holds compiled commands. Each command is named for its source directory, but only using the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped so that you can add DIR/bin to your PATH to get at the installed commands. Here's an example directory layout: GOPATH=/home/user/gocode /home/user/gocode/ src/ foo/ bar/ (go code in package bar) x.go quux/ (go code in package main) y.go bin/ quux (installed command) pkg/ linux_amd64/ foo/ bar.a (installed package object) A build constraint,. To distinguish build constraints from package documentation, a series of build constraints must be followed by a blank line. A build constraint is evaluated as the OR of space-separated options; each option evaluates as the AND of its comma-separated terms; and each term is an alphanumeric word or, preceded by !, its negation. That is, the build constraint: // +build linux,386 darwin,!cgo corresponds to the boolean formula: (linux AND 386) OR (darwin AND (NOT cgo)) A file may have multiple build constraints. The overall constraint is the AND of the individual constraints. That is, the build constraints: // +build linux darwin // +build 386 corresponds to the boolean formula: (linux OR darwin) AND 386 During a particular build, the following words are satisfied: - the target operating system, as spelled by runtime.GOOS - the target architecture, as spelled by runtime.GOARCH - the compiler being used, either "gc" or "gccgo" - "cgo", if ctxt.CgoEnabled is true - "go1.1", from Go version 1.1 onward - "go1.2", from Go version 1.2 onward - ). To keep a file from being considered for the build: // +build ignore (any other unsatisfied word will work as well, but “ignore” is conventional.) To build a file only when using cgo, and only on Linux and OS X: // +build linux,cgo darwin,cgo Such a file is usually paired with another file implementing the default functionality for other systems, which in this case would carry the constraint: // +build !linux,!darwin !cgo Naming a file dns_windows.go will cause it to be included only when building the package for Windows; similarly, math_386.s will be included only when building the package for 32-bit x86.. build.go doc.go read.go syslist.go ToolDir is the directory containing build tools. ArchChar returns "?" and an error. In earlier versions of Go, the returned string was used to derive the compiler and linker tool names, the default object file suffix, and the default linker output name. As of Go 1.5, those strings no longer vary by architecture; they are compile, link, .o, and a.out, respectively. IsLocalImport reports whether the import path is a local import path, like ".", "..", "./foo", or "../foo". // The build and release tags specify build constraints // that should be considered satisfied when processing +build lines. // Clients creating a new context may customize BuildTags, which // defaults to empty, but it is usually an error to customize ReleaseTags, // which defaults to the list of Go releases the current release is compatible with. // In addition to the BuildTags and ReleaseTags, build constraints // consider the values of GOARCH and GOOS as satisfied tags. BuildTags []string ReleaseTags []string // The install suffix specifies a suffix to use in the name of the installation // directory. By default it is empty, but custom builds that need to keep // their outputs separate can set InstallSuffix to do so. For example, when // using the race detector, the go command uses InstallSuffix = "race", so // that on a Linux/386 system, packages are written to a directory named // "linux_386_race" instead of the usual "linux_386". InstallSuffix string // JoinPath joins the sequence of path fragments into a single path. // If JoinPath is nil, Import uses filepath.Join. JoinPath func(elem ...string) string // SplitPathList splits the path list into a slice of individual paths. // If SplitPathList is nil, Import uses filepath.SplitList. SplitPathList func(list string) []string // IsAbsPath reports whether path is an absolute path. // If IsAbsPath is nil, Import uses filepath.IsAbs. IsAbsPath func(path string) bool // IsDir reports whether the path names a directory. // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method. IsDir func(path string) bool // HasSubdir reports whether dir is lexically a subdirectory of // root, perhaps multiple levels below. It does not try to check // whether dir exists. // If so, HasSubdir sets rel to a slash-separated path that // can be joined to root to produce a path equivalent to dir. // If HasSubdir is nil, Import uses an implementation built on // filepath.EvalSymlinks. HasSubdir func(root, dir string) (rel string, ok bool) // ReadDir returns a slice of os.FileInfo, sorted by Name, // describing the content of the named directory. // If ReadDir is nil, Import uses ioutil.ReadDir. ReadDir func(dir string) ([]os.FileInfo, error) // OpenFile opens a file (not a directory) for reading. // If OpenFile is nil, Import uses os.Open. OpenFile func(path string) (io.ReadCloser, error) } A Context specifies the supporting context for a build. Default is the default Context for builds. It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables if set, or else the compiled code's GOARCH, GOOS, and GOROOT. Import returns details about the Go package named by the import path, interpreting local import paths relative to the srcDir directory. If the path is a local import path naming a package that can be imported using a standard import path, the returned package will set p.ImportPath to that path. In the directory containing the package, .go, .c, .h, and .s files are considered part of the package except for: - .go files in package documentation - files starting with _ or . (likely editor temporary files) - files with build constraints not satisfied by the context If an error occurs, Import returns a non-nil error and a non-nil *Package containing partial information. ImportDir is like Import but processes the Go package found in the named directory. MatchFile reports whether the file with the given name in the given directory matches the context and would be included in a Package created by ImportDir of that directory. MatchFile considers the name of the file and may use ctxt.OpenFile to read some or all of the file's content. SrcDirs returns a list of package source root directories. It draws from the current Go root and Go path but omits directories that do not exist. An ImportMode controls the behavior of the Import method. const ( // If FindOnly is set, Import stops after locating the directory // that should contain the sources for a package. It does not // read any files in the directory. FindOnly ImportMode = 1 << iota // If AllowBinary is set, Import can be satisfied by a compiled // package object without corresponding sources. // // Deprecated: // The supported way to create a compiled-only package is to // write source code containing a //go:binary-only-package comment at // the top of the file. Such a package will be recognized // regardless of this flag setting (because it has source code) // and will have BinaryOnly set to true in the returned Package. AllowBinary // If ImportComment is set, parse import comments on package statements. // Import returns an error if it finds a comment it cannot understand // or finds conflicting comments in multiple source files. // See golang.org/s/go14customimport for more information. ImportComment // By default, Import searches vendor directories // that apply in the given source directory before searching // the GOROOT and GOPATH roots. // If an Import finds and returns a package using a vendor // directory, the resulting ImportPath is the complete path // to the package, including the path elements leading up // to and including "vendor". // For example, if Import("y", "x/subdir", 0) finds // "x/vendor/y", the returned package's ImportPath is "x/vendor/y", // not plain "y". // See golang.org/s/go15vendor for more information. // // Setting IgnoreVendor ignores vendor directories. // // In contrast to the package's ImportPath, // the returned package's Imports, TestImports, and XTestImports // are always the exact import paths from the source files: // Import makes no attempt to resolve or check those paths. NoGoError is the error used by Import to describe a directory containing no buildable Go source files. (It may still contain test files, files hidden by build tags, and so on.) system object files to add to archive // Cgo directives CgoCFLAGS []string // Cgo CFLAGS directives CgoCPPFLAGS []string // Cgo CPPFLAGS directives CgoCXXFLAGS []string // Cgo CXXFLAGS directives C from XTestGoFiles XTestImportPos map[string][]token.Position // line information for XTestImports } A Package describes the Go package found in a directory. func Import(path, srcDir string, mode ImportMode) (*Package, error) Import is shorthand for Default.Import. func ImportDir(dir string, mode ImportMode) (*Package, error) ImportDir is shorthand for Default.ImportDir. IsCommand reports whether the package is considered a command to be installed (not just a library). Packages named "main" are treated as commands. Package build imports 20 packages (graph) and is imported by 2939 packages. Updated 2018-06-08. Refresh now. Tools for package owners.
https://godoc.org/go/build
CC-MAIN-2018-26
refinedweb
1,631
56.76
Even as web and mobile applications appear to overtake the software development market, there’s still a demand for traditional Graphical User Interface (GUI) desktop applications. For developers who are interested in building these kinds of applications in Python, there are a wide variety of libraries to choose from, including Tkinter, wxPython, PyQt, PySide2, and others. In this tutorial, you’ll develop GUI desktop applications with Python and PyQt. You’ll learn how to: - Create Graphical User Interfaces with Python and PyQt - Give life to your applications by connecting user events to concrete actions - Create fully-functional GUI applications to solve real-world problems For this tutorial, you’ll create a calculator application with Python and PyQt. This will help you grasp the fundamentals and get you up and running with the library. You can download the source code for the project and all examples in this tutorial by clicking on the link below: Download Code: Click here to download the code you'll use to build a calculator in Python with PyQt in this tutorial. Understanding PyQt PyQt is a Python binding for Qt, which is a set of C++ libraries and development tools that include platform-independent abstractions for Graphical User Interfaces (GUI), as well as networking, threads, regular expressions, SQL databases, SVG, OpenGL, XML, and many other powerful features. Developed by RiverBank Computing Ltd, PyQt is available in two editions: - PyQt4: an edition that’s built against Qt 4.x and 5.x - PyQt5: an edition that’s only built against Qt 5.x Even though PyQt4 can be built against Qt 5.x, only a small subset that is also compatible with Qt 4.x will be supported. This means that if you decide to use PyQt4, then you’ll probably miss out on some of the new features and improvements in PyQt5. See the PyQt4 documentation for more information on this topic. You’ll be covering PyQt5 in this tutorial, as it seems to be the future of the library. From now on, be sure to consider any mention of PyQt as a reference to PyQt5. Note: If you want to dive deeper into the differences between the two versions of the library, then you can take a look at the related page on the PyQt5 documentation. PyQt5 is based on Qt v5 and includes classes that cover Graphical User Interfaces as well as XML handling, network communication, regular expressions, threads, SQL databases, multimedia, web browsing, and other technologies available in Qt. PyQt5 implements over one thousand of these Qt classes in a set of Python modules, all of which are contained within a top-level Python package called PyQt5. PyQt5 is compatible with Windows, Unix, Linux, macOS, iOS, and Android. This can be an attractive feature if you’re looking for a library or framework to develop multi-platform applications with a native look and feel on each platform. PyQt5 is available under two licenses: Your PyQt5 license must be compatible with your Qt license. If you use the GPL version, then your code must also use a GPL-compatible license. If you want to use PyQt5 to create commercial applications, then you’ll need a commercial license for your installation. Note: The Qt Company has developed and currently maintains its own Python binding for the Qt library. The Python library is called Qt for Python and is considered to be the official Qt for Python. In this case, the Python package is called PySide2. As PyQt5 and PySide2 are both built on top of Qt, their APIs are quite similar, even almost identical. That’s why porting PyQt5 code to PySide2 can be as simple as updating some imports. If you learn one of them, then you’ll be able to work with the other with minimal effort. If you want to dive deeper into the differences between these two libraries, then you can check out the following resources: Installing PyQt You have several options to choose from when you install PyQt on your system or development environment. The first option is to build from source. This can be a bit complicated, so you might want to avoid it if possible. If you really need to build from source, then you can take a look at what the library’s documentation recommends in those cases. Note: Most of the installation options you’ll cover here require that you have a working Python installation. If you need to dive deeper into how to install Python, then check out Installing Python on Windows, macOS, and Linux. Another option would be to use binary wheels. Wheels are a very popular way to manage the installation of Python packages. However, you need to consider that wheels for PyQt5 are only available for Python 3.5 and later. There are wheels for: - Linux (64-bit) - macOS - Windows (32-bit and 64-bit) All of these wheels include copies of the corresponding Qt libraries, so you won’t need to install them separately. Your third option is to use package managers on Linux distributions and macOS. For Windows, you can use a binary .exe file. Your fourth and final option is to use the Anaconda distribution to install PyQt on your system. The next few sections will walk you through some of the options you have to properly install PyQt5 from different sources and on different platforms. System-Wide Installation With pip If you’re using Python 3.5 or later, then you can install PyQt5 from PyPI by running the following command: $ pip3 install pyqt5 With this command, you’ll install PyQt5 in your base system. You can start using the library immediately after the installation finishes. Depending on your operating system, you may need root or administrator privileges for this installation to work. Virtual Environment Installation With pip You may decide not to install PyQt directly on your base system to avoid messing up your configuration. In this case, you can use a Python virtual environment. Use the following commands to create one and install PyQt5: $ python3 -m venv pyqtvenv $ source pyqtvenv/bin/activate (pyqtvenv) $ pip install pyqt5 Collecting pyqt5 ... Successfully installed PyQt5-sip-4.19.17 pyqt5-5.12.2 Here, you create a virtual environment with venv. Once you activate it, you install pyqt5 in that environment with pip install pyqt5. This installation alternative is the most recommended option if you want to keep your base system clean. Platform-Specific Installation In the Linux ecosystem, several distributions include binary packages for PyQt in their repositories. If this is true for your distribution, then you can install the library using the distribution’s package manager. On Ubuntu 18.04 for example, you can use the following command: $ sudo apt install python3-pyqt5 With this command, you’ll install PyQt5 and all its dependencies in your base system, so you can use the library in any of your GUI projects. Note that root privileges are needed, which you invoke here with sudo. If you’re a Mac user, then you can install PyQt5 using the Homebrew package manager. To do that, open a terminal and type in the following command: $ brew install pyqt5 If all goes well, then you’ll have PyQt5 installed on your base system, ready for you to use. Note: If you use a package manager on Linux or macOS, then there’s a chance you won’t get the latest version of PyQt5. A pip installation would be better if you want to ensure that you have the latest release. If you prefer to use Windows, but you decide not to use the binary wheels, then your path through PyQt installation can be painful. That’s because the PyQt5 download page appears to no longer provide Windows binaries ( .exe files) for later versions. Still, you can find some Windows binary packages for older versions of the library at the project page. The latest binary file was built for PyQt v5.6. If you really need to install PyQt this way, then you’ll need to: - Determine what version of Python you’re running and whether you have 32-bit or 64-bit Python - Download the right version for your Python installation - Install PyQt by running the .exefile and following the on-screen instructions Anaconda Installation Another alternative you can use to install PyQt is Anaconda, a Python distribution for data science. Anaconda is a free and multi-platform package and environment manager that includes a collection of over 1,500 open source packages. Anaconda provides a user-friendly installation wizard that you can use to install PyQt on your system. You can download the appropriate version for your current platform and follow the on-screen instructions. If you install the latest version of Anaconda, then you’ll have the following packages: pyqt: a Python binding for the cross-platform GUI toolkit Qt (Commercial, GPL-2.0, GPL-3.0 licenses) anyqt: a compatibility layer for PyQt4/PyQt5 (GPL-3.0 license) qtpy: an abstraction layer PyQt5/PyQt4/PySide (MIT license) pyqtgraph: a Python library for Scientific Graphics (MIT license) With this set of packages, you’ll have all that you need to develop GUI desktop applications with Python and PyQt. Note: Note that the Anaconda installation will occupy a large amount of disk space. If you install Anaconda only to use the PyQt packages, then you’ll have a serious amount of unused packages and libraries on your system. Keep this in mind when you consider using the Anaconda distribution. Creating Your First PyQt Application Now that you have a working PyQt installation, you’re ready to start coding. You’re going to create a “Hello, World!”). You can download the source code for the examples you’ll cover in this section at the link below: Download Code: Click here to download the code you'll use to build a calculator in Python with PyQt in this tutorial. You’ll start with a file called hello.py in your current working directory: # Filename: hello.py """Simple Hello World example with PyQt5.""" import sys # 1. Import `QApplication` and all the required widgets from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QLabel from PyQt5.QtWidgets import QWidget First, you import sys, which will allow you to handle the exit status of the application. Then, you import QApplication, QWidget, and QLabel from QtWidgets, which is part of the package called PyQt5. You’ll be using these imports later on, but for now, you’re done with step one. For step two, you need to create an instance of QApplication as follows: # 2. Create an instance of QApplication app = QApplication(sys.argv) Here, you create the instance of QApplication. Since the QApplication object ( app) does so much initialization, you should create it before you create any other object related to the GUI. The QApplication object also deals with common command line arguments, so you also need to pass in sys.argv as an argument when you create app. Note: sys.argv contains the list of command-line arguments passed into a Python script. If your application is not going to accept command line arguments, then you can use an empty list instead of sys.argv. That is, you can do something like app = QApplication([]). Step three is to create the application’s GUI. For this example, your GUI will be based on QWidget, which is the base class of all user interface objects in PyQt. Let’s create the GUI: # 3. Create an instance of your application's GUI window = QWidget() window.setWindowTitle('PyQt5 App') window.setGeometry(100, 100, 280, 80) window.move(60, 15) helloMsg = QLabel('<h1>Hello World!</h1>', parent=window) helloMsg.move(60, 15) In this code, window is an instance of QWidget, which provides all the features you’ll need to create the application’s window (or form). With .setWindowTitle(), you can add a title to your application’s window. In this case, the title to show is PyQt5 App. You can use .setGeometry() to define the size of the window and where to place it on your screen. The first two parameters are the x and y coordinates at which the window will be placed on the screen. The third and fourth parameters are the width and height of the window. Every functional GUI application needs widgets! Here, you use a QLabel object ( helloMsg) to show the message Hello World! on your application’s window. QLabel objects can accept HTML text, so you can use the HTML element '<h1>Hello World!</h1>' to format the text as an h1 header. Finally, you use .move() to place helloMsg at the coordinates (60, 15) on your application’s window. Note: In PyQt5, you can use any widget (a subclass of QWidget) as a top-level window, or even a button or a label. The only condition is that you pass no parent to it. When you use a widget like this, PyQt5 automatically gives it a title bar and turns it into a normal window. The parent-child relationship is used for two complementary purposes: - A widget that doesn’t have a parentis a main window or a top-level window. - A widget that has a parent(which is always another widget) is contained (or shown) within its parent. This relationship also defines ownership, with parents owning their children. The PyQt5 ownership model ensures that if you delete a parent (for example, a top-level window), then all of its children (widgets) are automatically deleted as well. To avoid memory leaks, you should always make sure that any QWidget object has a parent, with the sole exception of top-level windows. You’re done with step three, so let’s code the last two steps and get your first PyQt GUI application ready to go live: # 4. Show your application's GUI window.show() # 5. Run your application's event loop (or main loop) sys.exit(app.exec_()) Here, you call .show() on window. The call to .show() schedules a paint event. In other words, it adds a new event to the application’s event queue. You cover the event loop in a later section. Note: A paint event is a request for painting the widgets that compose a GUI. Finally, you start the application’s event loop by calling app.exec_(). The call to .exec_() is wrapped in a call to sys.exit(), which allows you to cleanly exit Python and release memory resources when the application terminates. You can run hello.py with the following command: $ python3 hello.py When you run this script, you should see a window like this: Here, your application shows a window (based on QWidget) with the message Hello World! on it. To show the message, you use a QLabel that contains the message in HTML format. Congrats! You’ve created your first PyQt GUI desktop application! Considering Code Styles If you take a closer look at the code for your first application, then you’ll notice that PyQt doesn’t follow PEP 8 coding style and naming conventions. PyQt is built on top of Qt, which is written in C++ and uses a camelCase naming style for functions, methods, and variables. That said, you’ll need to decide what naming style you’re going to use for your own PyQt GUI applications. With regard to this issue, PEP 8 states that: New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred. (Source) In addition, the Zen of Python says: …practicality beats purity. (Source) If you want to write consistent code, then you might want to disregard PEP 8 naming style and stick to the PyQt naming style. This is a decision that you need to make. In this tutorial, you’ll follow the PyQt naming style for consistency. Learning the Basics of PyQt You’ll need to master the basic concepts of PyQt logic in order to efficiently use the library to develop GUI applications. Some of these concepts include: - Widgets - Layout managers - Dialogs - Main windows - Applications - Event loops - Signals and slots These elements will be the building blocks of your PyQt GUI applications. Most of them are represented as Python classes. PyQt5.QtWidgets is the module that provides all these classes. These elements are extremely important, so you’ll cover them in the next few sections. Widgets QWidget is the base class for all user interface objects, or widgets. These are rectangular-shaped graphical components that you can place on your application’s windows to build the GUI. Widgets contain a series of attributes and methods that allow you to model their appearance and behavior. They can also paint a representation of themselves on the screen. Widgets also receive mouse clicks, keypresses, and other events from the user, the window system, and many other sources. Each time a widget catches an event, it emits a signal to announce its state change. PyQt5 has a rich and modern collection of widgets that serve several purposes. Some of the most common and useful widgets are: - Buttons - Labels - Line edits - Combo boxes - Radio buttons Let’s take a closer look at each of these widgets. First up is the button. You can create a button by instantiating QPushButton, a class that provides a classical command button. Typical buttons are OK, Cancel, Apply, Yes, No, and Close. Here’s how they look on a Linux system: Buttons like these are perhaps the most commonly used widget in any GUI. When you click them, you can command the computer to perform actions. You can even perform actions in response to a user clicking a button. Up next are labels, which you can create with QLabel. Labels give you a way to display useful information in the form of text or images: You can use labels like these to better explain the purpose or usage of your GUI. You can tweak their appearance in several ways, and they can even accept HTML text, as you saw earlier. Labels can also be used to specify a focus mnemonic key for another widget. Another common widget is the line edit, a single-line text box that you can create with QLineEdit. Line edits are useful when you need the user to enter or edit data in plain text format. Here’s how they look on a Linux system: Line edits like these provide basic editing operations like copy, paste, undo, redo, drag, drop, and so on. In the above figure, you can also see that the objects on the first row show placeholder text to inform the user what kind of input is required. Combo boxes are another useful widget that you can create with QComboBox. A combo box will present your user with a list of options in a way that takes up a minimal amount of screen space. Here’s an example of a dropdown list on a Linux system: This combo box is read-only, which means the user can select one of several options but can’t add their own. Combo boxes can also be editable, allowing the user to add new options. They can contain pixmaps, strings, or both. The last widget you’ll cover here is the radio button, which you can create with QRadioButton. A QRadioButton object is an option button that can be switched on (checked) or off (unchecked). Radio buttons are useful when you need the user to select one of many options. In this case, all options are visible on the screen at the same time: In this group of radio buttons, only one button can be checked at a given time. If the user selects another radio button, then the previously selected button will switch off automatically. PyQt5 has a large collection of widgets. At the time of this writing, there are over forty available for you to use to create your application’s GUI. Those you’ve covered so far are only a small sample, but they show you the power and flexibility of PyQt5. In the next section, you’ll cover how to lay out different widgets to create modern and functional GUIs for your applications. Layout Managers Now you know what widgets are and how to use them to build GUIs. But how can you arrange a set of widgets to create a GUI that is both coherent and functional? There are a variety of techniques that you can use to lay out the widgets on a form or window. For instance, you can use .resize() and .move() to give widgets absolute sizes and positions. However, this can have some drawbacks: - You’ll have to do a lot of manual calculations to determine the correct size and position of every single widget in your forms. - You’ll have to do some extra calculations to correctly respond to changes in form size (resize event). - You’ll have to redo all the calculations whenever you change the layout of your forms or add or remove widgets. One alternative is to use .resizeEvent() to calculate widget size and position dynamically. However, the most effective alternative is might be to use layout managers, which will both increase your productivity and improve your code’s maintainability. Layout managers are classes that allow you to size and position your widgets at the places you want them to be on the application’s form. Layout managers automatically adapt to resize events and content changes. They also control the size of the widgets within them. This means that the widgets in a layout are automatically resized whenever the form is resized. Note: If you develop international applications, then you may have seen how translated labels can be cut short. This is particularly likely when the target language is more verbose than the original language. Layout managers can help you avoid this common pitfall. However, this feature can be a bit tricky and can sometimes fail with particularly wordy languages. PyQt provides four basic layout manager classes: The first layout manager class is QHBoxLayout, which arranges widgets horizontally from left to right: The widgets will appear one next to the other, starting from the left. This code example shows you how to use QHBoxLayout to arrange buttons horizontally: 1 # Filename: h_layout.py 2 3 """Horizontal layout example.""" 4 5 import sys 6 7 from PyQt5.QtWidgets import QApplication 8 from PyQt5.QtWidgets import QHBoxLayout 9 from PyQt5.QtWidgets import QPushButton 10 from PyQt5.QtWidgets import QWidget 11 12 app = QApplication(sys.argv) 13 window = QWidget() 14 window.setWindowTitle('QHBoxLayout') 15 layout = QHBoxLayout() 16 layout.addWidget(QPushButton('Left')) 17 layout.addWidget(QPushButton('Center')) 18 layout.addWidget(QPushButton('Right')) 19 window.setLayout(layout) 20 window.show() 21 sys.exit(app.exec_()) The highlighted lines do the magic here: - Line 15 creates a QHBoxLayoutobject called layout. - Lines 16 to 18 add three buttons to layoutwith .addWidget() - Line 19 sets layoutas your window’s layout with .setLayout(). When you run python3 h_layout.py from your command line, you’ll get the following output: In the above figure, you added three buttons in a horizontal arrangement. Notice that the buttons are shown from left to right in the same order as you added them in your code. The next layout manager class is QVBoxLayout, which arranges widgets vertically, from top to bottom: Each new widget will appear beneath the previous one. You can use this class to construct vertical box layout objects and organize your widget from top to bottom. Here’s how you can create and use a QVBoxLayout object: 1 # Filename: v_layout.py 2 3 """Vertical layout example.""" 4 5 import sys 6 7 from PyQt5.QtWidgets import QApplication 8 from PyQt5.QtWidgets import QPushButton 9 from PyQt5.QtWidgets import QVBoxLayout 10 from PyQt5.QtWidgets import QWidget 11 12 app = QApplication(sys.argv) 13 window = QWidget() 14 window.setWindowTitle('QVBoxLayout') 15 layout = QVBoxLayout() 16 layout.addWidget(QPushButton('Top')) 17 layout.addWidget(QPushButton('Center')) 18 layout.addWidget(QPushButton('Bottom')) 19 window.setLayout(layout) 20 window.show() 21 sys.exit(app.exec_()) In line 15, you create an instance of QVBoxLayout. In the next three lines, you add three buttons to layout. Finally, you use layout to arrange the widget in a vertical layout. When you run this application, you’ll get an output like this: This application shows three buttons in a vertical layout, one below the other. The buttons appear in the same order as you added them in your code, from top to bottom. The third layout manager class is QGridLayout, which arranges widgets into a grid of rows and columns. Every widget will have a relative position on the grid. You can define a widget’s position by passing it a pair of coordinates in the form of (row, column). These coordinates should be valid int numbers. They define which cell of the grid you’re going to place the widget on. The grid layout works as follows: QGridLayout takes the space made available to it by its parent, divides it up into rows and columns, and puts each widget into its own cell. Here’s how to use QGridLayout in your GUI: 1 # Filename: g_layout.py 2 3 """Grid layout example.""" 4 5 import sys 6 7 from PyQt5.QtWidgets import QApplication 8 from PyQt5.QtWidgets import QGridLayout 9 from PyQt5.QtWidgets import QPushButton 10 from PyQt5.QtWidgets import QWidget 11 12 app = QApplication(sys.argv) 13 window = QWidget() 14 window.setWindowTitle('QGridLayout') 15 layout = QGridLayout() 16 layout.addWidget(QPushButton('Button (0, 0)'), 0, 0) 17 layout.addWidget(QPushButton('Button (0, 1)'), 0, 1) 18 layout.addWidget(QPushButton('Button (0, 2)'), 0, 2) 19 layout.addWidget(QPushButton('Button (1, 0)'), 1, 0) 20 layout.addWidget(QPushButton('Button (1, 1)'), 1, 1) 21 layout.addWidget(QPushButton('Button (1, 2)'), 1, 2) 22 layout.addWidget(QPushButton('Button (2, 0)'), 2, 0) 23 layout.addWidget(QPushButton('Button (2, 1) + 2 Columns Span'), 2, 1, 1, 2) 24 window.setLayout(layout) 25 window.show() 26 sys.exit(app.exec_()) In this example, you create an application that uses a QGridLayout object to organize its widgets. Notice that, in this case, the second and third arguments you pass to .addWidget() are int arguments that define the position of each widget. In line 23, you add two more arguments to .addWidget(). These arguments are called rowSpan and columnSpan, and they’re the fourth and fifth arguments passed to the function. You can use them to make a widget occupy more than one row or column like you did with QPushButton('Button (2, 1) + 2 Columns Span') here. If you run this code from your command line, then you’ll get a window like this: You can see your widgets arranged in a grid of rows and columns. The last widget occupies more than one cell, as you specified in line 23. The last layout manager class is QFormLayout, which arranges widgets in a two-column layout. The first column usually displays messages in labels. The second column generally contains widgets like QLineEdit, QComboBox, QSpinBox, and so on. These allow the user to enter or edit data regarding the information in the first column. The following diagram shows how form layouts work in practice: The left column consists of labels, and the right column consists of field widgets. If you’re dealing with a database application, then this kind of layout can be an attractive option for increased productivity when you’re creating your forms. The following example shows you how to create an application that uses a QFormLayout object to arrange its widgets: 1 # Filename: f_layout.py 2 3 """Form layout example.""" 4 5 import sys 6 7 from PyQt5.QtWidgets import QApplication 8 from PyQt5.QtWidgets import QFormLayout 9 from PyQt5.QtWidgets import QLineEdit 10 from PyQt5.QtWidgets import QWidget 11 12 app = QApplication(sys.argv) 13 window = QWidget() 14 window.setWindowTitle('QFormLayout') 15 layout = QFormLayout() 16 layout.addRow('Name:', QLineEdit()) 17 layout.addRow('Age:', QLineEdit()) 18 layout.addRow('Job:', QLineEdit()) 19 layout.addRow('Hobbies:', QLineEdit()) 20 window.setLayout(layout) 21 window.show() 22 sys.exit(app.exec_()) Lines 15 to 20 do the hard work in this example. Notice that QFormLayout has a convenient method called .addRow(). You can use this method to add a two-widget row to the layout. The first argument of .addRow() should be a label, and the second argument should be any other widget that allows the user to enter or edit data. If you run this code, then you’ll get the following output: The above figure shows a GUI that uses a form layout. The first column contains labels to ask the user for some information. The second column shows widgets that allow the user to enter or edit the information you asked from them. Dialogs With PyQt, you can develop two types of GUI desktop applications. Depending on the class you use to create the main form or window, you’ll have one of the following: - A Main Window-Style application: The application’s main window inherits from QMainWindow. - A Dialog-Style application: The application’s main window inherits from QDialog. You’ll start with Dialog-Style applications first. In the next section, you’ll cover Main Window-Style applications. To develop a Dialog-Style application, you need to create a GUI class that inherits from QDialog, which is the base class of all dialog windows. A dialog window is always a top-level window that you can use as the main window for your Dialog-Style application. Note: Dialog windows are also commonly used in Main Window-Style applications for brief communication and interaction with the user. When dialog windows are used to communicate with the user, they may be: - Modal dialogs: block input to any other visible windows in the same application. You can display a modal dialog by calling .exec_(). - Modeless dialogs: operate independently of other windows in the same application. You can display a modeless dialog by using .show(). Dialog windows can also provide a return value and have default buttons (for example, OK and Cancel). A dialog is always a top-level widget. If it has a parent, then its default location is centered on top of the parent’s top-level widget. This kind of dialog will also share the parent’s taskbar entry. If you don’t set a parent for a given dialog, then the dialog will get its own entry in the system’s taskbar. Here’s an example of how you’d use QDialog to develop a Dialog-Style application: 1 # Filename: dialog.py 2 3 """Dialog-Style application.""" 4 5 import sys 6 7 from PyQt5.QtWidgets import QApplication 8 from PyQt5.QtWidgets import QDialog 9 from PyQt5.QtWidgets import QDialogButtonBox 10 from PyQt5.QtWidgets import QFormLayout 11 from PyQt5.QtWidgets import QLineEdit 12 from PyQt5.QtWidgets import QVBoxLayout 13 14 class Dialog(QDialog): 15 """Dialog.""" 16 def __init__(self, parent=None): 17 """Initializer.""" 18 super().__init__(parent) 19 self.setWindowTitle('QDialog') 20 dlgLayout = QVBoxLayout() 21 formLayout = QFormLayout() 22 formLayout.addRow('Name:', QLineEdit()) 23 formLayout.addRow('Age:', QLineEdit()) 24 formLayout.addRow('Job:', QLineEdit()) 25 formLayout.addRow('Hobbies:', QLineEdit()) 26 dlgLayout.addLayout(formLayout) 27 btns = QDialogButtonBox() 28 btns.setStandardButtons( 29 QDialogButtonBox.Cancel | QDialogButtonBox.Ok) 30 dlgLayout.addWidget(btns) 31 self.setLayout(dlgLayout) 32 33 if __name__ == '__main__': 34 app = QApplication(sys.argv) 35 dlg = Dialog() 36 dlg.show() 37 sys.exit(app.exec_()) This application is a bit more elaborate. Here’s what’s going on: - Line 14 creates a full class Dialogfor the GUI, which inherits from QDialog. - Line 20 assigns a QVBoxLayoutobject to dlgLaout. - Line 21 assigns a QVFormLayoutobject to formLayout. - Line 22 to 25 add widgets to formLayout. - Line 26 uses dlgLayoutto arrange all the widgets on the form. - Line 27 provides a convenient object to place the dialog buttons. - Lines 28 and 29 add two standard buttons: Okand Cancel. - Lines 33 to 37 wrap the boilerplate code in an if __name__ == '__main__':idiom. This is considered a best practice for Pythonistas. Note: If you look at line 26 in the code block above, then you’ll notice that layout managers can be nested inside one another. You can nest layouts by calling .addLayout() on the container layout and passing in the nested layout as an argument to this method. The code block above displays the following window: This is the GUI that you created using QFormLayout for the widgets and QVBoxLayout for the general application’s layout ( dlgLayout in line 20). Main Windows Most of the time, your GUI applications will be Main Window-Style. This means that they’ll have a menu bar, some toolbars, a status bar, and a central widget that will be the GUI’s main element. It’s also common that your apps will have several dialog windows to accomplish secondary actions that depend on user input. You’ll use the class QMainWindow to develop Main Window-Style applications. You need to inherit from QMainWindow to create your main GUI class. An instance of a class that derives from QMainWindow is considered to be a main window. QMainWindow provides a framework for building your application’s GUI. The class has its own built-in layout, which you can use to place the following: One menu bar is at the top of the window. The menu bar holds the application’s main menu. Several toolbars are on the sides of the window. Toolbars are suitable for holding tool buttons and other kinds of widgets such as QComboBox, QSpinBox, and more. One central widget is in the center of the window. The central widget can be of any type, or it can be a composite widget. Several dock widgets are around the central widget. Dock widgets are small, movable windows. One status bar is at the bottom of the window. The status bar shows information on the application’s general status. You can’t create a main window without first setting a central widget. You must have a central widget, even if it’s just a placeholder. When this is the case, you can use a QWidget object as your central widget. You can set the main window’s central widget with .setCentralWidget(). The main window’s layout will allow you to have only one central widget, but it can be a single or a composite widget. The following code example shows you how to use QMainWindow to create a Main Window-Style application: 1 # Filename: main_window.py 2 3 """Main Window-Style application.""" 4 5 import sys 6 7 from PyQt5.QtWidgets import QApplication 8 from PyQt5.QtWidgets import QLabel 9 from PyQt5.QtWidgets import QMainWindow 10 from PyQt5.QtWidgets import QStatusBar 11 from PyQt5.QtWidgets import QToolBar 12 13 class Window(QMainWindow): 14 """Main Window.""" 15 def __init__(self, parent=None): 16 """Initializer.""" 17 super().__init__(parent) 18 self.setWindowTitle('QMainWindow') 19 self.setCentralWidget(QLabel("I'm the Central Widget")) 20 self._createMenu() 21 self._createToolBar() 22 self._createStatusBar() 23 24 def _createMenu(self): 25 self.menu = self.menuBar().addMenu("&Menu") 26 self.menu.addAction('&Exit', self.close) 27 28 def _createToolBar(self): 29 tools = QToolBar() 30 self.addToolBar(tools) 31 tools.addAction('Exit', self.close) 32 33 def _createStatusBar(self): 34 status = QStatusBar() 35 status.showMessage("I'm the Status Bar") 36 self.setStatusBar(status) 37 38 if __name__ == '__main__': 39 app = QApplication(sys.argv) 40 win = Window() 41 win.show() 42 sys.exit(app.exec_()) Here’s how this code works: - Line 13 creates a class Windowthat inherits from QMainWindow. - Line 18 sets the window’s title. - Line 19 sets a QLabelas the central widget. - Lines 20 to 22 call private methods in the lines that follow in order to create different GUI elements: - Lines 24 to 26 create the main menu. - Lines 28 to 31 create the toolbar. - Lines 33 to 36 create the status bar. Note: When you implement different GUI components in their own method, you’re making your code more readable and more maintainable. This is not a requirement, however, so you’re free to organize your code in the way you like best. When you run the above code, you’ll see a window like the following: You can see that your Main Window-Style application has the following components: - One main menu called - One toolbar with a functional Exittool button - One central widget (a QLabelobject) - One status bar at the bottom of the window So far, you’ve covered some of the more important graphical components of PyQt5’s set of widgets. In the next two sections, you’ll cover some other important concepts related to PyQt GUI applications. Applications The most basic class you’ll use when developing PyQt GUI applications is QApplication. This class is at the core of any PyQt application. It manages the application’s control flow as well as its main settings. In PyQt, any instance of QApplication is considered to be an application. Every PyQt GUI application must have one QApplication object. Some of the application’s responsibilities include: - Handling initialization and finalization - Providing the event loop and event handling - Handling most of the system-wide and application-wide settings - Providing access to global information, such as the application’s directory, screen size, and so on - Parsing common command-line arguments - Defining the application’s look and feel - Providing localization capabilities These are just some of the core responsibilities of QApplication. As you can see, this is a fundamental class when it comes to developing PyQt GUI applications! One of the most important responsibilities of QApplication is to provide the event loop and the entire event handling mechanism. Let’s take a closer look at the event loop now. Event Loops GUI applications are event-driven. This means that functions and methods are executed in response to user actions like clicking on a button, selecting an item from a combo box, entering or updating the text in a text edit, pressing a key on the keyboard, and so on. These user actions are generally called events. Events are commonly handled by an event loop (also called the main loop). An event loop is an infinite loop in which all events from the user, the window system, and any other sources are processed and dispatched. The event loop waits for an event to occur and then dispatches it to perform some task. The event loop continues to work until the application is terminated. Event loops are used by all GUI applications. The event loop is kind of an infinite loop that waits for the occurrence of events. If an event happens, then the loop checks if the event is a Terminate event. In that case, the loop is terminated and the application exits. Otherwise, the event is sent to the application’s event queue for further processing, and the loop starts again. In PyQt, you can run the application’s event loop by calling .exec_() on the QApplication object. Note: PyQt was first developed to target Python 2, which already has an exec keyword. In earlier versions, an underscore was added to the end .exec_() to help avoid name conflicts. PyQt5 targets Python 3, which doesn’t have an exec keyword. Still, the library provides two methods that start the event loop: .exec_() .exec() This means that you can remove .exec_() from your code, and you can safely use .exec() instead. For an event to trigger a response action, you need to connect the event with the action you want to be executed. In PyQt5, you can establish that connection by using the signals and slots mechanism. You’ll cover these in the next section. Signals and Slots PyQt widgets act as event-catchers. This means that every widget can catch a specific number of events, like mouse clicks, keypresses, and so on. In response to these events, widgets always emit a signal, which is a kind of message that announces a change in its state. The signal on its own doesn’t perform any action. If you want a signal to trigger an action, then you need to connect it to a slot. This is the function or method that will perform an action whenever the connecting signal is emitted. You can use any Python callable (or callback) as a slot. If a signal is connected to a slot, then the slot is called whenever the signal is emitted. If a signal isn’t connected to any slot, then nothing happens and the signal is ignored. Here are some of the most useful features of this mechanism: - A signal can be connected to one or many slots. - A signal may also be connected to another signal. - A slot may be connected to one or many signals. You can use the following syntax to connect a signal to a slot: widget.signal.connect(slot_function) This will connect slot_function to widget.signal. Whenever signal is emitted, slot_function() will be called. This code shows you how to use the signals and slots mechanism: 1 # Filename: signals_slots.py 2 3 """Signals and slots example.""" 4 5 import sys 6 7 from PyQt5.QtWidgets import QApplication 8 from PyQt5.QtWidgets import QLabel 9 from PyQt5.QtWidgets import QPushButton 10 from PyQt5.QtWidgets import QVBoxLayout 11 from PyQt5.QtWidgets import QWidget 12 13 def greeting(): 14 """Slot function.""" 15 if msg.text(): 16 msg.setText("") 17 else: 18 msg.setText("Hello World!") 19 20 app = QApplication(sys.argv) 21 window = QWidget() 22 window.setWindowTitle('Signals and slots') 23 layout = QVBoxLayout() 24 25 btn = QPushButton('Greet') 26 btn.clicked.connect(greeting) # Connect clicked to greeting() 27 28 layout.addWidget(btn) 29 msg = QLabel('') 30 layout.addWidget(msg) 31 window.setLayout(layout) 32 window.show() 33 sys.exit(app.exec_()) In line 13, you create greeting(), which you’ll use as a slot. Then in line 26, you connect the button’s clicked signal to greeting(). This way, whenever the user clicks on the button, greeting() is called and msg will alternate between the message Hello World! and an empty string: When you click on Greet, the Hello World! message will appear and disappear on your screen. Note: Every widget has its own set of predefined signals. You can check them out on the widget’s documentation page. If your slot function needs to receive extra arguments, then you can pass them in by using functools.partial. For example, you can modify greeting() as follows: def greeting(who): """Slot function.""" if msg.text(): msg.setText('') else: msg.setText(f'Hello {who}') Now, greeting() needs to receive an argument called who. If you want to connect this new version of greeting() to the btn.clicked signal, then you can do something like this: btn.clicked.connect(functools.partial(greeting, 'World!')) For this code to work, you need to import functools first. The call to functools.partial() returns an object that behaves similarly to calling greeting() with who='World!'. Now, when the user clicks on the button, the message 'Hello World!' will be shown in the label as well as before. Note: You can also use lambda to connect a signal to a slot that requires extra arguments. For a practice exercise, try to code the above example using lambda instead of functools.partial(). The signals and slots mechanism is what you’ll use to give life to your PyQt5 GUI applications. This mechanism will allow you to turn user events into concrete actions. You can dive deeper into the signals and slots mechanism by taking a look at the PyQt5 documentation. Now you’ve finished covering the most important concepts of PyQt5. With this knowledge and the library’s documentation at hand, you’re ready to start developing your own GUI applications. In the next section, you’ll build your first fully-functional GUI application. Let’s go for it! Creating a Calculator With Python and PyQt In this section, you’re going to develop a calculator using the Model-View-Controller (MVC) design pattern. This pattern has three layers of code, each with different roles: The model takes care of your app’s business logic. It contains the core functionality and data. For your calculator, the model will handle the calculations. The view implements your app’s GUI. It hosts all the widgets the end-user would need to interact with the application. The view also receives user actions and events. For your calculator, the view will be the window you’ll see on your screen. The controller connects the model and the view to make the application work. User events (or requests) are sent to the controller, which puts the model to work. When the model delivers the requested result (or data) in the right format, the controller forwards it to the view. For your calculator, the controller will receive user events from the GUI, ask the model to perform calculations, and update the GUI with the result. Here’s a step-by-step MVC pattern for a GUI desktop application: - The user performs an action or request (event) on the view (GUI). - The view notifies the controller about the user’s action. - The controller gets the user’s request and queries the model for a response. - The model processes the controller query, performs the required operations, and returns an answer or result. - The controller receives the model’s answer and updates the view accordingly. - The user finally sees the requested result on the view. You’ll use this MVC design pattern to build your calculator. Creating the Skeleton You’ll start by implementing a basic skeleton for your application, called pycalc.py. You can find this script and the rest of the source code at the link below: Download Code: Click here to download the code you'll use to build a calculator in Python with PyQt in this tutorial. If you’d prefer to code the project on your own, then go ahead and create pycalc.py in your current working directory. Then, open the file in your code editor and type the following code: #!/usr/bin/env python3 # Filename: pycalc.py """PyCalc is a simple calculator built using Python and PyQt5.""" import sys # Import QApplication and the required widgets from PyQt5.QtWidgets from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QMainWindow from PyQt5.QtWidgets import QWidget __version__ = '0.1' __author__ = 'Leodanis Pozo Ramos' # self._centralWidget = QWidget(self) self.setCentralWidget(self._centralWidget) # Client code def main(): """Main function.""" # Create an instance of QApplication pycalc = QApplication(sys.argv) # Show the calculator's GUI view = PyCalcUi() view.show() # Execute the calculator's main loop sys.exit(pycalc.exec_()) if __name__ == '__main__': main() This script implements all the code you’ll need to run a basic GUI application. You’ll use this skeleton to build your calculator. Here’s how it works: Lines 10 to 12 import the required modules and classes from PyQt5.QtWidgets. Line 18 creates the GUI with the class PyCalcUi. Note that this class inherits from QMainWindow. Line 24 sets the window’s title to PyCalc. Line 25 uses .setFixedSize()to give the window a fixed size. This ensures that the user won’t be able to resize the window. Line 27 creates a QWidgetobject to play the role of a central widget. Remember that since your GUI class inherits from QMainWindow, you need a central widget. This object will be the parentfor the rest of the GUI component. Line 31 defines your calculator’s main function, which is considered a best practice. This function will be the entry point to the application. Inside main(), your program does the following: - Line 34 creates a QApplicationobject pycalc. - Line 37 shows the GUI with view.show(). - Line 39 runs the application’s event loop with pycalc.exec_(). When you run the script, the following window will appear on your screen: This is your GUI application skeleton. Completing the View The GUI you have at this point doesn’t really look like a calculator. Let’s finish the GUI by adding the display and buttons for the numbers. You’ll also add buttons for basic math operations and for clearing the display. First, you’ll need to add the following imports to the top of your file: from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QGridLayout from PyQt5.QtWidgets import QLineEdit from PyQt5.QtWidgets import QPushButton from PyQt5.QtWidgets import QVBoxLayout You’re going to use a QVBoxLayout for the calculator’s general layout. You’ll also use a QGridLayout object to arrange the buttons. Finally, you import QLineEdit for the display and QPushButton for the buttons. There should now be eight import statements at the top of your file. Now you can update the initializer for PyCalcUi: # and the general layout self.generalLayout = QVBoxLayout() self._centralWidget = QWidget(self) self.setCentralWidget(self._centralWidget) self._centralWidget.setLayout(self.generalLayout) # Create the display and the buttons self._createDisplay() self._createButtons() Here, you’ve added the highlighted lines of code. You’ll use a QVBoxLayout to place the display at the top and the buttons in a grid layout at the bottom. The calls to ._createDisplay() and ._createButtons() won’t work, because you haven’t yet implemented those methods. Let’s fix that by coding ._createDisplay(): class PyCalcUi(QMainWindow): # Snip def _createDisplay(self): """Create the display.""" # Create the display widget self.display = QLineEdit() # Set some display's properties self.display.setFixedHeight(35) self.display.setAlignment(Qt.AlignRight) self.display.setReadOnly(True) # Add the display to the general layout self.generalLayout.addWidget(self.display) To create the display widget, you use a QLineEdit object. Then you set the following display properties: - The display has a fixed height of 35 pixels. - The display shows the text as left-aligned. - The display is set to read-only to avoid direct editing. The last line adds the display to the calculator’s general layout with generalLayout.addWidget(). Next, you’ll implement ._createButtons() to create buttons for your calculator. You’ll use a dictionary to hold each button’s text and position on the grid. You’ll also use QGridLayout to arrange the buttons on the calculator’s window. The final code will look like this: class PyCalcUi(QMainWindow): # Snip def _createButtons(self): """Create the buttons.""" self.buttons = {} buttonsLayout = QGridLayout() # Button text | position on the QGridLayout buttons = {'7': (0, 0), '8': (0, 1), '9': (0, 2), '/': (0, 3), 'C': (0, 4), '4': (1, 0), '5': (1, 1), '6': (1, 2), '*': (1, 3), '(': (1, 4), '1': (2, 0), '2': (2, 1), '3': (2, 2), '-': (2, 3), ')': (2, 4), '0': (3, 0), '00': (3, 1), '.': (3, 2), '+': (3, 3), '=': (3, 4), } # Create the buttons and add them to the grid layout for btnText, pos in buttons.items(): self.buttons[btnText] = QPushButton(btnText) self.buttons[btnText].setFixedSize(40, 40) buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1]) # Add buttonsLayout to the general layout self.generalLayout.addLayout(buttonsLayout) You first create an empty dictionary self.buttons to hold the calculator buttons. Then, you create a temporary dictionary to store their labels and relative positions on the grid layout ( buttonsLayout). Inside the for loop, you create the buttons and add them to both self.buttons and buttonsLayout. Every button will have a fixed size of 40x40 pixels, which you set with .setFixedSize(40, 40). Note: When it comes to widget size, you’ll rarely find measurement units in the PyQt documentation. It’s assumed that the measurement unit is pixels (except for QPrinter, which uses points). Now, the calculator’s GUI (or view) can show the display and the buttons. But there’s still no way to update the information shown in the display. You can fix this by adding a few extra methods: .setDisplayText()to set and update the display’s text .displayText()to get the current display’s text .clearDisplay()to clear the display’s text These methods will form the GUI public interface and complete the view class for your Python calculator. Here’s a possible implementation: class PyCalcUi(QMainWindow): # Snip def setDisplayText(self, text): """Set display's text.""" self.display.setText(text) self.display.setFocus() def displayText(self): """Get display's text.""" return self.display.text() def clearDisplay(self): """Clear the display.""" self.setDisplayText('') Here’s what each function does: .setDisplayText()uses .setText()to set and update the display’s text, and .setFocus()to set the cursor’s focus on the display. .displayText()is a getter method that returns the display’s current text. When the user clicks on the equals sign ( =), the program will use the return value of .displayText()as the math expression to be evaluated. .clearDisplay()sets the display’s text to an empty string ( '') so the user can introduce a new math expression. Now your calculator’s GUI is ready! When you run the application, you’ll see a window like this one: You’ve completed the calculator’s GUI interface. However, if you try to do some calculations, then you’ll notice that the calculator doesn’t do anything just yet. That’s because you haven’t implemented the model or the controller. Next, you’ll add a basic controller class to start giving life to your calculator. Creating a Basic Controller In this section, you’re going to code the calculator’s controller class. This class will connect the view to the model. You’ll use the controller class to make the calculator perform actions in response to user events. You’ll start with the following import: from functools import partial At the top of pycalc.py, you import partial() to connect signals with methods that need to take extra arguments. Your controller class needs to perform three main tasks: - Access the GUI’s public interface - Handle the creation of math expressions - Connect button clickedsignals with the appropriate slots This will ensure that your calculator is working correctly. Here’s how you code the controller class: # Create a Controller class to connect the GUI and the model class PyCalcCtrl: """PyCalc Controller class.""" def __init__(self, view): """Controller initializer.""" self._view = view # Connect signals and slots self._connectSignals() def _buildExpression(self, sub_exp): """Build expression."""['C'].clicked.connect(self._view.clearDisplay) The first thing you do is give PyCalcCtrl an instance of the view PyCalcUi. You’ll use this instance to gain full access to the view’s public interface. Next, you create ._buildExpression() to handle the creation of math expressions. This method also updates the calculator’s display in response to user input. Finally, you use ._connectSignals() to connect the printable buttons with ._buildExpression(). This allows your users to create math expressions by clicking on the calculator’s buttons. In the last line, you connect the clear button ( C) to ._view.clearDisplay(). This method will clear up the text on the display. For this new controller class to work, you need to update main(): # Client code def main(): """Main function.""" # Create an instance of QApplication pycalc = QApplication(sys.argv) # Show the calculator's GUI view = PyCalcUi() view.show() # Create instances of the model and the controller PyCalcCtrl(view=view) # Execute calculator's main loop sys.exit(pycalc.exec_()) This code creates an instance of PyCalcCtrl(view=view) with the view passed in as an argument. This will initialize the controller and connect the signals and slots to give your calculator some functionality. If you run the application, then you’ll see something like the following: As you can see, the calculator already has some useful functionalities! Now, you can build math expressions by clicking on the buttons. Notice that the equals sign ( =) doesn’t work yet. To fix this, you need to implement the calculator’s model. Implementing the Model The model is the layer of code that takes care of the business logic. In this case, the business logic is all about basic math calculations. Your model will evaluate the math expressions introduced by your users. Since the model needs to handle errors, you’re going to define the following global constant: ERROR_MSG = 'ERROR' This is the message the user will see if they introduce an invalid math expression. Your model will be a single function: # Create a Model to handle the calculator's operation def evaluateExpression(expression): """Evaluate an expression.""" try: result = str(eval(expression, {}, {})) except Exception: result = ERROR_MSG return result Here, you use eval() to evaluate a string as an expression. If this is successful, then you’ll return the result. Otherwise, you’ll return the error message. Note that this function isn’t perfect. It has a couple of important issues: - The try...exceptblock doesn’t catch any specific exception, which is not a best practice in Python. - The function is based on the use of eval(), which can lead to some serious security issues. The general advice is to only use eval()on trusted input. You’re free to rework the function to make it more reliable and secure. For this tutorial, you’ll use the function as-is. Completing the Controller Once you’ve completed the calculator’s model, you can finish the controller. The final version of PyCalcCtrl will include logic to process the calculations and to make sure the equals sign ( =) works correctly: # Create a Controller class to connect the GUI and the model class PyCalcCtrl: """PyCalc's Controller.""" def __init__(self, model, view): """Controller initializer.""" self._evaluate = model self._view = view # Connect signals and slots self._connectSignals() def _calculateResult(self): """Evaluate expressions.""" result = self._evaluate(expression=self._view.displayText()) self._view.setDisplayText(result) def _buildExpression(self, sub_exp): """Build expression.""" if self._view.displayText() == ERROR_MSG: self._view.clearDisplay()['='].clicked.connect(self._calculateResult) self._view.display.returnPressed.connect(self._calculateResult) self._view.buttons['C'].clicked.connect(self._view.clearDisplay) The new lines of code are highlighted. First, you add a new parameter to the init function. Now the class receives instances from both the model and the view. Then in ._calculateResult(), you take the display’s content, evaluate it as a math expression, and finally show the result in the display. You also add an if statement to ._buildExpression() to check if an error has occurred. If so, then you clear the display and start over with a new expression. Finally, you add two more connections inside ._connectSignals(). The first enables the equals sign ( =). The second ensures that when the user hits Enter, the calculator will process the expression as expected. For all this code to work, you need to update main(): # Client code def main(): """Main function.""" # Create an instance of `QApplication` pycalc = QApplication(sys.argv) # Show the calculator's GUI view = PyCalcUi() view.show() # Create instances of the model and the controller model = evaluateExpression PyCalcCtrl(model=model, view=view) # Execute calculator's main loop sys.exit(pycalc.exec_()) Here, your model holds a reference to evaluateExpression(). In addition, PyCalcCtrl() now receives two arguments: the model and the view. Running the Calculator Now that you’ve finished the code, it’s time for a test! If you run the application, then you’ll see something like this: To use PyCalc, enter a valid math expression with your mouse. Then, press Enter or click on the equals sign ( =) to see the result on the calculator’s display. Congrats! You’ve developed your first fully-functional GUI desktop application with Python and PyQt! Additional Tools PyQt5 offers quite a useful set of additional tools to help you build solid, modern, and full-featured GUI applications. Here are some of the most remarkable tools you can use: - The Qt Designer - The set of internationalization tools - The PyQt5 resource system Qt Designer is the Qt tool for designing and building graphical user interfaces. You can use it to design widgets, dialogs, or complete main windows by using on-screen forms and a drag-and-drop mechanism. The following figure shows some of the Qt Designer’s features: Qt Designer uses XML .ui files to store your GUI designs. You can load them with QUiLoader. PyQt includes a module called uic to help with this. You can also convert the .ui file content into Python code with a command-line tool called pyuic5. PyQt5 also provides a comprehensive set of tools for the internationalization of apps into local languages. pylupdate5 creates and updates translation ( .ts) files. Then, Qt Linguist updates the generated .ts files with translations of the strings. It also releases the .ts files as .qm files. These .qm files are compact binary equivalents that can be used directly by the application. Finally, you can use the PyQt5 resource system, which is a facility for embedding resources such as icons and translation files. To use this tool, you need to generate a .qrc file. This is an XML file that’s used to specify which resource files are to be embedded. Once you have this file ready, you can use pyrcc5 to generate a Python module that contains the embedded resources. Conclusion Graphical User Interface (GUI) desktop applications still hold a substantial share of the software development market. Python offers a handful of frameworks and libraries that can help you develop modern and robust GUI applications. In this tutorial, you learned how to use PyQt, which is arguably one of the most popular and solid libraries for GUI desktop application development in Python. Now you know how to effectively use both Python and PyQt to build modern GUI desktop applications. You’re now able to: - Create Graphical User Interfaces with Python and PyQt - Connect user events to concrete actions in your application - Create fully-functional GUI desktop applications to solve real-world problems Now you can use Python and PyQt to give life to your desktop GUI applications! You can get the source code for the calculator project and all code examples at the link below: Download Code: Click here to download the code you'll use to build a calculator in Python with PyQt in this tutorial. Further Reading If you want to dive deeper into PyQt and its related tools, then you can take a look at some of these resources: - PyQt5 Documentation - PyQt4 Documentation - Qt v5 Documentation - PyQt Wiki - Rapid GUI Programming with Python and Qt - Qt Designer Manual - Qt for Python ( PySide2) documentation Although the PyQt5 Documentation is the first resource listed here, some important parts are still missing or incomplete. Fortunately, you can use the PyQt4 Documentation to fill in the blanks. The Class Reference is particularly useful for gaining a complete understanding of widgets and classes. If you’re using the PyQt4 documentation as a reference for PyQt5 classes, then bear in mind that the classes will be slightly different and may behave differently, too. Another option would be to use the original Qt v5 Documentation and its Class Reference instead. In this case, you may need some background in C++ to properly understand the code samples.
https://realpython.com/python-pyqt-gui-calculator/
CC-MAIN-2019-47
refinedweb
10,466
58.48
# .NET Core 3 for Windows Desktop In September, we released .NET Core support for building Windows desktop applications, including WPF and Windows Forms. Since then, we have been delighted to see so many developers share their stories of migrating desktop applications (and controls libraries) to .NET Core. We constantly hear stories of .NET Windows desktop developers powering their business with WPF and Windows Forms, especially in scenarios where the desktop shines, including: * UI-dense forms over data (FOD) applications * Responsive low-latency UI * Applications that need to run offline/disconnected * Applications with dependencies on custom device drivers This is just the beginning for Windows application development on .NET Core. Read on to learn more about the benefits of .NET Core for building Windows applications. ![](https://habrastorage.org/r/w1560/webt/zr/wf/ns/zrwfnstt7l3hyx-pzo_8bexswbu.png) Why Windows desktop on .NET Core? --------------------------------- .NET Core (and in the future .NET 5 that is built on top of .NET Core) will be the future of .NET. We are committed to support .NET Framework for years to come, however it will not be receiving any new features, those will only be added to .NET Core (and eventually .NET 5). To improve Windows desktop stacks and enable .NET desktop developers to benefit from all the updates of the future, we brought Windows Forms and WPF to .NET Core. They will still remain Windows-only technologies because there are tightly coupled dependencies to Windows APIs. But .NET Core, besides being cross-platform, has many other features that can enhance desktop applications. First of all, all the runtime improvements and language features will be added only to .NET Core and in the future to .NET 5. A good example here is C# 8 that became available in .NET Core 3.0. Besides, the .NET Core versions of Windows Forms and WPF will become a part of the .NET 5 platform. So, by porting your application to .NET Core today you are preparing them for .NET 5. Also, .NET Core brings deployment flexibility for your applications with new options that are not available in .NET Framework, such as: * Side-by-side deployment. Now you can have multiple .NET Core versions on the same machine and can choose which version each of your apps should target. * Self-contained deployment. You can deploy the .NET Core platform with your applications and become completely independent of your end users environment – your app has everything it needs to run on any Windows machine. * Smaller app sizes. In .NET Core 3 we introduced a new feature called linker (also sometimes referred to as trimmer), that will analyze your code and include in your self-contained deployment only those assemblies from .NET Core that are needed for your application. That way all platform parts that are not used for your case will be trimmed out. * Single .exe files. You can package your app and the .NET Core platform all in one .exe file. * Improved runtime performance. .NET Core has many performance optimizations compared to .NET Framework. When you think about the history of .NET Core, built initially for web and server workloads, it helps to understand if your application may see noticeable benefits from the runtime optimizations. Specifically, desktop applications with heavy dependencies on File I/O, networking, and database operations will likely see improvements to performance *for those scenarios*. Some areas where you may not notice much change are in UI rendering performance or application startup performance. By setting the properties ,  and  in the publishing profile you’ll be able to deploy a trimmed self-contained application as a single .exe file as it is shown in the example below. ``` Exe netcoreapp3.0 true win-x64 true ``` Differences between .NET Framework desktop and .NET Core desktop ---------------------------------------------------------------- While developing desktop applications, you won’t notice much difference between .NET Framework and .NET Core versions of WPF and Windows Forms. A part of our effort was to provide a functional parity between these platforms in the desktop area and enhance the .NET Core experience in the future. WPF applications are fully supported on .NET Core and ready for you to use, while we are working on minor updates and improvements. For Windows Forms the runtime part is fully ported to .NET Core and the team is working on the Windows Forms Designer. We are planning to get it ready by the fourth quarter of 2020 and for now you can check out the Preview version of the designer in [Visual Studio](https://visualstudio.microsoft.com/vs/preview/) 16.4 Preview 3 or later. Don’t forget to set the checkbox in the Tools->Options->Preview Features->Use the Preview of Windows Forms designer for .NET Core apps and restart the Visual Studio. Please keep in mind that the experience is limited for now since the work on it is in progress. ### Breaking changes There are a few [breaking changes](https://docs.microsoft.com/dotnet/core/compatibility/framework-core) between .NET Framework and .NET Core but most of the code related to Windows Forms and WPF areas was ported to Core as-is. If you were using such components as WCF Client, Code Access Security, App Domains, Interop and Remoting, you will need to refactor your code if you want to switch to .NET Core. Another thing to keep in mind – the default output paths on .NET Core is different from on .NET Framework, so if you have some assumptions in your code about file/folder structure of the running app then it’ll probably fail at runtime. Also, there are changes in how you configure the .NET features. .NET Core instead of `machine.config` file uses `.runtimeconfig.json` file that comes with an application and has the same general purpose and similar information. Some configurations such as `system.diagnostics`, `system.net`, or `system.servicemodel` are not supported, so an app config file will fail to load if it contains any of these sections. This change affects `System.Diagnostics` tracing and WCF client scenarios which were commonly configured using XML configuration previously. In .NET Core you’ll need to configure them in code instead. To change behaviors without recompiling, consider setting up tracing and WCF types using values loaded from a `Microsoft.Extensions.Configuration` source or from `appSettings`. You can find more information on differences between .NET Core and .NET Framework in the [documentation](https://docs.microsoft.com/dotnet/core/porting/net-framework-tech-unavailable). Getting Started --------------- Check out these short video tutorials: * [Getting started with WPF on .NET Core](https://www.youtube.com/watch?v=Y4pthq_zGvI&list=PLdo4fOcmZ0oV7n106SEWwWPy4WVjpl3Fj&index=4&t=6s) * [Getting started with Windows Forms on .NET Core](https://www.youtube.com/watch?v=a66wsCRSgDk&list=PLdo4fOcmZ0oV7n106SEWwWPy4WVjpl3Fj&index=3&t=12s) * [Differences between .NET Core and .Net Framework and what to choose for your application](https://www.youtube.com/watch?v=BPWTdQ7rh2w&list=PLdo4fOcmZ0oV7n106SEWwWPy4WVjpl3Fj&index=2&t=67s) Porting from .NET Framework to .NET Core ---------------------------------------- First of all, run the [Portability Analyzer](https://github.com/Microsoft/dotnet-apiport-ui/releases/download/1.1/PortabilityAnalyzer.zip) and if needed, update your code to get a 100% compatibility with .NET Core. Here are [instructions on using the Portability Analyzer](https://devblogs.microsoft.com/dotnet/are-your-windows-forms-and-wpf-applications-ready-for-net-core-3-0/). We recommend to use a source control or to backup your code before you make any changes to your application in case the refactoring would not go the way you want, and you decide to go back to your initial state. When your application is fully compatible with .NET Core, you are ready to port it. As a starting point, you can try out a tool we created to help automate converting your .NET Framework project(s) to .NET Core – [try-convert](https://github.com/dotnet/try-convert). It’s important to remember that this tool is just a starting point in your journey to .NET Core. It is also not a supported Microsoft product. Although it can help you with some of the mechanical aspects of migration, it will not handle all scenarios or project types. If your solution has projects that the tool rejects or fails to convert, you’ll have to port by hand. No worries, we have plenty of tutorials on how to do it (in the end of this section). The try-convert tool will attempt to migrate your old-style project files to the new SDK-style and retarget applicable projects to .NET Core. For your libraries we leave it up to you to make a call regarding the platform: weather you’d like to target .NET Core or .NET Standard. You can specify it in your project file by updating the value for . Libraries without .NET Core-specific dependencies like WPF or Windows Forms may benefit from targeting .NET Standard: ``` netstandard2.1 ``` so that they can be used by callers targeting many different .NET Platforms. On the other hand, if a library uses a feature that requires .NET Core (like Windows desktop UI APIs), it’s fine for the library to target .NET Core: ``` netcoreapp3.0 ``` try-convert is a global tool that you can [install](https://github.com/dotnet/try-convert/releases) on your machine, then you can call from CLI: ``` C:\> try-convert -p ``` or ``` C:\> try-convert -w ``` As previously mentioned, if the try-convert tool did not work for you, here are materials on how to port your application by hand. **Videos** * [Simple porting case](https://sec.ch9.ms/ch9/beca/05683ec4-e8f8-4415-9009-046352a4beca/on.NET_porting_high.mp4) * [Advanced porting case](https://www.youtube.com/playlist?list=PLReL099Y5nRdG-LQ6OZSPECF-eXjgFNrW) **Documentation** * [Simple porting case](https://devblogs.microsoft.com/dotnet/porting-desktop-apps-to-net-core/) * Advanced porting case ([Part 1](https://devblogs.microsoft.com/dotnet/migrating-a-sample-wpf-app-to-net-core-3-part-1/), [Part 2](https://devblogs.microsoft.com/dotnet/migrating-a-sample-wpf-app-to-net-core-3-part-2/)) * [Overview of the porting process](https://docs.microsoft.com/en-us/dotnet/core/porting/)
https://habr.com/ru/post/475064/
null
null
1,673
51.24
Infinite Space for Sins of a Solar Empire: Rebellion. The mod enhances the overal look and feel of the game by adding a ton of new planets and planet types, planet bonuses, rendering, tweaks and much more! That's no moon! Oh wait, yes it is.. Currently I'm working on moons for planets: they are just eye candy and sadly don't orbit the planet. However, I'm planning to attach special planet bonuses for planets with moons, but I don't know what. Any feedback would be nice! Regarding last week's media update: I think I'm going to make several textures (mostly desert/ice) for pirate planets (normal/dwarf) and give them a negative planet bonus "Corruption" downgrading several stats of the planet. Tadaaa! i like it, but is there no way for you to make them orbit? talk with the developer from mealstrom, i think he knows how to do it. Yeah it's possible, just don't know how :) I've some models from another mod that orbit but the orbit is a bit to short so it's in the gravity well, meaning ships can fly through the moons, which is a deal breaker You do it as a particle effect. All you would need to do is increase the radius and make the effect part of the planet bonus. I have no experience with particle fx at all :D for the bonus what about certain moons are habitable which increase planet pop and some are mineral rich increase resource income and maybe others are tactical moons increasing amount of defenses around the gravity well? Yeah was thinking that too for the planet population but there's no way in selecting the moon or creating planet elevators on them (the space cars) No need for planet elevators or selecting the moons, just add the bonuses when there's a moon around the planet, and add 8-12 more tactical slots, since they can use the moon as a control centre which allows for more tactical slots. def pop bonus... maybe a tides bonus that increases... um... some kind of production. like increas in food or something so it makes more credits Nah... I don't think tides is a good idea... cool
http://www.moddb.com/mods/infinite-space/images/planets-with-moons
CC-MAIN-2015-32
refinedweb
379
69.01
07 May 2012 09:21 [Source: ICIS news] (recasts throughout, adds details) SINGAPORE (ICIS)--A fire that broke out at a Bangkok Synthetics’ (BST) facility at Map Ta Phut in Thailand’s Rayong province over the weekend killed at least 11 people and injured 141 more, the Thai producer said on Monday. The blaze broke out at toluene vessel inside its facility at around 15:20 hours local time (08:20 GMT) on 5 May, the company said in a statement posted on its website. The fire was under control at around 18:00 hours local time, it said. ?xml:namespace> BST’s units in Map Ta Phut can produce 140,000 tonnes/year of butadiene (BD), 55,000 tonnes/year of MTBE, 55,000 tonnes/year of butane LPG, 40,000 tonnes/year of C4 raffinate (isobutylene) and 35,000 tonnes/year of butene-1, according to the company's website. “At the time of the incident, during a heavy storm, the facility was in full shut down and the process had been previously cleaned using toluene to dry out moisture,” the company said. “This is the last step in the shutdown procedure during a product grade switching process,” it added. The cause of the fire is still under investigation, BST said. Toluene is a solvent used in synthetic rubber production and it is not classified as toxic or carcinogenic, according to the firm. “The level of toluene released from this incident is not harmful and not carcinogenic but can cause irritation and rash,” BST said. The closure of the BST facility has not affected paraxylene (PX) and purified terephthalic acid (PTA) producers at the Map Ta Phut industrial estate, with Indorama Petrochem Ltd running its 700,000 tonne/year PTA unit, which is a stone-throw away from the BST plant, normally on Monday. A source from PTT Global Chemical (PTTGC), meanwhile, said operations at its PX units in Map Ta Phut were unaffected by the explosion as its facilities are not located within close proximity from the blast site. PTTGC operates two PX units in Map Ta Phut with a combined nameplate capacity of 1.17m tonnes/year. With additional reporting by Bohan L
http://www.icis.com/Articles/2012/05/07/9557071/thailands-bangkok-synthetics-fire-kills-11-injures-141.html
CC-MAIN-2015-14
refinedweb
367
53.24
Common issues¶ This section has examples of cases when you need to update your code to use static typing, and ideas for working around issues if mypy doesn’t work as expected. Statically typed code is often identical to normal Python code, but sometimes you need to do things slightly differently. Can’t install mypy using pip¶ If installation fails, you’ve probably hit one of these issues: - Mypy needs Python 3.3 or later to run. - You may have to run pip like this: python3 -m pip install mypy. No errors reported for obviously wrong code¶ There are several common reasons why obviously wrong code is not flagged as an error. The function containing the error is not annotated. Functions that do not have any annotations (neither for any argument nor for the return type) are not type-checked, and even the most blatant type errors (e.g. 2 + 'a') pass silently. The solution is to add annotations. Example: def foo(a): return '(' + a.split() + ')' # No error! This gives no error even though a.split()is “obviously” a list (the author probably meant a.strip()). The error is reported once you add annotations: def foo(a: str) -> str: return '(' + a.split() + ')' # error: Unsupported operand types for + ("str" and List[str]) If you don’t know what types to add, you can use Any, but beware: One of the values involved has type ``Any``. Extending the above example, if we were to leave out the annotation for a, we’d get no error: def foo(a) -> str: return '(' + a.split() + ')' # No error! The reason is that if the type of ais unknown, the type of a.split()is also unknown, so it is inferred as having type Any, and it is no error to add a string to an Any. If you’re having trouble debugging such situations, reveal_type() might come in handy. Note that sometimes library stubs have imprecise type information, e.g. the pow()builtin returns Any(see typeshed issue 285 for the reason). Some imports may be silently ignored. Another source of unexpected Anyvalues are the “–ignore-missing-imports” and “–follow-imports=skip” flags. When you use --ignore-missing-imports, any imported module that cannot be found is silently replaced with Any. When using --follow-imports=skipthe same is true for modules for which a .pyfile is found but that are not specified on the command line. (If a .pyistub is found it is always processed normally, regardless of the value of --follow-imports.) To help debug the former situation (no module found at all) leave out --ignore-missing-imports; to get clarity about the latter use --follow-imports=error. You can read up about these and other useful flags in The mypy command line. Spurious errors and locally silencing the checker¶ You can use a # type: ignore comment to silence the type checker on a particular line. For example, let’s say our code is using the C extension module frobnicate, and there’s no stub available. Mypy will complain about this, as it has no information about the module: import frobnicate # Error: No module "frobnicate" frobnicate.start() You can add a # type: ignore comment to tell mypy to ignore this error: import frobnicate # type: ignore frobnicate.start() # Okay! The second line is now fine, since the ignore comment causes the name frobnicate to get an implicit Any type. Note The # type: ignore comment will only assign the implicit Any type if mypy cannot find information about that particular module. So, if we did have a stub available for frobnicate then mypy would ignore the # type: ignore comment and typecheck the stub as usual. Types of empty collections¶ You often need to specify the type when you assign an empty list or dict to a new variable, as mentioned earlier: a = [] # type: List[int] Without the annotation mypy can’t always figure out the precise type of a. You can use a simple empty list literal in a dynamically typed function (as the type of a would be implicitly Any and need not be inferred), if type of the variable has been declared or inferred before, or if you perform a simple modification operation in the same scope (such as append for a list): a = [] # Okay because followed by append, inferred type List[int] for i in range(n): a.append(i * i) However, in more complex cases an explicit type annotation can be required (mypy will tell you this). Often the annotation can make your code easier to understand, so it doesn’t only help mypy but everybody who is reading the code! Redefinitions with incompatible types¶ Each name within a function only has a single ‘declared’ type. You can reuse for loop indices etc., but if you want to use a variable with multiple types within a single function, you may need to declare it with the Any type. def f() -> None: n = 1 ... n = 'x' # Type error: n has type int Note This limitation could be lifted in a future mypy release. Note that you can redefine a variable with a more precise or a more concrete type. For example, you can redefine a sequence (which does not support sort()) as a list and sort it in-place: def f(x: Sequence[int]) -> None: # Type of x is Sequence[int] here; we don't know the concrete type. x = list(x) # Type of x is List[int] here. x.sort() # Okay! Invariance vs covariance¶ Most mutable generic collections are invariant, and mypy considers all user-defined generic classes invariant by default (see Variance of generic types for motivation). This could lead to some unexpected errors when combined with type inference. For example: class A: ... class B(A): ... lst = [A(), A()] # Inferred type is List[A] new_lst = [B(), B()] # inferred type is List[B] lst = new_lst # mypy will complain about this, because List is invariant Possible strategies in such situations are: Use an explicit type annotation: new_lst: List[A] = [B(), B()] lst = new_lst # OK Make a copy of the right hand side: lst = list(new_lst) # Also OK Use immutable collections as annotations whenever possible: def f_bad(x: List[A]) -> A: return x[0] f_bad(new_lst) # Fails def f_good(x: Sequence[A]) -> A: return x[0] f_good(new_lst) # OK Declaring a supertype as variable type¶ Sometimes the inferred type is a subtype (subclass) of the desired type. The type inference uses the first assignment to infer the type of a name (assume here that Shape is the base class of both Circle and Triangle): shape = Circle() # Infer shape to be Circle ... shape = Triangle() # Type error: Triangle is not a Circle You can just give an explicit type for the variable in cases such the above example: shape = Circle() # type: Shape # The variable s can be any Shape, # not just Circle ... shape = Triangle() # OK Complex type tests¶ Mypy can usually infer the types correctly when using isinstance() type tests, but for other kinds of checks you may need to add an explicit type cast: def f(o: object) -> None: if type(o) is int: o = cast(int, o) g(o + 1) # This would be an error without the cast ... else: ... Note Note that the object type used in the above example is similar to Object in Java: it only supports operations defined for all objects, such as equality and isinstance(). The type Any, in contrast, supports all operations, even if they may fail at runtime. The cast above would have been unnecessary if the type of o was Any. Mypy can’t infer the type of o after the type() check because it only knows about isinstance() (and the latter is better style anyway). We can write the above code without a cast by using isinstance(): def f(o: object) -> None: if isinstance(o, int): # Mypy understands isinstance checks g(o + 1) # Okay; type of o is inferred as int here ... Type inference in mypy is designed to work well in common cases, to be predictable and to let the type checker give useful error messages. More powerful type inference strategies often have complex and difficult-to-predict failure modes and could result in very confusing error messages. The tradeoff is that you as a programmer sometimes have to give the type checker a little help. Python version and system platform checks¶ Mypy supports the ability to perform Python version checks and platform checks (e.g. Windows vs Posix), ignoring code paths that won’t be run on the targeted Python version or platform. This allows you to more effectively typecheck code that supports multiple versions of Python or multiple operating systems. More specifically, mypy will understand the use of sys.version_info and sys.platform checks within if/elif/else statements. For example: import sys # Distinguishing between different versions of Python: if sys.version_info >= (3, 5): # Python 3.5+ specific definitions and imports elif sys.version_info[0] >= 3: # Python 3 specific definitions and imports else: # Python 2 specific definitions and imports # Distinguishing between different operating systems: if sys.platform.startswith("linux"): # Linux-specific code elif sys.platform == "darwin": # Mac-specific code elif sys.platform == "win32": # Windows-specific code else: # Other systems Note Mypy currently does not support more complex checks, and does not assign any special meaning when assigning a sys.version_info or sys.platform check to a variable. This may change in future versions of mypy. By default, mypy will use your current version of Python and your current operating system as default values for sys.version_info and sys.platform. To target a different Python version, use the --python-version X.Y flag. For example, to verify your code typechecks if were run using Python 2, pass in --python-version 2.7 from the command line. Note that you do not need to have Python 2.7 installed to perform this check. To target a different operating system, use the --platform PLATFORM flag. For example, to verify your code typechecks if it were run in Windows, pass in --platform win32. See the documentation for sys.platform for examples of valid platform parameters. Displaying the type of an expression¶ You can use reveal_type(expr) to ask mypy to display the inferred static type of an expression. This can be useful when you don’t quite understand how mypy handles a particular piece of code. Example: reveal_type((1, 'hello')) # Revealed type is 'Tuple[builtins.int, builtins.str]' Note reveal_type is only understood by mypy and doesn’t exist in Python, if you try to run your program. You’ll have to remove any reveal_type calls before you can run your code. reveal_type is always available and you don’t need to import it. Import cycles¶ An import cycle occurs where module A imports module B and module B imports module A (perhaps indirectly, e.g. A -> B -> C -> A). Sometimes in order to add type annotations you have to add extra imports to a module and those imports cause cycles that didn’t exist before. If those cycles become a problem when running your program, there’s a trick: if the import is only needed for type annotations in forward references (string literals) or comments, you can write the imports inside if TYPE_CHECKING: so that they are not executed at runtime. Example: File foo.py: from typing import List, TYPE_CHECKING if TYPE_CHECKING: import bar def listify(arg: 'bar.BarClass') -> 'List[bar.BarClass]': return [arg] File bar.py: from typing import List from foo import listify class BarClass: def listifyme(self) -> 'List[BarClass]': return listify(self) Note The TYPE_CHECKING constant defined by the typing module is False at runtime but True while type checking. Python 3.5.1 doesn’t have typing.TYPE_CHECKING. An alternative is to define a constant named MYPY that has the value False at runtime. Mypy considers it to be True when type checking. Here’s the above example modified to use MYPY: from typing import List MYPY = False if MYPY: import bar def listify(arg: 'bar.BarClass') -> 'List[bar.BarClass]': return [arg]
http://mypy.readthedocs.io/en/latest/common_issues.html
CC-MAIN-2017-26
refinedweb
1,999
62.88
I’m having some trouble with the ticket URLs contained in the mail sent to queue watchers. They look like this: They work fine when my browser is running and I’m already logged into RT. When I’m not logged in, RT displays the log-in screen (obviously), but after logging in, RT says “No ticket specified”. I guess this is because the log-in form is sent as a POST request, like this: POST /Ticket/Display.html?id=42 HTTP/1.1 [some header lines removed] User-Agent: iCab/2.7.1 (Macintosh; I; PPC) Content-Type: application/x-www-form-urlencoded Content-Length: [removed to protect the password] user=sflothow&pass= So RT (or Mason, or whatever) ignores the “?id=42” part of the URL because it’s a POST request, and the POST data doesn’t contain the ticket ID. I’ve verified this with iCab/2.7.1 on MacOS 8.6 and IE/6 on Win2K; RT is 2.0.13 (FCGI) on Apache 1.3. Can someone reproduce this problem on their system? Sebastian Flothow sebastian@flothow.de #include <stddisclaimer.h>
https://forum.bestpractical.com/t/ticket-urls-dont-work-when-logged-out/7596
CC-MAIN-2020-45
refinedweb
188
69.07
First time here? Check out the FAQ! I'm integrating data from a remote SAP system over SOAP services. The SAP services WSDL contains Policy elements. At runtime the remote call fails with PolicyException: None of the policy alternatives can be satisfied. Does anybody know how to call such a service? Policy PolicyException: None of the policy alternatives can be satisfied. asked 11.04.2018 at 05:44 SupportIvyTeam ♦♦ 1.3k●94●113●119 accept rate: 77% 7.1.0 and newer: You have two possibilities, when using Apache CXF as your client library: Apache CXF Ignore all policies: Many policies are optional and can be completely ignored. You can do this bis adding the feature IgnoreAllPoliciesFeature to your client web service configuration. IgnoreAllPoliciesFeature Ignore some policies: By adding the feature IgnorePolicyFeature you can specify with the property policy.ignore which policies you want to ignore in your web service client. The property value is a comma-separated list of form namespaceURI:policy, e.g. IgnorePolicyFeature policy.ignore namespaceURI:policy 7.0 LTS and older Many policies are optional and can be completely ignored. But the integrated Axis 1 and Axis 2 libraries are not able to handle them. The only way out is to patch the WSDL service definition. Remove all Policy declarations and their references and generate your service again against this modified WSDL. Axis 1 Axis 2 answered 11.04.2018 at 05:46 Reguel Werme... ♦♦ 8.8k●2●18●54 accept rate: 69% edited 12.04.2018 at 05:48 Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown webservice ×43 soap ×8 policy ×1 Asked: 11.04.2018 at 05:44 Seen: 645 times Last updated: 12.04.2018 at 05:48 Problem with German Umlaut in a Web Service wsdl SOAP Webservice in Ivy using Java Get IHttpRequest for SOAP web service How to use WS-Addressing in a webservice call? How to increase java heap space Web service development in AXON Ivy How can I evalute webservice response? How to use MTOM in Ivy web service call Can I use GIT as Team-Provider WebService Process: XmlElement(required=true) does not work
https://answers.axonivy.com/questions/3185/how-to-avoid-policy-error-when-calling-soap-webservices
CC-MAIN-2020-05
refinedweb
374
58.79
I am trying to create a basic image detector with open cv. I am using ORB, I try to open an image and then I try to detect keypoints in the image. Here is my code import cv2 from cv2 import ORB image1 = cv2.imread("original.jpg", cv2.IMREAD_GRAYSCALE) orb = ORB() # find the keypoints with ORB kp = orb.detect(image1, None) However when I run my code the program crashes with the following error Process finished with exit code -1073741819 (0xC0000005) I search for this error and I found out that this is a memory access violation but I dont know where there it could be a violation? I got the same error. After some searching I got that ORB_create() instead of ORB() fixes it. Sources: matching error in ORB with opencv 3 outImage error fix, Code: import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('extra/sample.jpg',0) ## ERROR #orb = cv2.ORB() ## FIX orb = cv2.ORB_create() # find the keypoints with ORB kp = orb.detect(img,None) # compute the descriptors with ORB kp, des = orb.compute(img, kp) ## ERROR #img2 = cv2.drawKeypoints(img,kp,color=(0,255,0), flags=0) ## Use This or the one below, One at a time #img2 = cv2.drawKeypoints(img, kp, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) img2 = cv2.drawKeypoints(img, kp, outImage = None, color=(255,0,0)) plt.imshow(img2),plt.show() User contributions licensed under CC BY-SA 3.0
https://windows-hexerror.linestarve.com/q/so60477706-orb-detect-crashes-when-try-to-detect
CC-MAIN-2020-16
refinedweb
241
68.67
Working with Pandas and NumPy¶ openpyxl is able to work with the popular libraries Pandas and NumPy NumPy Support¶ openpyxl has builtin support for the NumPy types float, integer and boolean. DateTimes are supported using the Pandas’ Timestamp type. Working with Pandas Dataframes¶ The openpyxl.utils.dataframe.dataframe_to_rows() function provides a simple way to work with Pandas Dataframes: from openpyxl.utils.dataframe import dataframe_to_rows wb = Workbook() ws = wb.active for r in dataframe_to_rows(df, index=True, header=True): ws.append(r) While Pandas itself supports conversion to Excel, this gives client code additional flexibility including the ability to stream dataframes straight to files. To convert a dataframe into a worksheet highlighting the header and index: wb = Workbook() ws = wb.active for r in dataframe_to_rows(df, index=True, header=True): ws.append(r) for cell in ws['A'] + ws[1]: cell.style = 'Pandas' wb.save("pandas_openpyxl.xlsx") Alternatively, if you just want to convert the data you can use write-only mode: from openpyxl.cell.cell import WriteOnlyCell wb = Workbook(write_only=True) ws = wb.create_sheet() cell = WriteOnlyCell(ws) cell.style = 'Pandas' def format_first_row(row, cell): for c in row: cell.value = c yield cell rows = dataframe_to_rows(df) first_row = format_first_row(next(rows), cell) ws.append(first_row) for row in rows: row = list(row) cell.value = row[0] row[0] = cell ws.append(row) wb.save("openpyxl_stream.xlsx") This code will work just as well with a standard workbook. Converting a worksheet to a Dataframe¶ To convert a worksheet to a Dataframe you can use the values property. This is very easy if the worksheet has no headers or indices: df = DataFrame(ws.values) If the worksheet does have headers or indices, such as one created by Pandas, then a little more work is required: data = ws.values cols = next(data)[1:] data = list(data) idx = [r[0] for r in data] data = (islice(r, 1, None) for r in data) df = DataFrame(data, index=idx, columns=cols)
http://openpyxl.readthedocs.io/en/latest/pandas.html
CC-MAIN-2017-17
refinedweb
325
59.7
csShaderVariableStack Class Reference A "shader variable stack". More... #include <ivideo/shader/shader.h> Detailed Description A "shader variable stack". Stores a list of shader variables, indexed by it's name. Definition at line 65 of file shader.h. Constructor & Destructor Documentation Member Function Documentation Copy contents of another stack. Unlike operator=() it does not change the storage of this stack. This stack must have the same number of elements as other. Returns whether a copy was actually made. No copy is made if both stacks point to the same storage. Definition at line 234 of file shader.h. Copies from another stack. If the other stack was created from a preallocated array, the stack points to that same array after the assignment. If the other stack used internal storage the new stack will allocate it's own internal array and copy over the contents. Definition at line 111 of file shader.h. The documentation for this class was generated from the following file: Generated for Crystal Space 2.0 by doxygen 1.6.1
http://www.crystalspace3d.org/docs/online/new0/classcsShaderVariableStack.html
CC-MAIN-2015-32
refinedweb
174
61.12
sandbox/Antoonvh/kh.c Clouds can serve as tracers to reveal the occurrence of a shear instability in the atmosphere. Image courtesy of EarthSky. The Kelvin-Helmholtz instability in two dimensions On this page a classical shear instability is simulated. According to the Kelvin-Helmholtz instability description, a thin shearing layer may be unstable and can then roll-up on itself creating vortices, or so-called Kelvin-Helmholtz billows. On this page the effect of the fluid’s viscosity on the observed dynamics is investigated. Set-up A fluid with an infinetly thin shear layer is initialized. The difference in velocity between the induvidual layers U and the length scale associated with the periodicity of the solution () in our set-up can be used to normalize the value of the fluid’s viscosity. Resulting in a Reynolds number, In this study, the Reynolds number is varied to be . In order to analyze the flow’s evolution, the emergence of coherent vortex structures is monitored. Therefore, the number of vortices is counted using the marvalous tag() function. It is remarkable how complex seamingly simple things can be. #include "navier-stokes/centered.h" #include "tag.h" int maxlevel; double vis, Re; FILE * fpn; char fnamev[99]; char fnameg[99]; As mentioned earlier periodic boundaries are used in the stream-wise direction. Furthermore, the boundaries in the span-wise direction of the square domain are of the free-slip type. int main(){ periodic(left); X0 = Y0 = -L0/2; A loop is used to run the simulation for the three different Reynolds numbers, increasing the grid resolution each iteration to a maximum of 11 levels for . maxlevel = 9; for (Re = 20000; Re <= 80001; Re = Re*2.){ init_grid (1 << 4); run(); maxlevel++; } } event init(t = 0){ vis = 1./Re; const face vector muc[] = {vis, vis}; μ = muc; The shear layer is initialized and a small random perturbation is added to the span-wise-velocity-componenent field to kick-off the growth of the instability. astats adapting; do{ foreach() u.x[] = 0.5 - (y < 0); boundary({u.x}); adapting = adapt_wavelet ({u.x}, (double[]){0.01}, maxlevel); }while (adapting.nf); foreach() u.y[] = 0.004*noise(); Output file names are defined and their names carry a Reynolds-number identifier. sprintf (fnamev, "KH%g.mp4", Re); sprintf (fnameg, "KHlev%g.mp4", Re); char name1[99]; sprintf (name1, "nrofvortices%g", Re); fpn = fopen (name1, "w"); } Output The usual suspects of animation types are generated. Meaning that the evolution of the vorticity () field and the grid resolution are visualized. The maximum value of the vorticity field () is monitored. consequently, a vortex can be defined as a connected region with a vorticity value . Based on this definition, we count and log the number of vortices. event output (t = 0.005; t += 0.01){ scalar ω[], lev[], f[]; int n = 0; double m = 0; foreach(reduction(+:n) reduction(max:m)){ n++; lev[] = level; ω[] = (u.x[0,1]-u.x[0,-1] - (u.y[1,0]-u.y[-1,0]))/(2*Δ); if (fabs(ω[]) > m) m = fabs(ω[]); } boundary({ω}); output_ppm (ω, file = fnamev, n = 512, min = -10, max = 10, linear = true); output_ppm (lev, file = fnameg, n = 512, min = 2, max = 11); foreach() f[] = (ω[] > m/3.); //1 or 0 int nrv = tag(f); fprintf (fpn,"%g\t%d\t%g\t%d\t%d\t%d\n",t, nrv, m, n,((1 << (maxlevel*dimension)))/(n), i); } The adaptation and the end-of-run events The grid resolution is adapted based on the wavelet-estimated discretization error in the representation of the velocity vector field. In the end-of-run event, the files associated with the run’s output file pointer is closed. event adapt (i++) adapt_wavelet((scalar*){u}, (double[]){0.01, 0.01}, maxlevel); event end (t = 5.) fclose(fpn); Results One may visually inspect the evolution of the various flow set-ups using the visualizations of the solutions and their grids. For , Evolution of the vorticity field Evolution of the grid structure , Evolution of the vorticity field Evolution of the grid structure and , Evolution of the vorticity field Evolution of the grid structure It seems as if the fastest growing mode is a function of the Reynolds number, this is consistent with the linear perturbation analysis that is presented in many text books on this topic. The ratio of the wavelength associated with this mode and the periodicity length scale () is related to the number of vortices that emerge. We can plot the evolution of the number of vortices for the the different runs. The evolution of the number of vortices Apart from the fact that the used vortex detection algorithm intermittently identifies decaying shear layers as vortices, these numbers seem to correspond with what we saw in the visualizations. Well done tag() function! Finally, we check if it was sensible to use an adaptive grid by plotting the grid-cell-compression ratio () over time. This ratio is defined as the number of grid cells required to fill the domain with an equidistant and static grid with a cell size divided by the number of grid cells employed by the adaptation algoirithm (i.e. ). The results speak for them selves (note the logaritmic axis).
http://basilisk.fr/sandbox/Antoonvh/kh.c
CC-MAIN-2018-43
refinedweb
865
55.44
I know it has something to do with how included my files. Here is the exact error that i get. c:\program files\microsoft visual studio\myprojects\areacalc\functions.c(1) : warning C4182: #include nesting level is 363 deep; possible infinite recursion c:\program files\microsoft visual studio\myprojects\areacalc\functions.c(1) : fatal error C1076: compiler limit : internal heap limit reached; use /Zm to specify a higher limit here is how i have it. I have a main.c with the main function in it. I have these included: #include "functions.c" #include "header.h" #include <stdio.h> #include <stdlib.h> and in functions.c i have these: #include "main.c" #include <stdio.h> #include <stdlib.h> #include <math.h> #include "header.h" can somebody plz explain this to me in easy terms, cuz i am sort of a noob. It is homework for me. Ive already made the program and it works, when i have it in one file, but my instructure want a header file, a function.c file, and a main.c file, and we havent learned that yet. I am just trying to get ahead on my homework, and i ran into this.
https://cboard.cprogramming.com/c-programming/10256-internal-heap-limit-printable-thread.html
CC-MAIN-2018-05
refinedweb
198
72.42
gettimeofday, settimeofday - get / set time Synopsis Description Errors Note #include <sys/time.h> int gettimeofday(struct timeval *tv, struct timezone *tz); int settimeofday(const struct timeval *tv , const struct timezone *tz); The functions gettimeofday and settimeofday can get and set the time as well as a timezone. The tv argument is a timeval struct, as specified in <sys/time.h>: struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; and gives the number of seconds and microseconds since the Epoch (see time(2)). The tz argument). The). Traditionally, the fields of struct timeval were longs. SVr4, BSD 4.3. POSIX 1003.1-2001 describes gettimeofday() but not settimeofday(). date(1), adjtimex(2), time(2), ctime(3), ftime(3)
http://www.squarebox.co.uk/cgi-squarebox/manServer/usr/share/man/man2/settimeofday.2
crawl-003
refinedweb
117
60.01
Download presentation Presentation is loading. Please wait. Published byNicolas Cullis Modified over 2 years ago 1 Kathleen Fisher cs242 Reading: Tackling the Awkward Squad, Sections 1-2Tackling the Awkward Squad Real World Haskell, Chapter 7: I/OReal World Haskell Thanks to Simon Peyton Jones for many of these slides. 2 Functional programming is beautiful: Concise and powerful abstractions higher-order functions, algebraic data types, parametric polymorphism, principled overloading,... Close correspondence with mathematics Semantics of a code function is the math function Equational reasoning: if x = y, then f x = f y Independence of order-of-evaluation (Church-Rosser) e1 * e2 result The compiler can choose the best order in which to do evaluation, including skipping a term if it is not needed. 3 But to be useful as well as beautiful, a language must manage the Awkward Squad: Input/Output Imperative update Error recovery (eg, timing out, catching divide by zero, etc.) Foreign-language interfaces Concurrency The whole point of a running a program is to affect the real world, an update in place. 4 Do everything the usual way: I/O via functions with side effects: Imperative operations via assignable reference cells: Error recovery via exceptions Foreign language procedures mapped to functions Concurrency via operating system threads Ok if evaluation order is baked into the language. putchar x + putchar y z = ref 0; z := !z + 1; f(z); w = !z (* What is the value of w? *) 5 Consider: Output depends upon the evaluation order of ( + ). Consider: Output depends on how the consumer uses the list. If only used in length ls, nothing will be printed because length does not evaluate elements of list. In a lazy functional language, like Haskell, the order of evaluation is deliberately undefined, so the direct approach will not work. res = putchar x + putchar y ls = [putchar x, putchar y] 6 Laziness and side effects are incompatible. Side effects are important! For a long time, this tension was embarrassing to the lazy functional programming community. In early 90s, a surprising solution (the monad) emerged from an unlikely source (category theory). Haskells IO monad provides a way of tackling the awkward squad: I/O, imperative state, exceptions, foreign functions, & concurrency. 7 The reading uses a web server as an example. Lots of I/O, need for error recovery, need to call external libraries, need for concurrency Web server Client 1Client 2Client 3Client 4 1500 lines of Haskell 700 connections/sec Writing High-Performance Server Applications in HaskellWriting High-Performance Server Applications in Haskell by Simon Marlow 8 Monadic Input and Output 9 A functional program defines a pure function, with no side effects. The whole point of running a program is to have some side effect. Tension 10 Streams Program issues a stream of requests to OS, which responds with a stream of responses. Continuations User supplies continuations to I/O routines to specify how to process results. World-Passing The World is passed around and updated, like a normal data structure. Not a serious contender because designers didnt know how to guarantee single-threaded access to the world. Stream and Continuation models were discovered to be inter-definable. Haskell 1.0 Report adopted Stream model. 11 Move side effects outside of functional program If Haskell main :: String -> String But what if you need to read more than one file? Or delete files? Or communicate over a socket?... Haskell main program standard input location (file or stdin) standard output location (file or stdin) Wrapper Program, written in some other language 12 Enrich argument and return type of main to include all input and output events. Wrapper program interprets requests and adds responses to input. main :: [Response] -> [Request] data Request = ReadFile Filename | WriteFile FileName String | … data Response= RequestFailed | ReadOK String | WriteOk | Success | … 13 Move side effects outside of functional program If Haskell main :: [Response] -> [Request] Laziness allows program to generate requests prior to processing any responses. Haskell program [ Response ][ Request ] 14 Haskell 1.0 program asks user for filename, echoes name, reads file, and prints to standard out. The ~ denotes a lazy pattern, which is evaluated only when the corresponding identifier is needed. main :: [Response] -> [Request] main ~(Success : ~((Str userInput) : ~(Success : ~(r4 : _)))) = [ AppendChan stdout "enter filename\n", ReadChan stdin, AppendChan stdout name, ReadFile name, AppendChan stdout (case r4 of Str contents -> contents Failure ioerr -> "cant open file") ] where (name : _) = lines userInput 15 Hard to extend: new I/O operations require adding new constructors to Request and Response types and modifying the wrapper. No close connection between a Request and corresponding Response, so easy to get out- of-step, which can lead to deadlock. The style is not composable: no easy way to combine two main programs.... and other problems!!! 16 A value of type ( IO t ) is an action. When performed, it may do some input/output before delivering a result of type t. 17 type IO t = World -> (t, World) IO t result :: t 18 Actions are sometimes called computations. An action is a first-class value. Evaluating an action has no effect; performing the action has the effect. A value of type ( IO t ) is an action. When performed, it may do some input/output before delivering a result of type t. type IO t = World -> (t, World) 19 getChar Char putChar () Char getChar :: IO Char putChar :: Char -> IO () main :: IO () main = putChar x Main program is an action of type IO () 20 putChar () getChar Char To read a character and then write it back out, we need to connect two actions. The bind combinator lets us make these connections. 21 We have connected two actions to make a new, bigger action. putChar () Char getChar (>>=) :: IO a -> (a -> IO b) -> IO b echo :: IO () echo = getChar >>= putChar 22 Operator is called bind because it binds the result of the left-hand action in the action on the right. Performing compound action a >>= \x->b: performs action a, to yield value r applies function \x->b to r performs the resulting action b{x <- r} returns the resulting value v b v a x r 23 The parentheses are optional because lambda abstractions extend as far to the right as possible. The putChar function returns unit, so there is no interesting value to pass on. echoDup :: IO () echoDup = getChar >>= (\c -> putChar c >>= (\() -> putChar c )) 24 The then combinator (>>) does sequencing when there is no value to pass: (>>) :: IO a -> IO b -> IO b m >> n = m >>= (\_ -> n) echoDup :: IO () echoDup = getChar >>= \c -> putChar c >> putChar c echoTwice :: IO () echoTwice = echo >> echo 25 We want to return (c1,c2). But, (c1,c2) :: (Char, Char) And we need to return something of type IO(Char, Char) We need to have some way to convert values of plain type into the I/O Monad. getTwoChars :: IO (Char,Char) getTwoChars = getChar>>= \c1 -> getChar>>= \c2 -> ???? 26 The action (return v) does no IO and immediately returns v: return :: a -> IO a return getTwoChars :: IO (Char,Char) getTwoChars = getChar>>= \c1 -> getChar>>= \c2 -> return (c1,c2) 27 The do notation adds syntactic sugar to make monadic code easier to read. Do) 28 The do notation only adds syntactic sugar: do { x >= \x -> do { es } do { e; es }=e >> do { es } do { e }=e do {let ds; es} = let ds in do {es} The scope of variables bound in a generator is the rest of the do expression. The last item in a do expression must be an expression. 29 The following are equivalent: do { x1 <- p1;...; xn <- pn; q } do x1 <- p1... xn <- pn q do x1 <- p1;...; xn <- pn; q If the semicolons are omitted, then the generators must line up. The indentation replaces the punctuation. 30 The getLine function reads a line of input: getLine :: IO [Char] getLine = do { c <- getChar ; if c == '\n' then return [] else do { cs <- getLine; return (c:cs) }} Note the regular code mixed with the monadic operations and the nested do expression. 31 Each action in the IO monad is a possible stage in an assembly line. For an action with type IO a, the type tags the action as suitable for the IO assembly line via the IO type constructor. indicates that the kind of thing being passed to the next stage in the assembly line has type a. The bind operator snaps two stages s1 and s2 together to build a compound stage. The return operator converts a pure value into a stage in the assembly line. The assembly line does nothing until it is turned on. The only safe way to run an IO assembly is to execute the program, either using ghci or running an executable. 12 32 Running the program turns on the IO assembly line. The assembly line gets the world as its input and delivers a result and a modified world. The types guarantee that the world flows in a single thread through the assembly line. Result ghci or compiled program 33 Values of type (IO t) are first class, so we can define our own control structures. Example use: forever :: IO () -> IO () forever a = a >> forever a repeatN :: Int -> IO () -> IO () repeatN 0 a = return () repeatN n a = a >> repeatN (n-1) a Main> repeatN 5 (putChar 'h') 34 Values of type (IO t) are first class, so we can define our own control structures. Example use: for :: [a] -> (a -> IO b) -> IO () for [] fa = return () for (x:xs) fa = fa x >> for xs fa Main> for [1..10] (\x -> putStr (show x)) 35 Example use: sequence :: [IO a] -> IO [a] sequence [] = return [] sequence (a:as) = do { r <- a; rs <- sequence as; return (r:rs) } Main> sequence [getChar, getChar, getChar] A list of IO actions. An IO action returning a list. 36 Slogan: First-class actions let programmers write application-specific control structures. 37 The IO Monad provides a large collection of operations for interacting with the World. For example, it provides a direct analogy to the Standard C library functions for files: openFile :: String -> IOMode -> IO Handle hPutStr :: Handle -> String -> IO () hGetLine :: Handle -> IO String hClose :: Handle -> IO () 38 The IO operations let us write programs that do I/O in a strictly sequential, imperative fashion. Idea: We can leverage the sequential nature of the IO monad to do other imperative things! A value of type IORef a is a reference to a mutable cell holding a value of type a. data IORef a -- Abstract type newIORef :: a -> IO (IORef a) readIORef :: IORef a -> IO a writeIORef :: IORef a -> a -> IO () 39 But this is terrible! Contrast with: sum [1..n]. Claims to need side effects, but doesnt really.)} 40)} Just because you can write C code in Haskell, doesnt mean you should! 41 Track the number of chars written to a file. Here it makes sense to use a reference. type HandleC = (Handle, IORef Int) openFileC :: String -> IOMode -> IO HandleC openFileC fn mode = do { h <- openFile fn mode; v <- newIORef 0; return (h,v) } hPutStrC :: HandleC -> String -> IO() hPutStrC (h,r) cs = do { v <- readIORef r; writeIORef r (v + length cs); hPutStr h cs } 42 All operations return an IO action, but only bind (>>=) takes one as an argument. Bind is the only operation that combines IO actions, which forces sequentiality. Within the program, there is no way out! return :: a -> IO a (>>=) :: IO a -> (a -> IO b) -> IO b getChar :: IO Char putChar :: Char -> IO ()... more operations on characters... openFile :: [Char] -> IOMode -> IO Handle... more operations on files... newIORef :: a -> IO (IORef a)... more operations on references... 43 Suppose you wanted to read a configuration file at the beginning of your program: The problem is that readFile returns an IO String, not a String. Option 1: Write entire program in IO monad. But then we lose the simplicity of pure code. Option 2: Escape from the IO Monad using a function from IO String -> String. But this is the very thing that is disallowed! configFileContents :: [String] configFileContents = lines (readFile "config") -- WRONG! useOptimisation :: Bool useOptimisation = "optimise" elem configFileContents 44 Reading a file is an I/O action, so in general it matters when we read the file relative to the other actions in the program. In this case, however, we are confident the configuration file will not change during the program, so it doesnt really matter when we read it. This situation arises sufficiently often that Haskell implementations offer one last unsafe I/O primitive: unsafePerformIO. unsafePerformIO :: IO a -> a configFileContents :: [String] configFileContents = lines(unsafePerformIO(readFile"config")) 45 unsafePerformIO The operator has a deliberately long name to discourage its use. Its use comes with a proof obligation: a promise to the compiler that the timing of this operation relative to all other operations doesnt matter. unsafePerformIO :: IO a -> a Result act Invent World Discard World 46 unsafePerformIO As its name suggests, unsafePerformIO breaks the soundness of the type system. So claims that Haskell is type safe only apply to programs that dont use unsafePerformIO. Similar examples are what caused difficulties in integrating references with Hindley/Milner type inference in ML. r :: IORef c -- This is bad! r = unsafePerformIO (newIORef (error "urk")) cast :: a -> b cast x = unsafePerformIO (do {writeIORef r x; readIORef r }) 47 GHC uses world-passing semantics for the IO monad: It represents the world by an un-forgeable token of type World, and implements bind and return as: Using this form, the compiler can do its normal optimizations. The dependence on the world ensures the resulting code will still be single-threaded. The code generator then converts the code to modify the world in-place. type IO t = World -> (t, World) return :: a -> IO a return a = \w -> (a,w) (>>=) :: IO a -> (a -> IO b) -> IO b (>>=) m k = \w -> case m w of (r,w) -> k r w 48 What makes the IO Monad a Monad? A monad consists of: A type constructor M A function bind :: M a -> ( a -> M b) -> M b A function return :: a -> M a Plus: Laws about how these operations interact. 49 return x >>= f = f x m >>= return = m do { x <- m 1 ; y <- m 2 ; m 3 } do { y <- do { x <- m 1 ; m 2 } m 3 } = x not in free vars of m 3 50 done >> m = m m >> done = m m 1 >> (m 2 >> m 3 ) = (m 1 >> m 2 ) >> m 3 (>>) :: IO a -> IO b -> IO b m >> n = m >>= (\_ -> n) done :: IO () done = return () 51 Using the monad laws and equational reasoning, we can prove program properties. putStr :: String -> IO () putStr [] = done putStr (c:s) = putChar c >> putStr s Proposition : putStr r >> putStr s = putStr (r ++ s) 52 putStr :: String -> IO () putStr [] = done putStr (c:cs) = putChar c >> putStr cs Proof: By induction on r. Base case: r is [] putStr [] >> putStr s = ( definition of putStr ) done >> putStr s = ( first monad law for >>) putStr s = (definition of ++) putStr ([] ++ s) Induction case: r is (c:cs) … Proposition : putStr r >> putStr s = putStr (r ++ s) 53 A complete Haskell program is a single IO action called main. Inside IO, code is single-threaded. Big IO actions are built by gluing together smaller ones with bind ( >>= ) and by converting pure code into actions with return. IO actions are first-class. They can be passed to functions, returned from functions, and stored in data structures. So it is easy to define new glue combinators. The IO Monad allows Haskell to be pure while efficiently supporting side effects. The type system separates the pure from the effectful code. 54 In languages like ML or Java, the fact that the language is in the IO monad is baked in to the language. There is no need to mark anything in the type system because it is everywhere. In Haskell, the programmer can choose when to live in the IO monad and when to live in the realm of pure functional programming. So it is not Haskell that lacks imperative features, but rather the other languages that lack the ability to have a statically distinguishable pure subset. Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/1522419/
CC-MAIN-2017-13
refinedweb
2,669
60.55
bad_words 0.1.2 bad_words # A dart filter for English bad words. Installation # bad_words: ^0.1.0 Usage # import 'package:bad_words/bad_words.dart'; final filter = Filter(); if (filter.isProfane('some string to test')) { // ... validation error etc. } [0.1.0] - August 29, 2019. Initial release. Includes blacklist of words checking if the string contains profane language. Only in English. [0.1.1] - September 2, 2019. Clean up the example.dart file. [0.1.2] - September 2, 2019. Update README example to use latest version. import 'package:bad_words/bad_words.dart'; main() { final testString = 'string that does not contain bad words'; final filter = Filter(); if (filter.isProfane(testString)) { print('put a nickle in the swear jar!'); } } Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: bad_words: :bad_words/bad_words.dart'; We analyzed this package on Jan 16, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.7.0 - pana: 0.13.4 - Flutter: 1.12.13+hotfix.5
https://pub.dev/packages/bad_words
CC-MAIN-2020-05
refinedweb
174
56.52
>JCL and slf4j ARE ready-to-use logging wrappers. +1 regards, gerhard Your JSF powerhouse - JSF Consulting, Development and Courses in English and German Professional Support for Apache MyFaces 2009/6/5 Manfred Geiler <manfred.geiler@gmail.com> > On Fri, Jun 5, 2009 at 19:49, Mario Ivankovits <mario@ops.co.at> wrote: > > Hi! > > > > Could one please eloberate a little bit more in detail what the pros are > of > > slf4j? > > Pros: > No class loader ambiguousness (as you mentioned) > You get what you define (especially when using maven): > compile-dependency to slf4j-api > runtime-dependency to slf4j-adapter of YOUR choice > --> that's it! > > No wild guessing like with JCL: Use Log4j if it is anywhere in the > (web container) classpath, else use Java logging... What, if I want to > use Java logging although there is Log4j in the classpath?! > "Someone dropped a log4j.jar in the tomcat/lib folder. Oh no, not again..." > Yes, I know commons-logging.properties solves this, but that's > awful... (BTW, I hate properties files in the root package namespace!) > > > > Notice, I switched to it in our company project - but always using the > > commons-logging api and just used the slf4j-over-cl wrapper. This is > > something wich is possible for each and ever user of myfaces already, > just > > by adjusting the depencendcies correctly. > > Guess, you meant the jcl-over-slf4j.jar bridge, right? That's the part > that reroutes JCL calls to the slf4j API. > Yes, that is a possible solution, but keep in mind that this is kind > of a hack. It is actually a reimplementation of the JCL API > (namespace) that routes all calls to SLF4J. > It's meant as runtime solution for legacy libs. Using it as compile > time dependency might be a shortcut, but my feeling says it's not the > nicest solution. > > > > Lately I even switched to my own logging wrapper, but this is another > story. > > In the end, everything still uses the cl API which is proven to work > fine. > > (I created the org.apache.commons.logging package structure with my own > > classes - which for sure is not possible for myfaces!). > > yet another logging wrapper.... WHY do so many people feel they must > write such a thing? JCL and slf4j ARE ready-to-use logging wrappers. > So??? > > > > I still think, that using the cl api is the best we can do for our users. > If > > they then use cl as implementation - and if this is considered "good" - > is > > another story, but nothing WE should anticipate. > > They CAN use JCL if myfaces uses slf4j. They just define a > slf4j-jcl-x.x.x.jar runtime-dependency and everything is fine. > > > > As far as I can say the cl api is rock solid, just the class-loader stuff > is > > a pain. But (again AFAIK), slf4j does not solve it, it just does not deal > > with it. > > slf4j DOES solve the problem by avoiding highly sophisticated classloader > magic! > > > > Before we start using any other logging api I'd suggest to build our own > > thin myfaces-logging wrapper where one then can easily plug in log4j, cl, > > jul (java utils ogging) or whatever - we do not even have to provide any > > other impl than for jul. > > yet another logging wrapper... (see above) > > How would you implement such a pluggable wrapper? Yet another > (mandatory) config parameter. System property? Servlet context param? > Come on! > What about this: looking for existing well-known logging > implementations and define some priority rules... Dejavu. See the > problem? > > > > As a plus, this then will remove a dependency - a dependency to any > logging > > framework - which - in terms of dependencies can be considered as a > "good" > > thing, no? > > You buy this "good" thing by re-implementing SLF4J and/or JCL. > Serious. I cannot imagine a "wrapper" (actually a "facade", right?) > implementation that is versatile for the developers and pluggable for > the users and has less source code than any of the well-known logging > facade APIs (slf4j and jcl). They both are actually meant to heal the > java world from proprietary "yet another logging facades/wrappers"! > > > +1 for using SLF4J as logging facade for future MyFaces developments > (JSF 2.0, ...) > +0 for replacing JCL by SLF4J for all existing code (if someone is > volunteering to do the job I have no problem with that...) > > > --Manfred >
http://mail-archives.apache.org/mod_mbox/myfaces-dev/200906.mbox/%3C2332f63b0906051156x339fef04tff1a86d3dfd6ae78@mail.gmail.com%3E
CC-MAIN-2015-35
refinedweb
714
66.94
To use the SQL Anywhere .NET Data Provider, you must include two items in your Visual Studio .NET project: a reference to the SQL Anywhere .NET Data Provider DLL a line in your source code referencing the SQL Anywhere .NET Data Provider classes These steps are explained below. For information about installing and registering the SQL Anywhere .NET Data Provider, see Deploying the SQL Anywhere .NET Data Provider. Adding a reference tells Visual Studio .NET which DLL to include to find the code for the SQL Anywhere .NET Data Provider. Start Visual Studio .NET and open your project. In the Solution Explorer window, right-click References and choose Add Reference from the popup menu. The Add Reference dialog appears. On the .NET tab, click Browse to locate iAnywhere.Data.SQLAnywhere.dll. Note that there are separate versions of the DLL for each of .NET 1.x and 2.0 and each of Windows and Windows CE. For the Windows .NET 2.0 Data Provider, the default location is install-dir\Assembly\v2. For the Windows CE .NET 2.0 Data Provider, the default location is install-dir\ce\Assembly\v2 for each supported Windows CE hardware platform (for example, ce\Assembly\v2\arm.30). For the Windows .NET 1.x Data Provider, the default location is install-dir\Assembly\v1. For the Windows CE .NET 1.x Data Provider, the default location is install-dir\ce\Assembly\v1 for each supported Windows CE hardware platform (for example, ce\Assembly\v1\arm.30). Select the DLL and then click Open. For a complete list of installed DLLs, see SQL Anywhere .NET Data Provider required files. You can verify that the DLL is added to your project. Open the Add Reference dialog and then click the .NET tab. iAnywhere.Data.SQLAnywhere.dll appears in the Selected Components list. Click OK to close the dialog. The DLL is added to the References folder in the Solution Explorer window of your project. To facilitate the use of the SQL Anywhere .NET Data Provider namespace and the types defined in this namespace, you should add a directive to your source code. Start Visual Studio .NET and open your project. Add the following line to your project: If you are using C#, add the following line to the list of using directives at the beginning of your project: using iAnywhere.Data.SQLAnywhere; If you are using Visual Basic .NET, add the following line at the beginning of your project before the line Public Class Form1: Imports iAnywhere.Data.SQLAnywhere This directive is not required, however, it allows you to use short forms for the SQL Anywhere ADO.NET classes. For example: SAConnection conn = new SAConnection() Without this directive, you can still use the following: iAnywhere.Data.SQLAnywhere.SAConnection conn = new iAnywhere.Data.SQLAnywhere.SAConnection()
http://dcx.sap.com/1001/en/dbpgen10/pg-project-adodotnet-development.html
CC-MAIN-2019-13
refinedweb
468
70.39
Subject: Re: [boost] Outcome v2 From: Andrzej Krzemienski (akrzemi1_at_[hidden]) Date: 2017-07-13 09:16:48 2017-07-12 20:49 GMT+02:00 Emil Dotchevski via Boost <boost_at_[hidden]> : > On Wed, Jul 12, 2017 at 10:23 AM, Andrzej Krzemienski via Boost < > boost_at_[hidden]> wrote: > > > > On Tue, Jul 11, 2017 at 3:16 PM, Emil Dotchevski < > > emildotchevski_at_[hidden] > > > > > > > wrote: > > > > > > > On Tue, Jul 11, 2017 at 2:11 PM, Niall Douglas via Boost < > > > > boost_at_[hidden]> wrote: > > > > > > > >> > Outcome does not solve the most important problem that needs > solving > > > by > > > >> an > > > >> > error handling library. > > > >> > > > >> Does Expected? > > > >> > > > > > > > > Nope, but the original outcome<T> was closer. I thought, perhaps it > is > > > > possible to make it able to transport arbitrary error types, and not > by > > > > exception_ptr. My attempt at solving that problem lead me to TLS but > > > maybe > > > > there are other ways. > > > > > > > > > > Allow me to clarify. Suppose I have a function foo which returns FILE * > > on > > > success, some EC1 on failure, and another function bar(), which calls > foo > > > and returns an int on success, some EC2 on failure. I believe in terms > of > > > Outcome this would be: > > > > > > outcome::result<FILE *,EC1> foo() noexcept; > > > > > > outcome::result<int,EC2> bar() noexcept { > > > if( auto r=foo() ) { > > > //no error, use r.value(), produce the int result or return EC2(x). > > > } else { > > > return ______; > > > } > > > } > > > > > > What do you recommend in place of _____? > > > > > > Here is the same code in terms of Noexcept: > > > > > > FILE * foo() noexcept; > > > > > > int bar() noexcept { > > > if( FILE * r=foo() ) { > > > //no error, use r, produce the int result or return throw_(EC2(x)). > > > } else { > > > return throw_(); > > > } > > > } > > > > > > That is, with Noexcept, bar() would not care what error types propagate > > out > > > of foo because it can't handle any errors anyway. Whatever the error > is, > > it > > > is simply passed to the caller. > > > > The default EC type in outcome::result<> is std::error_code, and it is > > possible to use only this type throughout entire program > > > I didn't mean that you would design the program like this, the point is > that you may not have control over the fact that foo returns EC1, and you > still have to be able to write bar() (I should have made that clearer by > using different namespaces.) > So, you are saying that one can construct a programming problem that Outcome library will not be able to solve. I agree. If you are forced to return EC1 and are forced to use something that returns EC2, where EC1 is not related to EC2, you will probably not be able to solve it decently. > > In this comment you're echoing what Niall was saying in the documentation > of the original Outcome, where he had several paragraphs attempting to > convince the reader to stop using random error codes and _always_ use > std::error_code, with technical phrases like "don't be anti-social" :) > Yes. It is my understanding that the value of this library can be only appreciated and exploited when you decide you will be using std::error_code as EC uniformly (or otherwise apply other precautions). One can compare it to the expectation that, C++ exception handling mechanism is useful provided that you decide to throw objects that inherit directly or not from `std::exception`. People generally don't have problem with this constraint. And occasionally some clever people find reasons to throw other types, like `boost::interrupted`. > > But that is not our reality, and it will never be our reality in C++ > because C++ programs do use C libraries, I am not sure what using C libraries changes here? > and because different C++ > libraries commonly use their own types for similar things. This is > especially true for error codes. > I think this is what std::error_code was design for: to convey the original (unconverted) numeric value of any error code (along with the error domain) from any library in a uniform way. The fact that result<T, EC> allows you to put just any EC should not be understood that it is reasonable to return different EC1 and EC2 wherever you like. I would intuitively expect of the users of `result<>` that they use different EC's only in the following situations: 1. EC1 is std::error_code and EC2 is an opaque typedef on std::error_code, and I need an opaque typedef to customize the behavior of `result` on it. 2. The usage of a custom EC2 is completely encapsulated from the outside world: I use it in one translation unit internally, and never expose it in the interface, as shown in my example with the parser: > > given that these > > errors are to be handled immediatly in the next layer, it should not be > > that much of the problem. > > > > In my example the error is not to be handled immediately in the next layer. > I don't need an error handling library if the error is always handled "in > the next layer". > If by "error handling" you mean "never be forced to respond to it in the next layer" (note: not "handle" but "respond"), you may say that Outcome is not a library for error handling. But you may still find it useful for situations that are not "errors" by your definition, but that occur in programs, and are "irregular" in some sense, and you need to respond to them in the next layer. To "respond" is different than to "handle", because the "response" is usually to report it one level up, so that it still needs to be responded to. It is tat this decision to forward the condition up is noted explicitly in the code. Sometimes you do not want this explicitness and you will use stack unwinding. Sometimes you want this explicitness and this is where Outcome is helpful. Regards, &rzej; Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2017/07/237130.php
CC-MAIN-2019-39
refinedweb
969
56.69
Vapoursynth is not slow as well, same Avisynth, it uses C or C++ for frame manipulations, functions, not sure what now. Or you use DLL's that are C or C++. I do not know which, maybe they could be written in both. I have slow PC , first i5 that were around , 10 years old+, and SD resolution is running that top code, piping from ffmpeg runs at 220fps. 1920x1080 video, processes as 30fps. Mostly using laptops even and it is fast enough. And that script I posted in previous thread, runs very fast as well. If you convert to video from that script, it is negligible, because conversion takes forever in comparison. ctypes.memmove is very fast, that is C also. Converting from vapoursynth frame to numpy frame are very fast as well, milliseconds for frame, they are just memory operations. Running just using Vapoursynth source Plugin, lsmas.LibavSMASHSource gives similar speeds and you can go back and forth. Using just pipe, like you do, it is one way only, one read and frame is gone. That last sentence I'd pull out again, because of using pipe, you cannot view that video in a sense going back and forth, you have one shot for a frame. That is why I included lots of try - except blocks in that script, because if you view that video, it could give you all sort of weirdness or errors or how do you know that pipe needs to be terminated if you just decide to be done viewing. That ffmpeg pipe needs to be terminated manually if not reading all frames. Maybe this is why you have lots of problems with this, because you have difficulty with feedback, what you do. I know what you are trying to do now, I read that thread you are active in, looking at those codes, that is why i posted some Python code for comparison. And you include for yourself something that limits RGB. Now you need the same but piping YUV 10bit , not RGB from YUV8bit. But all you need is to figure out arguments, starting with those lines I mentioned, and settle on it for one vapoursynth yuv to rgb conversion line. Instead you try to come up again for completely new codes, because you use YUV10bit. That is why Avisynth and Vapoursth are here (thorough video pixel manipulations and piping it with ease to encoders). Or as a matter of fact, opencv(using numpy and having terms to put it on screen right away, GUI), or PIL, even Qt (but that mostly regarding GUI). + Reply to Thread Results 31 to 36 of 36 Thread Last edited by _Al_; 4th Mar 2020 at 22:43. I just tested getting RGB as you want to those particular coefficients to process YUV to RGB manually and also same conversion by Vapoursynth line. They are identical. Code: r = (255/219)*y + (255/112)*v*(1-Kr) - (255*16/219 + 255*128/112*(1-Kr)) g = (255/219)*y - (255/112)*u*(1-Kb)*Kb/Kg - (255/112)*v*(1-Kr)*Kr/Kg - (255*16/219 - 255/112*128*(1-Kb)*Kb/Kg - 255/112*128*(1-Kr)*Kr/Kg) b = (255/219)*y + (255/112)*u*(1-Kb) - (255*16/219 + 255*128/112*(1-Kb))Code: import vapoursynth as vs core = vs.core #color bar YUV420P8 clip c = core.colorbars.ColorBars(format=vs.YUV444P10) c = core.std.SetFrameProp(clip=c, prop="_FieldBased", intval=0) c = core.std.Convolution(c,mode="h",matrix=[1,2,4,2,1]) c = core.resize.Point(clip=c, matrix_in_s ='709', format=vs.YUV420P8) c = c * (30 * 30000 // 1001) clip = core.std.AssumeFPS(clip=c, fpsnum=30000, fpsden=1001) #BT709 Kr = 0.2126 Kg = 0.7152 Kb = 0.0722 #yuv [16,235] <-> rgb [0,255] R1 = 255/219 R2 = (255/112)*(1-Kr) R3 = (255*16/219 + 255*128/112*(1-Kr)) G1 = 255/219 G2 = (255/112)*(1-Kb)*Kb/Kg G3 = (255/112)*(1-Kr)*Kr/Kg G4 = (255*16/219 - 255/112*128*(1-Kb)*Kb/Kg - 255/112*128*(1-Kr)*Kr/Kg) B1 = 255/219 B2 = (255/112)*(1-Kb) B3 = (255*16/219 + 255*128/112*(1-Kb)) yuv444 = core.resize.Point(clip, format = vs.YUV444P8) #to have no subsumpling for expressions planes = [core.std.ShufflePlanes(yuv444, planes=i, colorfamily=vs.GRAY) for i in range(3)] R = core.std.Expr(clips = planes, expr = [f"{R1} x * {R2} z * + {R3} -"]) G = core.std.Expr(clips = planes, expr = [f"{G1} x * {G2} y * - {G3} z * - {G4} -"]) B = core.std.Expr(clips = planes, expr = [f"{B1} x * {B2} y * + {B3} -"]) rgb = core.std.ShufflePlanes(clips = [R,G,B], planes= [0,0,0], colorfamily=vs.RGB) rgb = core.std.SetFrameProp(rgb, prop='_Matrix', delete=True) #this is Vapoursynth conversion YUV to RGB rgb2 = core.resize.Point(clip, format = vs.RGB24, matrix_in_s = '709') #both outputs are the same rgb.set_output() rgb2.set_output(1) Code: clip = core.lsmas.LibavSMASHSource(r"C:\video.mp4") I'm not having any luck getting Vapoursynth to go. See my post in the "ffmpeg color range" thread in Video Conversion. Last edited by chris319; 5th Mar 2020 at 17:18. - - - Similar Threads 10-bit to 8-bit Video File Conversions - the easy (free) way!By VideoWiz in forum Video ConversionReplies: 10Last Post: 6th Feb 2020, 04:24 Help with running 32-bit DLL in 64-bit AVSynth with MP_Pipeline.By Vitality in forum Video ConversionReplies: 1Last Post: 12th Jan 2019, 17:26 16-bit PNG ~> 10-bit MKV GPU encodeBy Hylocereus in forum Newbie / General discussionsReplies: 8Last Post: 30th Mar 2018, 00:07 MPC HC: 32-bit or 64-bit on Windows 7 64-bitBy flashandpan007 in forum Software PlayingReplies: 20Last Post: 22nd Jul 2016, 10:22 why in windows 64 bit I don't see 64 bit codec with DSFmgr?By marcorocchini in forum Newbie / General discussionsReplies: 2Last Post: 8th Sep 2015, 10:01
https://forum.videohelp.com/threads/396140-10-Bit-Pixels/page2?s=88f23e00b55f96b31dc5a5f788baf69b
CC-MAIN-2020-16
refinedweb
990
74.79
Calling Go code from Python code Inspired by the ruby version from @jondot With the release of Go 1.5 you can now call Go as a shared library in other languages. That little tidbit escaped me the first time I went through the release notes but after having the above ruby article come through my twitter stream I decided I should see if I could quickly get a simple example working between Go and Python. First you have to write a short go func you want to expose to your python code in a simple file. I wrote one in libadd.go. The comments are critical to include so the functions are exported. //libadd.go package main import "C" //export add func add(left, right int) int { return left + right } func main() { } Then you’re going to want to use the new buildmode option in 1.5 go build -buildmode=c-shared -o libadd.so libadd.go Make sure you’ve upgraded to 1.5.1 while having completely removed any previous version or you’ll get this error imports runtime: C source files not allowed when not using cgo or SWIG: atomic_amd64x.c defs.c float.c heapdump.c lfstack.c malloc.c mcache.c mcentral.c mem_linux.c mfixalloc.c mgc0.c mheap.c msize.c os_linux.c panic.c parfor.c proc.c runtime.c signal.c signal_amd64x.c signal_unix.c stack.c string.c sys_x86.c vdso_linux_amd64.c The python code is really short and this is only passing an integer back and forth (more complex string and struct cases are much more challenging). from ctypes import cdll lib = cdll.LoadLibrary('./libadd.so') print "Loaded go generated SO library" result = lib.add(2, 3) print result The Ruby post includes a full demo project that shows what the go code would look like that would go fetch several URLs using channels and return results back that project is here and it would probably be worth doing a Python version at some point the illustrates how to do more complex struct and types (this was a very limited post). Here is some further reading: the design doc around how this is going to all work python ctypes and cffi cgo and how types interplay with the export/import go C package ctypes documentation cffi documentation Perhaps a note to indicate that the “//export add” comment is important!!! Added, thanks! Would be better if you post more examples, because I’m adding a factorial function with channel and goroutines inside it, I got error Traceback (most recent call last): File “add.py”, line 7, in resfib = lib.factorial(6) File “/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/ctypes/__init__.py”, line 360, in __getattr__ func = self.__getitem__(name) File “/usr/local/var/pyenv/versions/3.5.0/lib/python3.5/ctypes/__init__.py”, line 365, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: dlsym(0x7fbd9ac1f6f0, factorial): symbol not found
http://savorywatt.com/2015/09/18/calling-go-code-from-python-code/
CC-MAIN-2019-47
refinedweb
496
60.75
Programming FAQ Contents - Programming FAQ - General Questions - Core Language - Why am I getting an UnboundLocalError when the variable has a value? - What are the rules for local and global variables in Python? - Why do lambdas defined in a loop with different values all return the same result? - How do I share global variables across modules? - What are the “best practices” for using import in a module? - Why are default values shared between objects? - How can I pass optional or keyword parameters from one function to another? - What is the difference between arguments and parameters? - Why did changing list ‘y’ also change list ‘x’? - How do I write a function with output parameters (call by reference)? - How do you make a higher order function in Python? - How do I copy an object in Python? - How can I find the methods or attributes of an object? - How can my code discover the name of an object? - What’s up with the comma operator’s precedence? - Is there an equivalent of C’s ”?:” ternary operator? - Is it possible to write obfuscated one-liners in Python? - Numbers and strings - How do I specify hexadecimal and octal integers? - Why does -22 // 10 return -3? - How do I convert a string to a number? - How do I convert a number to a string? - How do I modify a string in place? - How do I use strings to call functions/methods? - Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings? - Is there a scanf() or sscanf() equivalent? - What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean? - Performance - Sequences (Tuples/Lists) - How do I convert between tuples and lists? - What’s a negative index? - How do I iterate over a sequence in reverse order? - How do you remove duplicates from a list? - How do you make an array in Python? - How do I create a multidimensional list? - How do I apply a method to a sequence of objects? - Why does a_tuple[i] += [‘item’] raise an exception when the addition works? - Dictionaries - Objects - What is a class? - What is a method? - What is self? - How do I check if an object is an instance of a given class or of a subclass of it? - What is delegation? - How do I call a method defined in a base class from a derived class that overrides it? - How can I organize my code to make it easier to change the base class? - How do I create static class data and static class methods? - How can I overload constructors (or methods) in Python? - I try to use __spam and I get an error about _SomeClassName__spam. - My class defines __del__ but it is not called when I delete the object. - How do I get a list of all instances of a given class? - Why does the result of id() appear to be not unique? - Modules General Questions Is there a source code level debugger with breakpoints, single-stepping, etc.?: - Wing IDE () - Komodo IDE () - PyCharm () Is there a tool to help find bugs or perform static analysis?. How can I create a stand-alone binary from a Python script? tool is Anthony Tuininga’s cx_Freeze. Are there coding standards or a style guide for Python programs? Yes. The coding style required for standard library modules is documented as PEP 8. Core Language Why am I getting an UnboundLocalError when the variable has a value? What are the rules for local and global variables in Python? In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects. Why do lambdas defined in a loop with different values all return the same result?. What are the “best practices” for using import in a module? In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.: - standard library modules – e.g. sys, os, getopt, re - third-party library modules (anything installed in Python’s site-packages directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc. - locally-developed modules. How can I pass optional or keyword parameters from one function to another?) What is the difference between arguments and parameters?. Why did changing list ‘y’ also change list ‘x’? If you wrote code like: >>> x = [] >>> y = x >>> y.append(10) >>> y [10] >>> x [10] you might be wondering why appending an element to y changed x too. There are two factors that produce this result: - Variables are simply names that refer to objects. Doing y = x doesn’t create a copy of the list – it creates a new variable y that refers to the same object x refers to. This means that there is only one object (the list), and both x and y refer to it. - Lists are mutable, which means that you can change their content. After the call to append(), the content of the mutable object has changed from [] to [10]. Since both the variables refer to the same object, using either name accesses the modified value [10]. If we instead assign an immutable object to x: >>> x = 5 # ints are immutable >>> y = x >>> x = x + 1 # 5 can't be mutated, we are creating a new object here >>> x 6 >>> y 5 we can see that in this case x and y are not equal anymore. This is because integers are immutable, and when we do x = x + 1 we are not mutating the int 5 by incrementing its value; instead, we are creating a new object (the int 6) and assigning it to x (that is, changing which object x refers to). After this assignment we have two objects (the ints 6 and 5) and two variables that refer to them (x now refers to 6 but y still refers to 5). Some operations (for example y.append(10) and y.sort()) mutate the object, whereas superficially similar operations (for example y = y + [10] and sorted(y)) create a new object. In general in Python (and in all cases in the standard library) a method that mutates an object will return None to help avoid getting the two types of operations confused. So if you mistakenly write y.sort() thinking it will give you a sorted copy of y, you’ll instead end up with None, which will likely cause your program to generate an easily diagnosed error. However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, += mutates lists but not tuples or ints (a_list += [1, 2, 3] is equivalent to a_list.extend([1, 2, 3]) and mutates a_list, whereas some_tuple += (1, 2, 3) and some_int += 1 create new objects). In other words: - If we have a mutable object (list, dict, set, etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change. - If we have an immutable object (str, int, tuple, etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object. If you want to know if two variables refer to the same object or not, you can use the is operator, or the built-in function id(). How do I write a function with output parameters (call by reference)?. How do you make a higher order function in Python?.[:] How can I find the methods or attributes of an object? For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class. How can my code discover the name of an object?! What’s up with the comma operator’s precedence?. Is there an equivalent of C’s ”?:” ternary operator??! Numbers and strings How do I specify hexadecimal and octal integers? Why. How do I convert a string to a number?’). How do I convert a number to a string?.0/3.0) yields '0.333'. How do I modify a string in place?' How do I use strings to call functions/methods?. Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?. are more powerful than C’s sscanf() and better suited for the task. Performance My program is too slow. How do I speed it up? That’s a tough one, in general. First, here are a list of things to remember before diving further: - Performance characteristics vary across Python implementations. This FAQ focusses on CPython. - Behaviour can vary across operating systems, especially when talking about I/O or multi-threading. - You should always find the hot spots in your program before attempting to optimize any code (see the profile module). - Writing benchmark scripts will allow you to iterate quickly when searching for improvements (see the timeit module). - module. - mini-HOWTO Sequences (Tuples/Lists) How do I convert between tuples and lists?. What’s a negative index?. How do I iterate over a sequence in reverse order? Use the reversed() built... How do you remove duplicates from a list? set keys (i.e. they are all hashable) this is often faster mylist = list(set(mylist)) This converts the list into a set, thereby removing duplicates, and then back into a list.. How do I create a multidimensional list?. How do I apply a method to a sequence of objects? Use a list comprehension: result = [obj.method() for obj in mylist] Why does a_tuple[i] += [‘item’] raise an exception when the addition works? This is because of a combination of the fact that augmented assignment operators are assignment operators, and the difference between mutable and immutable objects in Python. This discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects, but we’ll use a list and += as our exemplar. If you wrote: >>> a_tuple = (1, 2) >>> a_tuple[0] += 1 Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment The reason for the exception should be immediately clear: 1 is added to the object a_tuple[0] points to (1), producing the result object, 2, but when we attempt to assign the result of the computation, 2, to element 0 of the tuple, we get an error because we can’t change what an element of a tuple points to. Under the covers, what this augmented assignment statement is doing is approximately this: >>> result = a_tuple[0] + 1 >>> a_tuple[0] = result Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment It is the assignment part of the operation that produces the error, since a tuple is immutable. When you write something like: >>> a_tuple = (['foo'], 'bar') >>> a_tuple[0] += ['item'] Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment The exception is a bit more surprising, and even more surprising is the fact that even though there was an error, the append worked: >>> a_tuple[0] ['foo', 'item'] To see why this happens, you need to know that (a) if an object implements an __iadd__ magic method, it gets called when the += augmented assignment is executed, and its return value is what gets used in the assignment statement; and (b) for lists, __iadd__ is equivalent to calling extend on the list and returning the list. That’s why we say that for lists, += is a “shorthand” for list.extend: >>> a_list = [] >>> a_list += [1] >>> a_list [1] This is equivalent to: >>> result = a_list.__iadd__([1]) >>> a_list = result The object pointed to by a_list has been mutated, and the pointer to the mutated object is assigned back to a_list. The end result of the assignment is a no-op, since it is a pointer to the same object that a_list was previously pointing to, but the assignment still happens. Thus, in our tuple example what is happening is equivalent to: >>> result = a_tuple[0].__iadd__(['item']) >>> a_tuple[0] = result Traceback (most recent call last): ... TypeError: 'tuple' object does not support item assignment The __iadd__ succeeds, and thus the list is extended, but even though result points to the same object that a_tuple[0] already points to, that final assignment still results in an error, because tuples are immutable. Dictionaries How can I get a dictionary to store and display its keys in a consistent order? Use collections.OrderedDict. I want to do a complicated sort: can you do a Schwartzian Transform in Python?. How can I sort one list by values from another list?. Objects What is a class?. What is a method? A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined as functions inside the class definition: class C: def meth (self, arg): return arg * 2 + self.attribute What is self??. How do I check if an object is an instance of a given class or of a subclass of it?() What is delegation?. How do I call a method defined in a base class from a derived class that overrides it?. How) ... How do I create static class data and static class methods?. How can I overload constructors (or methods) in Python?. I try to use __spam and I get an error about _SomeClassName__spam.. My.. Why does the result of id() appear to be not unique? The id() builtin returns an integer that is guaranteed to be unique during the lifetime of the object. Since in CPython, this is the object’s memory address, it happens frequently that after an object is deleted from memory, the next freshly created object is allocated at the same position in memory. This is illustrated by this example: >>> id(1000) 13901272 >>> id(2000) 13901272 The two ids belong to different integer objects that are created before, and deleted immediately after execution of the id() call. To be sure that objects whose id you want to examine are still alive, create another reference to the object: >>> a = 1000; b = 2000 >>> id(a) 13901272 >>> id(b) 13891296 Modules How do I create a .pyc file? When a module is imported for the first time (or when the source –('foo.py') This will write the .pyc to a __pycache__ subdirectory in the same location as foo . How do I find the current module name?()).. __import__(‘x.y.z’) returns <module ‘x’>; how do I get z? Consider using the convenience function import_module() from importlib instead: z = importlib.import_module('x.y.z') When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?-reading of a changed module, do this: import importlib import modname importlib importlib >>> import cls >>> c = cls.C() # Create an instance of C >>> importlib'
https://documentation.help/Python-3.4.4/programming.html
CC-MAIN-2020-10
refinedweb
2,495
65.73
Closed Bug 980384 Opened 6 years ago Closed 6 years ago Assertion failure: slot < num Value Slots(), at jit/Baseline Frame .h:150 or Bus Error Categories (Core :: JavaScript Engine: JIT, defect, critical) Tracking () mozilla30 People (Reporter: decoder, Assigned: wingo) Details (Keywords: assertion, crash, testcase, Whiteboard: [jsbugmon:update]) Attachments (2 files) The following testcase asserts on mozilla-central revision 8122ffa9e1aa (run with --fuzzing-safe): function testcase() { try { testcase('(function (){var arguments;});'); } catch (e) { return (testcase)); } } testcase(testcase); Crashes with a bus error: Program received signal SIGBUS, Bus error. 0x00007ffff7ff1c4c in ?? () (gdb) x /i $pc => 0x7ffff7ff1c4c: testl $0x200,-0x8(%rbp) (gdb) info reg rbp rbp 0xfff9000000000000 0xfff9000000000000 Marked s-s based on that. status-firefox30: --- → affected Whiteboard: [jsbugmon:update,bisect] I would expect that we bailout from the try block when we exceed the recursion limit, but I do not see where the catch block is important here. Jandem might be the right person to ask about this issue. Flags: needinfo?(jdemooij) Whiteboard: [jsbugmon:update,bisect] → [jsbugmon:update] JSBugMon: Bisection requested, result: === Tinderbox Build Bisection Results by autoBisect === The "good" changeset has the timestamp "20140225091817" and the hash "ecfb4d63943f". The "bad" changeset has the timestamp "20140225092218" and the hash "cc698e2ff036". Likely regression window: Needinfo from wingo based on comment 4, likely regressed by bug 962599. Flags: needinfo?(wingo) Assignee: nobody → wingo Comment on attachment 8388401 [details] [diff] [review] Fix frame marker for half-constructed stack frames Unfortunately I was unable to produce a test case. Your test case recurses until it reaches the stack limit, then hammers at the stack limit with a recursive function with many locals until GC happens during an early stack check. There's no obvious way to make the test terminate, at least that I can see, and it's going to be n-squared on Mac due to its larger stack size and the cost of constructing the exception. Attachment #8388401 - Flags: review?(jdemooij) Flags: needinfo?(wingo) Comment on attachment 8388401 [details] [diff] [review] Fix frame marker for half-constructed stack frames Review of attachment 8388401 [details] [diff] [review]: ----------------------------------------------------------------- Good catch. Attachment #8388401 - Flags: review?(jdemooij) → review+ Flags: needinfo?(jdemooij) This shouldn't have landed without security approval since it doesn't have a rating and isn't clear what branches it affects. Status: NEW → RESOLVED Closed: 6 years ago Resolution: --- → FIXED Target Milestone: --- → mozilla30 > There's no obvious way to make the test terminate, at least that I can see, > and it's going to be n-squared on Mac due to its larger stack size and the > cost of constructing the exception. Perhaps you could fix bug 813646 and/or bug 735082? I've stopped fuzzing these too-much-recursion corners because even fuzz testcases are slow and unreliable. Meanwhile, Decoder is finding plenty of bugs with this pattern (e.g. this bug, bug 978811, bug 970252, bug 957716). Status: RESOLVED → VERIFIED JSBugMon: This bug has been automatically verified fixed. (In reply to Ryan VanderMeulen [:RyanVM UTC-4] from comment #10) > This shouldn't have landed without security approval since it doesn't have a > rating and isn't clear what branches it affects. > As I understand the guidelines, this was simply a recent regression in m-c that never shipped, and so landing it directly was OK. status-firefox29: --- → unaffected status-firefox-esr24: --- → unaffected Group: core-security
https://bugzilla.mozilla.org/show_bug.cgi?id=980384
CC-MAIN-2020-16
refinedweb
555
51.68
I am trying to install fastai in my windows 10. My laptop has no GPU, I am using pip in cmd to install fastai. In pip page(), they mentioned to install pytroch before installing fastai. I followed that step, For pytorch()- pip install torch==1.6.0+cpu torchvision==0.7.0+cpu -f Then, For fastai- pip install fastai These python packages are installed successfully. from fastai.vision import * This statement is imported fastai.vision successfully, But when I use the ImageDataBunch function, data = ImageDataBunch.from_folder(path, train=".", valid_pct=0.2, size=512, bs=4, seed=24) It shows error, NameError: name ‘ImageDataBunch’ is not defined I do not know what is happening, Could you please help me to solve this error, thanks
https://forums.fast.ai/t/imagedatabunch-is-not-defined/77405
CC-MAIN-2021-10
refinedweb
124
66.33
On Apr 1, 6:29 am, jfager <jfa... at gmail.com> wrote: > On Apr 1, 3:29 am, Kay Schluehr <kay.schlu... at gmx.net> wrote: > > > > "Discoverable", as in built-in tools that let you have the following > > > conversation: "Program, tell me all the things I can configure about > > > you" - "Okay, here they all are". No digging through the source > > > required. > > > But this doesn't have any particular meaning. If I run a dir(obj) > > command all attributes of obj will be returned and I can be sure these > > are all. In C# I can reflect on attributes of an assembly which is a > > well defined entity. "Program" is not an entity. It's kind of a user > > interface name in StarTreck ( which prefers "computer" for this > > purpose though ). This way we cannot design systems. > > "Module and transitive graph of other modules (constructed through > 'import' statements), tell me all the things I can configure about > you". Is that a little clearer? Using shelve, which I suggested earlier, you have to rely on modules to choose the options they want to make available. You could require them to store configs. on a per-module basis in separate files, or require them to use separate namespaces in the shelf. It could also be possible to interface with the target process's garbage collector, but you're limited to objects you can identify in the list of tracked objects, and only the ones that are mutable at that.
https://mail.python.org/pipermail/python-list/2009-April/531353.html
CC-MAIN-2014-15
refinedweb
245
73.58
User talk:Kugelschreiber Contents - 1 Welcome - 2 Sysop - 3 By the way - 4 Chickenhawks - 5 Presenting my opinion of fuckball's reading comprehension, since he chooses to shit up my page. - 6 Sock status - 7 Mona - 8 Edit War - 9 Coop - 10 Weird block - 11 HAIL ZEON! - 12 Irreligion as Intellectual Privilege - 13 You reverted my edits - 14 Sysoprevoked and deautopatrolled - 15 Just doing my monthly or so check - 16 It's not worth an edit war - 17 Why are you harassing people about uploads in progress? - 18 Equivocating academic criticism with mob lynching - 19 Coop case Welcome[edit] Hello and welcome to Rationalwiki! This wiki can always use more Europeans! And also, we should put a stop to calligraphy snobs 146.185.147.55 (talk) 21:36, 25 January 2016 (UTC) - Thank you very much, but I'm no calligraphy snob, I'm just remembering my school days, where the teachers forced us up to a certain grade to use fountain pens instead of the awesomely convenient and very cheap (if you look hard enough and roam your local bigger mall a bit, you'd sure find a free one intended as a freebee) ballpoint pen. The pens themselves were inreliable, broke easily, the ink cartridge had to be replaced often, your fingers were often dirty with ink as was your pencil case. Thanks goodness that's a thing of the past now for me.--Kugelschreiber (talk) 21:48, 25 January 2016 (UTC) Sysop[edit] Your edits at Sargon of Akkad seemed pretty high quality. As a result:. Herr FüzzyCätPötätö (talk/stalk) 02:17, 28 January 2016 (UTC) - Wowzers, thanks!--Kugelschreiber (talk) 16:41, 28 January 2016 (UTC) By the way[edit] How do I get a website accepted to the 'webshites' page? -Webshite Hunter - There is no special procedure, AFAIK, the webshite list is no different from other articles. You just add the webshite to the list under the appropriate category (a description is optional but welcomed) and if someone objects to the inclusion of this website, you discuss it on the talk page (please no edit wars, there's been too much of that lately and it wasn't nice to look at).--Kugelschreiber (talk) 18:52, 8 February 2016 (UTC) Chickenhawks[edit] I noticed your Rand Paul edit and someone else's revert. Margaret Thatcher is listed as a chickenhawk too. Sometimes the labels seem to get carried away. I agree with the other person that chickenhawk's don't have to be draft dodgers, but this label isn't very useful if it's applied to anyone with no military experience who advocates a military response to anything. --Read-Write (talk) 02:28, 10 February 2016 (UTC) - Where do we draw the line then and actually, in most cases people mean exactly that (draft-dodgers going all war-happy. Why not calling people, who clamor for war but were not subject to the draft "war hawks" instead of "chickenhawks"? It would be spot-on).--Kugelschreiber (talk) 02:31, 10 February 2016 (UTC) - Argumentum ad dictionariam? Fuck right off with that. There is no consensus on the chickenhawk talk page, not even if one includes Arisboch's dribblings in the discussion. How has Rand Paul "supported the troops" that he is enthusiastic about sending off to fight? CamelCasePragmatist (talk) 02:50, 10 February 2016 (UTC) - To answer your question about war hawks, calling someone a chicken hawk adds a layer of hypocrisy that is not present in all warhawks. CamelCasePragmatist (talk) 02:53, 10 February 2016 (UTC) - No need to get abusive about it.Read-Write (talk) 02:54, 10 February 2016 (UTC) - That is making the definition of "chickenhawk" even more broad, than it already is in the article. Really orwellian.--Kugelschreiber (talk) 02:57, 10 February 2016 (UTC) - If Rand Paul is a ckickenhawk then Hillary Clinton is too. Read-Write (talk) 02:59, 10 February 2016 (UTC) - How about "armchair warrior" then? More or less in the same category as internet tough guy. CamelCasePragmatist (talk) 03:04, 10 February 2016 (UTC) - I don't see why not.--Kugelschreiber (talk) 03:07, 10 February 2016 (UTC) Presenting my opinion of fuckball's reading comprehension, since he chooses to shit up my page.[edit] It's not spam, shit-for-brains. What part of "Comment here again and you get double the comments on your own page." do you not fucking understand? Are you retarded, you fucking cum stain? --Castaigne2 (talk) 17:42, 15 February 2016 (UTC) - What else would call copy-pasting the same message over and over (and over and over... you get the picture) on someone's talk page? I'm no expert, so what is it called? Wandalism? Flaming? Shitposting? UBE?--Kugelschreiber (talk) 17:48, 15 February 2016 (UTC) - Well, since you lack the reading comprehension to understand what was being said, I would call it the necessary amount of dictation required to allow something to seep through that thick fucking skull of yours. If we were in person, mong loving nutsack handle, right now I'd be slapping you every time you opened your mouth. Yes, I'm being serious here. You're apparently one of those who only understands physical instruction. Must make educating a bitch for you. --Castaigne2 (talk) 17:55, 15 February 2016 (UTC) Degenerate and base you are, friend of a dick tranny rider. You are absolutely determined for me to have fun with you. Well, my dear erection basher, I have never been one to pass up invitations. --Castaigne2 (talk) 17:55, 15 February 2016 (UTC) Sock status[edit] Hi Kugelschreiber, some people suspect that you are a sock of a recently banned user User:Arisboch. It seems to me that I may as well ask you directly so that you can state it yourself one way or the other. As you may know we don't use checkuser here so there is no concrete way for us to determine if you are a sock or not. You may also be aware that if you are a sock of Arisboch you will be banned for evading a community sanctioned ban (albeit one that I personally disagreed with). Tielec01 (talk) 01:06, 2 March 2016 (UTC) - That's just nonsense. The only things I did was piratecopying his signature (which was apparently in turn piratecopied from somewhere else (many other people have links in their signatures, so that people can joke-ban or e-mail them easier)) and contradicting Mona (which quite a few others did). Mona has a history of calling anyone disagreeing with her a sock of Arisboch or Avenger.--Kugelschreiber (talk) (mail) (block) 14:33, 2 March 2016 (UTC) 14:33, 2 March 2016 (UTC) - Maybe you should have a checkuser tool to avoid those witch hunts as to who is a sock of whom? It gets tiresome to hear accusations against pretty much everybody that they are a sock of someone else just for sharing an opinion... Pizzameister (talk) 14:50, 2 March 2016 (UTC) - It's not so much an opinion as it is all of them. 142.124.55.236 (talk) 15:22, 2 March 42016 AQD (UTC) - Some of us admit to being socks. Mostly so I can edit on my phone but still. StickySock (talk) 15:34, 2 March 2016 (UTC) - Editing RationalWiki on the phonr despite the RationalWiki having no mobile page like Wikipedia or even Conservapedia? --Kugelschreiber (talk) (mail) (block) 15:36, 2 March 2016 (UTC) 15:36, 2 March 2016 (UTC) - RW has a crappy mobile support. But I think David Gerard knows that and is either unwilling or unable to do anything about that... Pizzameister (talk) 15:37, 2 March 2016 (UTC) Mona[edit] You and Mona have had an open feud and idk why you need to bother her. We all know your "welcome" wasn't sincere. She is barely a recurring user and only edits a few pages she seems to have an attachment too; if you don't like the edits then change when she is gone.--Owlman (talk) (mail) 19:23, 3 April 2016 (UTC) 19:23, 3 April 2016 (UTC) - Yes, the welcome was ironical.--Kugelschreiber (talk) (mail) (block) 19:27, 3 April 2016 (UTC) 19:27, 3 April 2016 (UTC) Edit War[edit] I had no idea this was going to be this much of an issue. It is silly pointless disputes such as this that are hurting RationalWiki. In order to try to calm things down, I'm going to refrain from participating in this stupid skirmish. What you do is up to you. Pbfreespace3 (talk) 03:05, 12 April 2016 (UTC) - And by "refusing to participate in this skirmish" you mean raise a coop case accusing him of being a sock, that scores a 10/10 on the irony meter. Bubba41102The place where you can scream at me 12:54, 12 April 2016 (UTC) - No, I said I wanted the edit war to stop. This is one way of achieving that, and resolving all future edit wars involving this user. Pbfreespace3 (talk) 15:44, 12 April 2016 (UTC) - In other words having users banning, that disagree with out on trumped up charges. Cool.--Kugelschreiber (talk) (mail) (block) 16:04, 12 April 2016 (UTC) 16:04, 12 April 2016 (UTC) - The coop is the coop,not mainspace. There were edit wars in the past that went on for weeks with dozens of reverts. That was very bad, much worse than simply resolving our differences in the coop. Pbfreespace3 (talk) 15:46, 12 April 2016 (UTC) Coop[edit] A case involving you has been raised at the Chicken Coop. Feel free to comment. Bubba41102The place where you can scream at me 12:52, 12 April 2016 (UTC) - Thanks.--Kugelschreiber (talk) (mail) (block) 12:57, 12 April 2016 (UTC) 12:57, 12 April 2016 (UTC) Weird block[edit] What's with this weird block?!--Harkinian | Oah! (talk) 01:08, 17 April 2016 (UTC) - Sorry, just a fun game among the gods.--Kugelschreiber (talk) (mail) (block) 01:14, 17 April 2016 (UTC) 01:14, 17 April 2016 (UTC) HAIL ZEON![edit] HAIL! HAIL! Zero (talk - contributions) 21:29, 20 April 2016 (UTC) - Death to the Zabis! Death to the Feddies! The teachings of Zeon Zum Deikon will lead the Spacenoids and all humanity into a bright future!!--Kugelschreiber (talk) (mail) (block) 21:37, 20 April 2016 (UTC) 21:37, 20 April 2016 (UTC) - Valar Morghulis! Pizzameister (talk) 23:09, 20 April 2016 (UTC) Irreligion as Intellectual Privilege[edit] Can you make a serious contribution to the discussion rather than asking inane questions like "why not"? And if you really don't understand why, I recommend you pick up some economics textbooks to understand the terms being discussed. It's implied you should come to the table prepared to contribute to the discussion meaningfully rather than have someone spoonfeed you every minute detail of the terms involved. Otherwise if you haven't done your research, you should not butt in. Withoutaname (talk) 21:29, 23 May 2016 (UTC) - Wow, that's really pathetic.--Kugelschreiber (talk) (mail) (block) 21:43, 23 May 2016 (UTC) 21:43, 23 May 2016 (UTC) - Except this isn't about conspiracy theories, this is about you being an obnoxious child asking "why" when someone talks about how trying to move faster than the speed of light will break relativity. It's more accurate to call your strategy an attempt at sealioning and my dismissal an appropriate response to that. Withoutaname (talk) 22:19, 23 May 2016 (UTC) - That's a goddamn lie. You were the first one on that thread resp. page to claim, that the end of religion necessitates the end of capitalism.--Kugelschreiber (talk) (mail) (block) 22:32, 23 May 2016 (UTC) 22:32, 23 May 2016 (UTC) - Well, the end of capitalism would certainly help, but I was merely commenting on capitalism's relationship to the public education system. Which, by the way, is a well-known fact, and not the product of any conspiracy theories. You didn't so much provide a counterargument as ask a silly question that you should have known the answer to beforehand, and now like a child caught in the act, you yell "that's a lie" when someone points out your sealioning. Withoutaname (talk) 22:52, 23 May 2016 (UTC) - There was no sealioning. It was a honest question on why you think that the end of religion necessitates an end of capitalism coming before it (that's how I understood your post). Well, according to the article, the existence of sealioning leads to newbies being suspected in sealioning (and sometimes, this accusation is used to silence other people).--Kugelschreiber (talk) (mail) (block) 23:00, 23 May 2016 (UTC) 23:00, 23 May 2016 (UTC) - I've never really given it much thought until David mentioned it to me, but you're starting to sound more like Arisboch with every post you make. That's not supposed to be a compliment, by the way. In any case, I highly doubt you're a newbie. - The existence of just about any monetary system really, and in particular laissez-faire capitalism, prioritizes those who have the ability to pay for their education over those who do not, i.e. who has more capital. The means by which knowledge is produced and reproduced are privately owned. Even if it were the case that "univeral" education was provided with "free" tuition, as proclaimed in some social democratic countries, under capitalism the cost of maintenance and upkeep is shifted financially to a government responsible for oversight of the education system, whose politics would then be greatly affected by whoever's in charge of the government. The government then shifts the financial burden to the rest of the working class population through taxation, and may decide to levy out punishment for those unable to pay the taxes (i.e. not the upper class). This would again boil down effectively to prioritizing who is able to pay for education. Not to mention the cost of transportation to the education system itself, which may or may not be subsidized. Withoutaname (talk) 23:36, 23 May 2016 (UTC) - I recommend moving the second parapgraph to this page.--Kugelschreiber (talk) (mail) (block) 23:42, 23 May 2016 (UTC) 23:42, 23 May 2016 (UTC) - Fine, but it should have been self-evident to everyone who was already in the conversation and wanted to contribute something meaningful. Withoutaname (talk) 23:48, 23 May 2016 (UTC) - It isn't even remotely self-evident, you absurd prick. At best, you have a valid claim that monied elites generally have preferential access to a higher standard of education. Good luck explaining how that necessarily prohibits universal education about religion. Robledo (talk) 19:55, 24 May 2016 (UTC) - And what has that all to do with education about religion??--Kugelschreiber (talk) (mail) (block) 20:03, 24 May 2016 (UTC) 20:03, 24 May 2016 (UTC) - Good god, I give only part of the proof and you start demanding the whole thing when I told you this is all covered in Introduction to Capitalism 101. Pick up a goddamn economics textbook. The very title of the essay is "irreligion as intellectual privilege" for chrissake. - Sealioning verb 1. Demanding answers, usually of entry-level topics far below the actual conversation. - Withoutaname (talk) 20:56, 24 May 2016 (UTC) - You're the only one here to make that kinda connection. There was no sealioning on my part, no matter how often you'll claim such a bullshit.--Kugelschreiber (talk) (mail) (block) 21:01, 24 May 2016 (UTC) 21:01, 24 May 2016 (UTC) - That's because you decided to go and interject yourself in a conversation with an utterly inane question that given enough effort you could have answered yourself. I'll wait until you can muster an actual rebuttal to my statement. Withoutaname (talk) 21:23, 24 May 2016 (UTC) - And magically prevented others and you from talking about it any further. Really, fuck off.--Kugelschreiber (talk) (mail) (block) 21:33, 24 May 2016 (UTC) 21:33, 24 May 2016 (UTC) - Kugelschreiber: As you're apparently shit at this stuff, SFTU for a bit. - Withoutaname: Proof or wind your fucking neck in. Protip: Can't be done, so you'd best stop digging. Robledo (talk) 21:39, 24 May 2016 (UTC) - Robledo: If you know what you're talking about and you can provide a counterargument for universal education being possible under capitalism, feel free to do so on the essay talk page. In my understanding of capitalism as an economic system, it will first funnel the money and resources from the many to the few (via surplus-value extraction and capital accumulation) and then commodify public education to sell it for profit. Since access is held under private ownership, it will be restricted against those with the least ability to pay for it in terms of money, so it will not be truly universal. Do you agree with this? Withoutaname (talk) 01:26, 25 May 2016 (UTC) I'll keep the discussion here, thanks, unless KS objects. And unsurprisingly, no, I don't agree with your analysis, and I find it genuinely difficult to believe you do either. - You're claiming a) universal education about religion (UEAR) is impossible under a capitalist system, and that b) this should be self-evident to anyone with a sufficient understanding of capitalism. - These are extraordinarily strong claims to make about a complex system of human interaction over an indefinite period. - a), in particular, can be contradicted simply by showing that UEAR could be possible under a capitalist system, regardless of likelihood. - That's an incredibly low bar, and you don't get to raise it any higher by self-defining what "truly" universal looks like. - You'll also find it difficult to deny that the infrastructure is already in place, unless you really want to go batshit insane and pretend there are no such fucking things as publically-funded schools and libraries. - Equally awkward will be explaining away the progressive movements of the late 19th and early 20th century that saw educational provision steadily increase for ever more children of ever higher ages. In short, you've picked a really dumb hill to die on. Wind your fucking neck in, and knock it off with the retarded hyperbole. You also owe KS an apology. Robledo (talk) 22:36, 25 May 2016 (UTC) What I don't understand is why you view capitalism as a monolithic block, the same way McCarthyites view Marxism - but I suppose all zealots are the same under the skin. There is no reason you can't have quality state education in a capitalist society, that's why taxation exists, so the government can do what the free market isn't good at doing. If you think otherwise, you should have addressed KS on the talk page of my essay instead of resorting to the Courtier's Reply like a defeated theist. Lord Aeonian (talk) 00:40, 26 May 2016 (UTC) - "why you view capitalism as a monolithic block" I don't, where are you getting this? I'm talking about capitalism as it functions worldwide, how every implementation including state sponsored solutions simply shift the problem elsewhere. I could point to the historical implementation and development of capitalism since the 1700s onward and say that there has been no examples of universal education under capitalism. I also think it quite strange you call heated discussion on a website "zealotry" as if it had any real world consequences. - I've already addressed why publically-funded schools and libraries (what you nominally call "universal education" and one that I'm already familiar with) still fail to provide proper education for the lowest segments of society. You've also used "universal education" to mean education in a single country, which wasn't what I meant at all and one objection that would have been more appropriate to the discussion we were having on the talkpage. - Kugelschreiber walked into a conversation asking a question that he could have taken two seconds to answer himself by using Google rather than providing any sort of counterargument or expecting me to provide all the answers for him. I find it baffling none of you see how frustrating that is. Withoutaname (talk) 12:01, 26 May 2016 (UTC) - "I don't, where are you getting this? I'm talking about capitalism as it functions worldwide, how every implementation including state sponsored solutions simply shift the problem elsewhere." - There are many implementations of capitalism. It does not "function worldwide" at all. That is an example of the monolithic thought I'm referring to. And why do you say "every implementation...simply shift[s] the problem elsewhere?" You're assuming the Marxist understanding of society is correct, when that is what you're supposed to support in the first place. Circular reasoning. - "I could point to the historical implementation and development of capitalism since the 1700s onward and say that there has been no examples of universal education under capitalism." - Once we figure out what you mean by "universal education," sure. But expecting "universal education" without a universal government is silly, so your criteria wouldn't be fulfilled regardless of whether Marxism or capitalism was in place in the diverse countries. - "I've already addressed why publically-funded schools and libraries (what you nominally call "universal education" and one that I'm already familiar with) still fail to provide proper education for the lowest segments of society." - And you blame this on...capitalism? Culture is much bigger factor. East Asia - the Marxist PRC and the capitalist SK and Japan - have excellent educational systems not so much because of quality as opposed to culture. - "Kugelschreiber walked into a conversation asking a question that he could have taken two seconds to answer himself by using Google rather than providing any sort of counterargument or expecting me to provide all the answers for him." - Your original statement was begging the question. You basically said "we all agree education cannot be accomplished in a capitalist system," which is not only a false assessment of your audience but a silly statement to began with. You addressed the issue with the Courtier's Reply rather than even providing resources you think would convince people your implication is correct. - "I find it baffling none of you see how frustrating that is." - And I find this ironic. You act as if we have never considered these questions, and most importantly, you act as if Marxism is the obvious solution and anyone who disagrees is uneducated on the issue. And because of this - shall I say, presuppositionalism - you come off as ridiculously arrogant and over confident. Lord Aeonian (talk) 12:37, 26 May 2016 (UTC) - Just because there are many implementations of capitalism (laissez-faire, liberal democracy, social democracy) does not mean it cannot function worldwide. In fact, you can even analyze how much more international and globalized modern-day capitalism is. And I think you're just throwing "monolithic thought" around as a buzzword because I don't view capitalism at all as a monolithic block, the same way you're different from a McCarthyite and a free-market capitalist, but just as ideologically committed as any of the latter two when you zealously condemn all "zealotry" as being the same. - "You're assuming the Marxist understanding of society is correct, when that is what you're supposed to support in the first place. Circular reasoning." It wasn't circular reasoning as much as my assumption that everyone in that thread was up to the same level of discourse as I was, and in that level of discourse we had already assumed/proved it to be the case a priori. But I guess you can't even muster up to that level of discourse, the overestimation of which was my fault. - "expecting "universal education" without a universal government is silly, so your criteria wouldn't be fulfilled regardless of whether Marxism or capitalism was in place in the diverse countries." First, why would we need a universal government to provide universal education? And secondly how can an "implementation" of Marxism be an economic basis for universal education? Marxism is a positive, not normative, philosophy and countries alone cannot provide universal education for anybody other than those within the country (and even then, sometimes not even then). - "You addressed the issue with the Courtier's Reply rather than even providing resources you think would convince people your implication is correct." I suppose I did err in trying to assess my audience, but the page you linked specifically tells me I'm allowed to tell people to read a book: In addition, it is not fallacious to tell, for example, a creationist to read more on evolution, if they clearly do not understand what they are talking about, and are basing their evidence on false premises (such as, for example, believing that abiogenesis = evolution)—Courtier's Reply - "You act as if we have never considered these questions, and most importantly, you act as if Marxism is the obvious solution and anyone who disagrees is uneducated on the issue." By the arguments that you use, like how capitalism "does not function worldwide at all" I have to wonder how much you really know about the historical developments of capitalism and globalization over the last century. So I have to wonder whether you really have considered these questions. Also Marxism is a method of analysis, not a solution in and of itself — it only points to possible solutions. You reject the Marxist "worldview" as "presuppositionalism" because you disagree with its validity, while seemingly refusing to criticize the validity of the base assumptions that form your own Enlightenment worldview. I rather think it's arrogant to dismiss an entire "worldview" out of hand simply because you feel a little too comfortable with your current one. But don't mind me, continue eating out of that trash can. Withoutaname (talk) 01:25, 25 September 2016 (UTC) - Yay, necroposting for the glorious revolution!!!--The (((Kigel))) (talk) (mail) 02:49, 25 September 2016 (UTC) 02:49, 25 September 2016 (UTC) - What's necroposting? I am not the Ombud's man 16:28, 25 September 2016 (UTC) - Posting stuff on a thread no-one has posted in weeks, months or years.--The (((Kigel))) (talk) (mail) 16:34, 25 September 2016 (UTC) 16:34, 25 September 2016 (UTC) You reverted my edits[edit] Well your site is a "crank" wiki too. Why do you deny it?I guess just as Conservapedia likes calling its opponents biased, you are no different. You like calling wikis you disagree with "crank" when you are one of them. And don't call people a "damned crybaby" you filthy mouthed fellow. Knowthefacts (talk) 11:57, 27 May 2016 (UTC) --JorisEnter (talk) 11:58, 27 May 2016 (UTC) - do you want references for the "alt-right" article edits? Kashifv (talk) 03:45, 26 September 2016 (UTC) - Talk pages were invented for a reason. But why would you use this talk page here instead of another one? I am not the Ombud's man 18:38, 26 September 2016 (UTC) Sysoprevoked and deautopatrolled[edit] For 1 day due to edit warring. Note that this doesn't imply you're in the wrong -- merely that you warred. If I forget to give your rights back (autopatrolled, sysop), feel free to pop in to my talkpage. Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 17:35, 3 July 2016 (UTC) Just doing my monthly or so check[edit] Hi, and blessed be! As it says in the title, but I couldn't resist leaving a message. You seem to have the heart in the right place. How can you stand this environment? By observing just every now and then, I think one may gain a clearer picture than by being involved daily. And RW is obviously an even worse place thaen when I left it even removing myself out of the whole thing. Well, at least, nothing that has happened for most of the year can be blamed on me. Cheers Uppivindinn (talk) 18:28, 16 July 2016 (UTC) - TBH out of boredom.--The (((Kigel))) (talk) (mail) 21:31, 16 July 2016 (UTC) 21:31, 16 July 2016 (UTC) It's not worth an edit war[edit] But we can and do remove WIGO pieces that people downvote enough as not really worth the visual space and promotion they get from being on the WIGO. ikanreed You probably didn't deserve that 17:39, 18 July 2016 (UTC) - What's the treshold? How many downvotes is required for a removal?--The (((Kigel))) (talk) (mail) 18:26, 18 July 2016 (UTC) 18:26, 18 July 2016 (UTC) - No threshold. Hence why it's not worth an edit war. ikanreed You probably didn't deserve that 18:46, 18 July 2016 (UTC) - I don't think, that this is the right way to deal with WIGO entries, at least not with WIGO entries that are not spam, trolling, blatantly racist, xenophobic or similar.--The (((Kigel))) (talk) (mail) 19:02, 18 July 2016 (UTC) 19:02, 18 July 2016 (UTC) - That's because you're quite silly. ikanreed You probably didn't deserve that 19:31, 18 July 2016 (UTC) Why are you harassing people about uploads in progress?[edit] I'm confused. Images take about a half hour to process due to weirdness and you seem to just be angry at random editors for it ikanreed You probably didn't deserve that 19:58, 16 August 2016 (UTC) - This bug has been known for months or even years and none of the tech staff (which, AFAIK, consists only of David Gerard. Correct me if I'm wrong) did anything about it. The Wikimedia software version is hopelessly obsolete, too and lacks many features even this goddamn Conservapedia has. What are the techs doing???--The (((Kigel))) (talk) (mail) 20:16, 16 August 2016 (UTC) 20:16, 16 August 2016 (UTC) - What kind of powers do you think that tech rights give me? As far as I can tell it's the following: the ability to edit the wikitext supporting special: pages, the ability to access a few specific tools(such as the edit filter), and the ability to edit the mediawiki namespace. ikanreed You probably didn't deserve that 20:42, 16 August 2016 (UTC) - I'm not talking about the users of this wiki who're in the user group "tech", I'm talking about the "technical staff" with direct access to the server. AFAIK it's only David Gerard who has such access and he does nothing to fix all these numerous bugs and update the wiki.--The (((Kigel))) (talk) (mail) 20:57, 16 August 2016 (UTC) 20:57, 16 August 2016 (UTC) Equivocating academic criticism with mob lynching[edit] That's some serious doublethink you have going on there. Withoutaname (talk) 00:16, 28 September 2016 (UTC) Coop case[edit] Since you've expressed an interest in voting in it, don't miss the current coop case. All the best, Reverend Black Percy (talk) 22:54, 28 September 2016 (UTC)
https://rationalwiki.org/wiki/User_talk:Kugelschreiber
CC-MAIN-2020-24
refinedweb
5,218
59.64
Mens Sana 2020-11-29T15:13:52-05:00 Jessica Szmajda Handling Departures 2020-11-25T00:00:00-05:00 <h3 id="im-writing-a-book">I’m writing a book!</h3> <p>I’ve been working on it for a while now, and I’m over 60,000 words into my first draft. It’s a lot of work, but I hope helpful. A friend of mine told me that if I help even just one person, it’ll have been worth it. I think he’s right. That kind of motivation is really helpful, thanks Casey :)</p> <p>I’m writing the book I wished I’d had the first time I became CTO. It’s a collection of thoughts, pointers, and ideas; things that have worked for me and things that haven’t. I hope it is, if nothing else, a light in the darkness.</p> <p>Every work thrives on feedback. To that end, I’m going to share some bits in a pieces here from time to time. I hope you’ll let me know what you think! Please leave a comment below :)</p> <p>I wanted to start with a section from my notes on Performance Management, <strong>Handling Departures</strong>.</p> <h3 id="handling-departures">Handling Departures</h3> <p>Sometimes people leave because they’ve decided to move on and sometimes you’ve made the decision. Either case should be handled with grace and dignity. How someone leaves your company is how they’ll remember you, and how they remember you is how they’ll speak of you. That word of mouth can go a long way in your favor or against it.</p> <p>If you’ve made the decision that it’s not going to work out, you should act as quickly as you can. If you let things drag on, the employee can usually tell that you or your leadership team have lost faith in them. They become demotivated or even toxic. At worst, I’ve seen employees in this “walking dead” state start to drag others down with them.</p> <p>Act quickly and give your departing employee a generous severance package. Severance is your way of giving that person respect and time to find their next opportunity. There was a poor fit in some way between that person and your job—it doesn’t mean they’re incompetent or incapable. I’ve seen someone I let go go on to become the CTO of another company and be quite successful. It’s all about the person, the company, and the specific time.</p> <p>I like to say “this isn’t working out, and I’m going to help you find a place where you’ll be happier.” When there’s a bad fit, the departing person is rarely happy.</p> <p>When you act with grace and are respectful of the other person it carries weight. If your paths cross again it’s far more likely they’ll remember your time together as a positive experience.</p> <p>If it’s your employee who has decided to leave, you have the option to try to retain them. If they’re leaving because they can get more compensation, then maybe you were off in some way. Review your compensation theory and change your model if you must, but don’t leave your model—stretching to retain a departing employee can be a vector for inequity. If they’re leaving for a different kind of role or an exciting new mission, there’s often very little you can do to change their mind. In the past I’ve countered employees who had an exciting new offer with a large retention package. While I was sometimes successful in retaining them, it often changed the nature of the relationship and turned them into a mercenary. That can be ok to a point, but mercenaries can be known to cut corners and not care as much about the long-term quality of the work. I’d much rather have a team of missionaries.</p> <p>No matter why someone leaves, when it’s clear they are going to leave let their Squad know quickly so they can start offboarding. Your organization will have an easier time remodeling itself around the loss when you give a departing employee time to finalize any necessary knowledge transfer. Remain respectful in how you speak about the person who is exiting. Thank them kindly for their service and wish them well in the future. If you speak poorly of them behind their back or later it only makes you look bitter.</p> <p>Change is inevitable. It’s your job as leader to prepare your organization to handle it.</p> <img src="" height="1" width="1" alt=""/> Transgender Day of Rememberance 2020-11-20T00:00:00-05:00 <p>Today is the Transgender Day of Remembrance (<a href="">TDoR</a>). On 11/20 every year we honor the memory of the transgender people whose lives were lost in acts of anti-transgender violence.</p> <p>In the past year there have been over 430 trans and gender non-conforming people who have lost their lives due to hate. 430 people whose only crime was to be their true and authentic self every day.</p> <p>My friend <a href="">Kelsey Campbell</a> over at <a href="">Gayta Science</a> put together this powerful visualization of the violence my community faces constantly. Please take a look when you can:</p> <p><a href=""><img src="/img/tdor.jpg" alt="TDoR Dataviz" /></a></p> <img src="" height="1" width="1" alt=""/> In Divided Times, We Must Come Together 2018-11-01T00:00:00-04:00 <p>In the wake of the deadly shooting <a href="">at the Tree of Life synagogue in Pittsburgh</a> on Saturday, October 27th, <a href="">communities</a> from across the region <a href="">came</a> <a href="">together</a> to <a href="">support</a> the Jewish community who had been so tragically attacked.</p> <p>Pittsburgh Mayor Bill Peduto <a href="">spoke to this</a> and said “To the victims’ families, to the victims’ friends, we are here for you as a community of one”. This powerful message is something we all need to remember right now.</p> <p>In a world of division, of hatred, of us vs them, a community of one is a radical thing. And yet, our nation’s strength has always stemmed from a coming together of diverse perspectives and different world views. When We Are One community, we create a stronger nation.</p> <p><strong>#WeAreOne</strong> is about building us all up. It’s about our equal right to live free of intolerance and hatred.</p> <p><strong>#WeAreOne</strong> is about knowing that we are all human. It’s about knowing that we all deserve a chance.</p> <p><strong>#WeAreOne</strong> is about celebrating each other’s diverse communities. It’s about fulfilling the American promise of freedom and equality.</p> <p>As we approach the election on November 6th, this tragedy can serve as a reminder of how important it is to get out and vote — to elect people who know that <strong>#WeAreOne</strong>. This is a new chance to choose inclusion over intolerance and hate.</p> <p><strong>#WeAreOne</strong> means that we can find moments in all our days to build better communities together. It’s sharing small smiles with people you meet on the street. It’s about knowing that sometimes everyone has a tough day and needs a break. It’s about the respect we offer to each other that celebrates our diversity.</p> <p>And remember that truly, <strong>#WeAreOne</strong>. We all need love and support. Celebrate the dignity in everyone you meet. Listen to someone’s story. Be there when others need you. And we will be one, stronger nation, together.</p> <p>When <strong>#WeAreOne</strong>, no ignorance, no hatred, and no violence can possibly stop us.</p> <img src="" height="1" width="1" alt=""/> Story Of Us 2017-10-16T00:00:00-04:00 <h3 id="collective-fiction">Collective Fiction</h3> <p>Interesting thing here. Here’s an excerpt from a <a href="">blog post</a> I’m reading (unrelated to this idea):</p> <blockquote> <p.</p> </blockquote> <p>We’ve passed 150 people at my company, but I don’t think we’ve invested enough in our Collective Fiction that explains <em>us</em> and what we’re doing. This is why I’ve been so obsessed with communicating context lately.</p> <p>We need to spend more time telling the story of Us so that we all understand who we are and how we get things done.</p> <p>A shared sense of Us enables us to make decisions in an aligned way and work together cohesively.</p> <p>This also explains why startups usually feel so different from big companies—the big companies have a much harder time telling a compelling story that staff wants to buy into. The good ones do a better job at this.</p> <p>So: who are we? Our values are one way to describe it, but also our shared history, and our shared perspective on the future—our vision. This is why describing a vision more clearly than just the long term helps—it puts our actions in context and if aligned to Who We Are, it Makes Sense.</p> <p>In my previous entry I wrote about how to set a vision. But I didn’t really write about why it’s so important. Vision enables us to tell our story.</p> <h3 id="shared-history">Shared History</h3> <p>A shared history is important too. Most people are good at telling their history—they love to tell stories about themselves and their past, especially if it has been successful. But telling a history <em>intentionally</em> is something else, and can take some planning.</p> <p>An Intentional History brings out why your values are what they are. It shows us how we’ve made decisions in the past and enables future decisions in line with how we want to get things done.</p> <ul> <li>“Of course to solve this problem Amy and Bob collaborated” - clearly we value collaboration to solve hard problems</li> <li>“Charlotte sacrificed sleep for 3 days to get the product to market” - we value sleepless nights and hero culture</li> <li>“Doug cleverly put in a clause that helped us win the next deal” - we value deception</li> </ul> <p>These stories can be powerful, so be intentional with how you tell them.</p> <h3 id="story-of-now">Story Of Now</h3> <p>It takes daily practice to tie our history and our vision to our current action. Why are we working on X project? What is it in service of? What’s next? How much time do we spend on this thing? Do we build it to last or build it for the moment? You can answer these questions if you understand the Story of Now.</p> <p>Think about the stories you tell, they’re how you grow an organization.</p> <img src="" height="1" width="1" alt=""/> Setting a Vision 2017-10-05T00:00:00-04:00 <p>We have a series of internal classes at Optoro called <em>Managing at Optoro</em>. It’s a great way for us to be able to promote talent into a leadership role and make sure they have the tools they need to be successful.</p> <p>The class I teach is called “Setting a Vision” and it’s something I think about a lot.</p> <p>I’m teaching the class later today. I generally hold an interactive discussion session, but I thought I might share some of my notes.</p> <h3 id="vision--context--framing">Vision = context = framing</h3> <p>Why is a vision important? I think vision is the essence of leadership. It <em>is</em> fundamentally leadership, and one of the most important things a leader can do. Vision provides direction, and without it teams wander from place to place, effectively going nowhere.</p> <p>Imagine you get on the road and start driving. You take whatever roads look interesting, and find fun along the way. But you’re not <em>going</em> somewhere.</p> <p>Vision provides context to the team on why this, why now, why not anything else. Context helps the team be successful, solve problems better, put themselves in the big picture. Vision frames decisions made and decisions to make. We’re able to move towards our vision because we have one.</p> <h3 id="connectedness-big-picture-understanding">Connectedness, big picture, understanding</h3> <p>When you have multiple teams working together to achieve something, a clear vision gives them a shared identity and shared purpose. Teams understand their part in the organization. They can connect their actions to the whole.</p> <p>We work better and produce better things when we understand how our piece fits. We can all help each other better when we can see where we’re going.</p> <h3 id="setting-vision">Setting vision</h3> <p>Think about where you want to be. Imagine your team, your company, yourself in 2, 3, 5, and 10 years. You don’t have to do all of them, but the more you can do the more complete and connected a vision you’ll have. What are you doing then? What have you accomplished? What tools are you using, or products have you built, or challenges have you overcome? Don’t worry about how - just where you want to be. Now that you have an idea, is it crazy? Good! Crazy goals can be motivating. But is it impossible? Maybe dial it back a little.</p> <p>Write it down. It doesn’t have to be complicated, but paint the picture of the future as best you can. It can be in words, pictures, whatever - just get it in a format you can share with others.</p> <p>Then share your vision with your team. Start with someone you trust to be honest and helpful. Listen, change your vision. Refine it. Then share it with everyone.</p> <h3 id="good-vision-is-not-100-definite-accepting-of-change">Good vision is not 100% definite, accepting of change</h3> <p>It’s hubris to assume a leader can see the future perfectly. Therefore we must accept that our visions are imperfect, incomplete, and subject to change. That doesn’t give us an excuse not to set one, but rather we should remain humble and accept that new information can change our course. We should always look for opportunities to learn more and revise our vision, and we should share that truth with our teams so they understand that we are human too and realistic and pragmatic.</p> <h3 id="sharing-vision-do-it-all-the-time">Sharing vision: do it all the time.</h3> <p>Repeat yourself over and over. Always connect what we’re doing now to where we’re going. Take every opportunity to bring your vision back to the table and use it to reframe what we’re doing to support it. Repeating feels silly but most people don’t really hear you until they’ve heard it many, many times. Take the opportunity!</p> <p>We all go through hard times, slogs, crunch time, etc. Understanding that this is part of a bigger thing helps people work through it. Remind them all the time.</p> <p>My teams sometimes during standup will play a little game. Instead of just sharing what’s up today (and blockers, etc), team members will share what they’re doing and then take a moment to connect the dots between their work and our company’s goals. A simple for example: “I’m building this feature so that we can take it to market and make money.” It doesn’t take much, but it can help connect the dots.</p> <h3 id="include-your-team">Include your team</h3> <p>Finally, remember to include your team in your process to set and adjust your vision as it changes. Demonstrate that you are also capable of change. Listen to your team and your team will listen to you.</p> <img src="" height="1" width="1" alt=""/> On Change 2017-08-31T00:00:00-04:00 <p><img src="/img/washington-dc.jpg" alt="Washington DC" /></p> <p>I’ve always wondered how people can expect so much permanence in their lives. In Washington DC, where I was born and raised (and live now), change is a way of life. People come and go. Buildings change, are torn down, are lost to time. It’s normal.</p> <p>When I lived in western Massachusetts I lived in a small town that had stayed largely the same most of its long history. There was a historical society with a small museum dedicated to the town. Mostly it celebrated the town’s heritage as a center of industrial progress in the 1800s, or its rebirth into an art mecca. But almost as important were the scars left on the town’s psyche by the change that had happened. The most telling was the museum’s focus on a large project in the ‘70s that tore down half of downtown in the name of progress. They removed old victorian-era storefronts and put up brutalist structures with efficient space and modern amenities. The town I lived in in the early 2000s bemoaned its lost history. The change was seen as a horrible mistake, a part of the town’s soul was lost to time.</p> <p>I never quite understood why that change was so important to that mountain town. In DC that kind of change happens constantly. I always wondered why, if it was so bad, didn’t they just tear that stuff down and build whatever it is they wanted instead.</p> <p>DC is a city of transients. Most people who call the District home don’t realize the change that constantly courses through it. They come for a few years for work, work harder than they ever have in their life, and then move on to other things. DC is a city of nerds, geeks, and workaholics. DC is a city of hidden depth. People see the monuments and federal buildings, and don’t realize that they’re just a small part. DC is always changing.</p> <p>So for me my life is constantly changing. Change is the only constant. Change is life, and to not change is to die. The idea of something permanent has its appeal, but give me too much stasis and I grow uncomfortable, change my music, my wallpaper, my watch face, my clothes. Change is oxygen.</p> <p>The DCTech event I was at today was very different from those of the past - smaller, less excited, quiet. And that’s why I felt the need to write this - it’s changed. And I’m uncomfortable with that. I want permanence. I want what it was. Sometimes it’s nice to have some consistency. And that’s weird for me.</p> <p>Maybe sometimes change has to change too.</p> <img src="" height="1" width="1" alt=""/> What Transition Is Like For Me 2017-08-17T00:00:00-04:00 <p>I get asked this now and then, “why did you transition?” Or “what’s it like?” Or even just “how does it feel?”</p> <p>For what it’s worth, some trans women <em>really</em> don’t like this question, so unless you’re invited to ask it, it’s probably safer not to. But I don’t mind sharing my story, and maybe it’ll help shine a light for some folks.</p> <p><a href="">Jenny Boylan</a> says “if you’ve met one trans person you’ve met one trans person,” basically we’re all unique people with unique journies. So don’t abstract this to everyone, it’s just my story ;)</p> <h3 id="storytime">Storytime</h3> <p>Imagine you wake up one day hearing this awful noise. It just won’t stop, no matter what you do. It’s pretty awful. (For the musicians out there I like to think of it as a <a href="">tritone</a>).</p> <p>You keep going about your life—it’s an awful noise but it’s just in your head, right? You need to just “grow a pair” and deal with it. Toughen up and all that. So you live your life with this.. whatever awful thing in the back of your head.</p> <p>Eventually you learn to tune it out.. it kind of fades into the background of life, but it’s not <em>gone</em>, it’s still there, you’re just getting good at ignoring it.</p> <p>You go along that way for a long time. Sometimes you feel these weird compulsions to do things, but nothing like, <em>freak show</em> weird, so whatever, everyone has their thing I guess.</p> <p>But that noise is still there. It’s still nagging at you, annoying you.</p> <p>Something happens at some point and the noise gets louder, harder to ignore. You redouble your efforts tuning it out but for some reason it’s harder now. It won’t go away. You need to do something about it.</p> <p>You do <em>a lot</em> of research, and find out that there are other people who hear that noise and that lots of them have gotten the noise to stop by doing this thing that just seems so unimagnable that it feels unreachable. It sounds terrifying and crazy and awful but <em>goddamn that noise</em> it’s <em>horrible</em> just <em>make it stop</em>.</p> <p>You’re faced with a decision: Do the unthinkable? Or go crazy, become bitter, and hate life.</p> <p>That was me.</p> <h3 id="quiet">Quiet</h3> <p>I felt.. <em>something</em> as far back as maybe when I was 8 or 10. This feeling of.. wrongness. I tuned it out for a long time.</p> <p>But when my wife became pregnant with our son, I was <em>so jealous</em> (I wanted to carry him!). The wrongness exploded in me.</p> <p>I chose to do the unthinkable, and in transition I have found <em>peace</em>.</p> <p>The wrongness is gone. The awful noise is no more. I feel free!</p> <p>Of course, it feels great :)</p> <h3 id="epilogue">Epilogue</h3> <p>I’m still dealing with it all, and it’s still really scary. Exploring the unknown and unfamiliar is scary. Some segments of society make everything harder. But I’m at peace inside my head, and that’s <em>such</em> a powerful thing.</p> <p>I’m happy to answer questions, leave a comment!</p> <img src="" height="1" width="1" alt=""/> Hello World! 2017-07-28T00:00:00-04:00 <p>Hello world, my name is Jess! I’m transgender :)</p> <iframe width="560" height="315" src="" frameborder="0" allowfullscreen=""></iframe> <p>It’s taken me awhile to admit it to myself, but I did last fall (2016). Coming to this realization made a lot of my life make sense, and transitioning has given me a sense of peace and joy like I’ve never experienced before.</p> <p>I am very fortunate to have a loving family, supporting work environment, and true friends. Many people who experience this change go through it with much more pain and sadness than I am. With that in mind, I have the opportunity to share my story more easily with people than many have before me. If you have questions, please ask! I’ll let you know if there’s a line I’d rather not cross. I’ve addressed some common questions below to get you started :)</p> <p>Thanks in advance for your support!</p> <p>Sincerely, -Jess (Jessica) Szmajda</p> <p>Q: How do you plan to medically transition?<br /> A: Transition is very much about identity and presentation, and medical options are something that can support that transition. I’ve chosen to undergo hormone replacement, and I’ve been on hormones now for about 5 months.</p> <p>Q: Should I use different pronouns, or a different name?<br /> A: Please do use she/her pronouns, and hi, my name is Jess! It’s short for Jessica, but I prefer Jess :) For what it’s worth, I do expect this to take some time for folks to get used to! It’s ok if you make a mistake, a simple correction means a lot to me. If you notice someone else making a mistake, it would be nice to help them remember there’s been a change too.</p> <p>Q: How can we best support you?<br /> A: Honestly the most supportive thing you can do right now is for us to just keep going like everything is normal. Please use Jess and she/her pronouns. If you’re interested in being a trans ally, I can point you in the direction of some books and articles too. And thank you!</p> <p>Q: Do you recommend any books?<br /> A: This <a href="">Transgender FAQ</a> is a great place to start. I also recommend a couple books - <a href="">Transgender 101</a> by Nicholas Teich, and <a href="">She’s Not There</a> by Jenny Boylan. I’m always looking for more resources, feel free to send any over you’ve found valuable too!</p> <p>Q: How should I get in touch if I have more questions?<br /> A: Please feel free to leave a comment below, or reach out to me on twitter (link in the sidebar)</p> <img src="" height="1" width="1" alt=""/> Experiment Results 2016-11-30T00:00:00-05:00 <p>This is a continuation of my blog post series on trying to use a Surface Book as my primary computer. The first entry was <a href="/essays/2016/11/23/surface-book.html">Surface Book</a> and the entry previous to this one was <a href="/essays/2016/11/29/a-surface-roadblock.html">A Surface Roadblock</a>.</p> <h3 id="i-give-up">I give up.</h3> <p>I got so frustrated today trying to just deal with basic window management that I said “well maybe I’ll just try the mac again for a few minutes…”. I’m not going back. Nope. Can’t make me do it.</p> <p>This mac <em>just works</em>! Ugh! It does everything I need it to do and it gets out of the way and lets me work. I’m too busy to spend time shaving all the stupid yaks I’d have to shave to use that damn surface. And they’re not <em>good</em> yaks, like dealing with <a href="">i3</a> or something, but annoying ones, like training my brain to expect bad behavior from the window manager.</p> <p>I’m even really liking the damn fuzzy mac text renderer. It’s soft and inviting, it feels good on my eyes. It’s cozy. And it’s <em>really</em> legible.</p> <p>Sure, typing my password is mildly annoying when waking up my computer, but if I get the new MBP I’ll get a fingerprint sensor so yay?</p> <p>So ultimately I realized I really still want to be running linux and not locking myself up with these damn companies but if I’m going to chain myself to a desktop vendor it won’t be Microsoft for a long time still.</p> <p>My 16 years of not using Windows as my primary desktop OS has only been broken for about a week.</p> <p>Oh god and vim just works again. Welcome back, beloved <code class="highlighter-rouge">"*</code>! Hello again, iTerm! Homebrew, you crappy bastard, I even missed you.</p> <h3 id="its-not-all-horrible">It’s not all horrible</h3> <p>If you’re not a developer you’d probably love the machine. If you’re not used to using the keyboard for <em>everything</em> you’d probably be fine with Windows. If you’re just not picky about good window management maybe Win10’s window manager is good enough for you. The machine is bright and crisp, and the pen interface is pretty interesting. If I were a fine artist or graphic designer I’d probably love carrying what’s effectively a <a href="">Cintiq</a> with me everywhere. The battery life ultimately was pretty good. The 9-series nVidia graphics card was potent. The tablet functionality was effective and interesting.</p> <p>It’s just not for me :)</p> <img src="" height="1" width="1" alt=""/> A Surface Roadblock 2016-11-29T00:00:00-05:00 <p>This is a continuation of my previous posts, the last one being <a href="/essays/2016/11/28/more-surface-book.html">More Surface Book</a></p> <h3 id="damnit-docker">Damnit Docker.</h3> <p>There is Docker for Windows, but there’s no <code class="highlighter-rouge">docker</code> CLI in the WSL environment. This might be a problem because we’re shifting more and more to using docker to deploy all our services. As the CTO I am occasionally required to actually like, edit services and run them on my machine. So this might be a big blocker. Certainly I can install an Ubuntu VM, but a big part of the point of all this is to avoid having to use a VM. I’m going to think about this one a bit, and even try the VM (with HyperV too, why not), but this might be the biggest reason to stick with Apple for now.</p> <p>Wow ok. Docker for Windows works by using Hyper-V. Hyper-V is Microsoft’s virtualization technology. When it’s installed it locks out all other virtualization technology, so like you can’t run VirtualBox and Hyper-V simultaneously and expect VB to get any kind of hardware virtualization acceleration. So if I want to run a Ubuntu VM for dev work in the background and still try to get Docker in Windows running then I have to have it in Hyper-V.</p> <p>That’s probably not a terrible thing except that HyperV doesn’t seem to have some of the nice things I take for granted with VirtualBox, at least not without more digging. Like a NAT’d IP for my VM so that I can always assume it’s at some internal IP.</p> <p>If I do run the VM I’ll either have to use the (pretty crappy) virtual desktop to get around the VIM ConEmu limitations or I’ll have to deal with ConEmu regardless. Starting to seem less and less worth it.</p> <img src="" height="1" width="1" alt=""/> More Surface Book 2016-11-28T00:00:00-05:00 <p>This is my first “normal” work day using the Surface Book. For first impressions go back and check out my first post, <a href="/essays/2016/11/23/surface-book.html">Surface Book</a> It’s the little things now, and a few big things</p> <h3 id="vim">VIM</h3> <p>So ConEmu doesn’t show my visual highlights properly. Maybe that’s a yak I can shave but it’s an annoying one.</p> <h3 id="general-windows-ui">General Windows UI</h3> <p>Windows is really confused by having a monitor (my external monitor) that I want to run at 100% DPI scaling and the tablet screen at 175%. Some apps start really huge and others really tiny.</p> <p>The snap / autotiling stuff that Win10 does is pretty good the first time, but then when I unplug my laptop things lose all sense of where they were and I have to set it all back up again. It’s a nice feature but still pretty immature.</p> <p>Seriously why can’t I drag a window between desktops in expose mode? (Win-Tab)</p> <p>Presenting from google slides on a second monitor in screen-mirroring mode (totally the default for most people) gives me this weird black border on the other monitor. The other monitor has the proper aspect ratio for the slides so it should be 100% full. It works fine when I’m extending my desktop onto the other screen.. WTF?</p> <p>Apparently if I’ve gotten the window arrangement wrong while docked when I undock sometimes windows can get into strange places where I can’t find them. I have to detatch my tablet, rotate everything around so that it gets repositioned, then reattach!</p> <p>Notifications on Win10 are fine. Windows gives them a little more functionality by default but not enough to be game-changing.</p> <p>Maybe I’m just used to it but I really prefer being able to switch desktops indivudually by monitor on the Mac vs switching entire worlds on Windows.</p> <p>Everything really does drive you to maximise your windows. I had forgotten how much that was the norm in Windowsland too. I had thought it was just some accident of design but it’s really baked into the UI expectations.</p> <h3 id="hardware">Hardware</h3> <p>External mice work tons better, I really much prefer the tracking velocity and speed on Windows. On the Mac I had given up trying to use an external mouse and went full trackpad. I didn’t mind because the trackpad was more capable, but wow this mouse is being handled well here.</p> <p>Having a touchscreen is nice after all. I do occassionally touch it to scroll things while I’m in a meeting. At my desk it’s not at hand and my external monitor insn’t a touchscreen so it doesn’t help there. Very small nice to have I guess.</p> <p>I did spend a session “whiteboarding” on the sketchpad app that comes in the Windows Ink Workspace. It worked well but I could’ve just as easily used an actual whiteboard.</p> <p>It is pretty annoying to have to press three keys to close a window from the keyboard - F4 is hidden behind a Fn key toggle.. (for Alt-F4)</p> <h3 id="battery">Battery</h3> <p>Battery life - I worked for 5 hours on battery and my remaining battery was at 32%. Not great to say the least. Most of that time was in excel and google sheets and presenting a google slides deck. That <em>really</em> shouldn’t drain the battery that much. Another potential dealkiller right there.</p> <p>To be fair I haven’t yet ‘trained’ the battery monitor by running it all the way down so let me do that before you take this battery “test” as gospel.</p> <p>More at my next post, <a href="/essays/2016/11/29/a-surface-roadblock.html">A Surface Roadblock</a></p> <img src="" height="1" width="1" alt=""/> Surface Book 2016-11-23T00:00:00-05:00 <p>I’m trying out the new Surface Book with the performance base as my main computer. It’s been.. interesting! Here are some ramblings about my experience:</p> <h2 id="initial-thoughts">Initial thoughts</h2> <p>I installed a bunch of stuff. Primarily <a href="">Windows Subsystem for Linux</a>, but also normal stuff (Chrome, etc), and the nicest terminal emulator I could find, <a href="">ConEmu</a></p> <p>It’s definitely different! It took me a good 4-5 hours to just remap all the text movement keys in my head. I had gotten pretty used to using the mac key and ctrl-e ctrl-a etc.</p> <p>Apple has a tightly locked-down OS but they have spent time making some things really really nice. Like plugging into an external monitor - the machine remembers what my display configuration was for that setup and returns there, so I can go big text on my mac when I’m plugged in. Windows doesn’t do that but it’s manageable.</p> <p>Windows text rendering is <em>much</em> crisper. I remember now moving to the mac and thinking everything was fuzzytown. Really nice to feel crisp!</p> <p>Missing the cmd-{ and cmd-} keyboard shortcuts from apple. Ctrl-tab is ok but more awkward for my fingers. It helps to have remapped caps-lock to ctrl though (weird that that’s a regedit thing).</p> <h2 id="black-friday">Black Friday</h2> <p>I didn’t use it much yesterday, with turkey and all.</p> <p>I’m starting to get used to it now, it’s feeling more comfortable. Still mildly annoying in how the keyboard feels (mostly just different). I’ve been tweaking some of the customization stuff a bit more. I think I have the resolution (really font scaling - odd but effective) stuff where I like it now. It defaults to 200% and I’m using 175%. Things are a <em>little</em> small but manageable.</p> <p>The trackpad is.. well it’s good for a windows computer but that’s not saying much at all. Apple really dominates trackpad hardware. If the 3 year old MBP I was using’s trackpad is 100%, the newly released larger one is like 110% and this surface’s trackpad is like 40-50%. Most laptops would clock in at around 10%. Really no comparison.</p> <p>The keyboard is a little mushy but again pretty good for a windows machine. I’m picky about keyboards and I think I can live with it.</p> <p>The screen is very nice, huge and high resolution, bright and crisp, great color reproduction.</p> <p>The machine is pretty snappy, but that’s just based on UI feedback so far. Haven’t tried to like, compile something or whatever yet.</p> <p>Battery life has been fine (haven’t really paid attention, but I’ve been mostly unplugged all day and it’s at like half)</p> <p>The trackpad has the option to right click by clicking on the bottom-right of the trackpad (like where a button would be on a lot of other trackpads). You can enable/disable it in the settings. I initially disabled it because I was used to the mac not forcing me to pick, but I’ve reenabled it because there’s no option-click alternative on windows. I’ll see how maddening it is, mostly it’s just a little weird.</p> <p>Speaking of the touchpad and gestures - I <em>really</em> miss the three-finger-drag gesture the mac has. The Surface supports most of the gestures I used to use on the mac (desktop swiping, window revealing (expose), app switching), but that three finger drag.. just so useful. Best I can do with windows is double-tap and drag, which is pretty meh by comparison. Also the gesture recognition is <em>slow</em>! The mac got it right away where this thing has a tiny but noticeable lag. So frustrate.</p> <p>One of my big still-unproven hypotheses is that I’ll be happier with this machine because I can tweak it more. Win10 is more tweakable to a point I think but I’m not yet sure where the limits are of my needs and its ability to support them. TBD!</p> <p>Relearning all these text motion shortcuts is a bear.. ctrl-shift vs shift-home, etc. I had gotten used to cmd-gestures with the mac.</p> <p>The whole detachable tablet thing is kinda nice. I’ve been detaching it and reattaching it in a variety of configurations during a variety of use-cases and it has been nice. More of a small sweetener IMO though still. I doubt I’ll want to use it as a clipboard for taking notes, for example, and I already rarely use a tablet at home for reading, so having the keyboard attached doesn’t really bother me. The on-screen input systems win10 has are.. well.. alright I guess. I much prefer Android systems for all that. Win10 has a handwriting recognition input mode.. it’s honestly pretty mediocre. I used handwriting recognition on my Compaq iPaq back in like 2000 and it was almost as good as this.</p> <p>Oh and I do much prefer Windows’s font rendering to OSX’s. <em>Much</em> crisper, makes me happy :)</p> <p>FWIW I’m writing this using neovim in the Windows Subsystem for Linux environment. It all works fine and I have a decently nice terminal app (ConEmu).</p> <p>HUH well I did just find that neovim doesn’t handle arrow-key input quite correctly so it’s back to standard vim for me for now.</p> <h3 id="ruby">Ruby</h3> <p>I tried rbenv because the macheads like it and I was starting to switch to it on my mac. Turns out it wouldn’t install 2.3.3. It doesn’t do that really nice <code class="highlighter-rouge">rvm requirements</code> thing that rvm does. So back to rvm. RVM is also so much more verbose and I like that. Don’t just sit there silently while you do god knows what, please.</p> <p>Yep ok RVM installed 2.3.3 just fine so goodbye rbenv</p> <p>Vim - the magic buffer <code class="highlighter-rouge">"*</code> isn’t supported. That buffer gives you access to the system clipboard. Sad. I use it a lot to copy/paste things in and out from vim. That alone <em>might</em> be a dealbreaker.</p> <h3 id="more-non-ruby">More non-ruby</h3> <p>This face unlock thing is pretty sweet actually. I hate typing my password all the time. I wonder how secure it actually is.</p> <p>Interesting, plugging in a mouse - the mouse scrollwheel goes in “classic” (not natural) mode, whereas the trackpad is in natural mode by default. /shrug</p> <p>Man it does feel good to use apt-get again.. Homebrew is nice and all but apt-get is life.</p> <h2 id="more">More</h2> <p>More at my next post, <a href="/essays/2016/11/28/more-surface-book.html">More Surface Book</a></p> <img src="" height="1" width="1" alt=""/> What Podcasts I'm Listening To Right Now 2016-03-02T00:00:00-05:00 <h3 id="podcasts">Podcasts</h3> <p>My commute is pretty long (about an hour and fifteen minutes each way), so I have the opportunity to listen to a lot of podcasts or audiobooks on the trip. I talk about them with folks pretty often, and some have asked me for a list of what I’m listening to, so here it is.</p> <p>Before the list, briefly how I consume podcasts: I have an Android phone and I use an app called <a href="">BeyondPod</a>. I have a smart playlist that pulls episodes from the various feeds I have in a specific order. I’ll go through that order in the list. I also by default listen to all shows at 1.3x normal playback speed. For some shows I configure a custom playback speed (1x for music shows, or 2x for some of the longer, more talking-head-style shows). I’ve found that this helps me consume more content and stay more interested, your mileage may vary :)</p> <p>OK, the list!</p> <h3 id="the-list">The List</h3> <ol> <li><a href="">NPR: Hourly News Summary</a> <ul> <li>I have BeyondPod set up to grab one of these a day. It’s 5 minutes long and a great start to the day.</li> </ul> </li> <li><a href="">WAMU Local news</a> (latest all) <ul> <li>With Podcasts it’s really easy to get disconnected from local news. I’m lucky WAMU syndicates their local news in this way.</li> </ul> </li> <li><a href="">The Economist: All Audio</a> (latest 2 episodes) <ul> <li>This can be hit an miss but it’s a good alternate perspective on news and events. I probably skip about half the content they publish but there are some real winners in here sometimes.</li> </ul> </li> <li><a href="">NPR Politics</a> <ul> <li>This is a talking-heads shows of all the NPR Politics correspondents talking about politics. These days it’s all election stuff, and honestly I eat it up. It runs a little left but they’re pretty fair in their GOP commentary. In my personal world bubble this is pretty even-keel stuff.</li> </ul> </li> <li><a href="">APM: Performance Today - Piano Puzzler</a> <ul> <li>This one is fun, every week this composer, Bruce Adolphe, rewrites a well-known tune in the style of a classical composer. Listeners call in and try to guess the tune and the composer whose style it’s written in. Fun way to learn more about classical music!</li> </ul> </li> <li><a href="">The Protagonist</a> <ul> <li>Pranav Vora, the founder of <a href="">Hugh & Crye</a> has been interviewing DC-area (and beyond) founders about how they started their company and their challenges. Each episode has been really well done. They’re few and far between but high quality, definitely check out their back catalog if you’re interested. It doesn’t hurt there’s an [Optoro][opotoro] <a href="">interview</a> too ;)</li> </ul> </li> <li><a href="">Intelligence Squared U.S.</a> <ul> <li>Oxford-style debates on American shores. A really great way to explore issues in depth and hear both sides well presented. Also interesting to see how well their rhetoric and debate tactics can sway an audience.</li> </ul> </li> <li><a href="">Question of the Day</a> <ul> <li>Stephen Dubner (of Freakonomics, etc) and James Altucher (investor, writer) have great chemistry and talk about stuff mostly they find on Quora. Short (under 20 minutes usually) and fun, with great banter.</li> </ul> </li> <li><a href="">Freakonomics Radio</a> <ul> <li>Speaking of Stephen Dubner, here’s his flagship media outlet. Freakonomics Radio expands on the books and looks at the world through an Economist’s perspective. Topics are broad and the research is very deep. Very highly recommended!</li> </ul> </li> <li><a href="">Song Exploder</a> <ul> <li>Hrishikesh Hirway interviews artists on how they created some of their songs. They cut down to the stems and talk about the music process in depth, including what instruments were chosen, how production went in the studio, and inspiration for lyrics and melodies, etc.</li> </ul> </li> <li><a href="">Planet Money</a> <ul> <li>NPR’s original Economics podcast keeps on going. They continue to create novel content around the world of business, finance, and economics. Great stuff, and on the short side (<20 min usually)</li> </ul> </li> <li><a href="">TED Radio Hour</a> <ul> <li>This show stitches together TED talks on a single topic each time. Good insights.</li> </ul> </li> <li><a href="">Ruby Rogues</a> <ul> <li>The biggest podcast in the Ruby community. Definitely talking-head style (I listen on 2x playback speed or faster), but good. Keeps me abreast of what’s happening in the Ruby world.</li> </ul> </li> <li>Everything else: <ul> <li>Stuff down here I don’t always get to listen to but when I do I very much enjoy it!</li> </ul> <ol> <li><a href="">99% Invisible</a> <ul> <li>The design of everything. Really can’t say enough good about 99% Invisible, they get into depth on some really interesting stuff, like <a href="">the history of the credit card</a>, or how <a href="">this building in new york’s design was flawed and some architecture student caught the problem</a>.</li> </ul> </li> <li><a href="">The Longest Shortest Time</a> <ul> <li>A show for parents about parenting. Helps me understand how to be a better Dad :)</li> </ul> </li> <li><a href="">Harmonia Early Music</a> <ul> <li>Nice (usually short) survey of new releases in early music (not actually an oxymoron!).</li> </ul> </li> <li><a href="">Ask Me Another</a> <ul> <li>Fun podcast to listen to on the weekends, it’s a quiz show with Jonathan Coulton.</li> </ul> </li> <li><a href="">The Dinner Party Download</a> <ul> <li>Another fun show to get me in the mood for the weekend, it’s NPR’s arts and leisure section.</li> </ul> </li> <li><a href="">This American Life</a> <ul> <li>A classic. Always deeply touching. If you haven’t ever listened you’re missing out.</li> </ul> </li> <li><a href="">Snap Judgment</a> <ul> <li>In the lines of This American Life but a little more off the beaten path.</li> </ul> </li> <li><a href="">Radiolab</a> <ul> <li>Another in the line of This American Life, but with very interesting audio design and quirkier hosts.</li> </ul> </li> </ol> </li> </ol> <p>What podcasts do you listen to? Let me know in the comments!</p> <img src="" height="1" width="1" alt=""/> Ergodox 2015-12-22T00:00:00-05:00 <p>I went on a quest awhile back to find the perfect keyboard for me. I used a <a href="">Microsoft Natural keyboard</a> for a long time and got used to the split layout, but eventually the keyswitches started to annoy me. I tried <a href="">Microsoft’s Sculpt Natural keyboard</a>, and it was nice but then I heard about mechanical keyboards. I tried the <a href="">Truly Ergonomic Keyboard</a> for a bit, but it wasn’t quite right, then I heard about the <a href="">Ergodox</a>. I’ve been using it for over a year now and it’s been perfect for me. I built it with Cherry Brown switches and got a nice set of shaped keycaps. Funnily enough the shaped keycaps made a big improvement in my typing speed (~5-10 wpm).</p> <p>One of the wonderful things about the Ergodox is that you can customize it to suit your needs. I was telling a friend about my layout and figured it would be a good idea to copy/paste it here for posterity and others to use. Good luck!</p> <p><a href="">Here’s the layout I use in Massdrop’s Configurator</a></p> <p>I’ve tweaked things for a long time to get to this point, it works pretty well for me on OSX.</p> <p>Layer 2 is mostly for gaming, I set it up when I was playing too much Skyrim…</p> <p>The duplicated ESC keys on the left hand are because sometimes one is more natural for me than the other when I’m vimming</p> <p>The duplicated ~ keys are just because I never actually use the key below z, or really the key below x.</p> <p>Duplicating the ctrl and alt keys on the left hand allow me to chord certain key combinations more easily (mostly when I’m using Atlassian products.. for some reason their keyboard shortcuts are dumb)</p> <p>F8 on the right hand is mapped in OSX to play/pause.. I couldn’t get the “real” play/pause keyboard input to work properly.</p> <p>The only other weirdness I think is that I always leave myself a teensy key somewhere on the layout so I don’t have to go fishing for something small to press the button on the teensy board to rewrite the nvram.</p> <p>And layer 3 is layer 0 just modified slightly to work better for windows</p> <p>Here’s what it all looks like on my desk:</p> <p><img src="/img/ergodox-on-desk.jpg" alt="Ergodox on my desk" /></p> <p>You can see that I use an apple trackpad and an extra numpad. The numpad I use in very specific situations when I’m doing a lot of number work (mostly budgets for work, etc). The trackpad is awesome, but when I’m gaming I’ll use a regular mouse instead. For work the trackpad is best for me though.</p> <p>Finallly here’s the layout from Massdrop in case the configurator link breaks at some point:</p> <p><img src="/img/ergodox-layout-small.png" alt="Modified QWERTY v2" /></p> <img src="" height="1" width="1" alt=""/> StrangeLoop 2014-09-20T00:00:00-04:00 <p>I went to <a href="">StrangeLoop</a>. It was awesome! Basically a polyglot conference that pulled together academia and industry. Very focused on Functional Programming (FP), but had other ideas too. I took notes, pasted in somewhat raw fashion below. I highly recommend going next year!</p> <h2 id="2014-09-17">2014-09-17</h2> <h3 id="future-of-programming-workshop-x-emerging-languages-camp">Future of Programming Workshop x Emerging Languages Camp</h3> <p>I attended a bonus day camp on the Future of Programming. I was expecting stuff like I’ve <a href="">seen out of Brett Victor</a>, and while I didn’t get quite that, I did see some really interesting stuff. All videos should be published by 12/1 this year.</p> <h3 id="jonathan-edwards--subtext">Jonathan Edwards / Subtext</h3> <ul> <li>“Leader of the Programmer Liberation Front”</li> <li><a href=""></a></li> <li>Experimental language trying to make it easier to build websites</li> <li>inspired by excel / lighttable</li> <li>wysiwyg with explosion of computation</li> <li>All arrays implemented as CRDTs</li> <li><a href="">Lenses</a> all the way down</li> <li>Transaction based</li> <li>Causality is monotonic in the tree</li> <li>Guaranteed change-commit cycle has nice properties, especially in parallel and distributed computation</li> <li>assertions are final phase of commit, operations are strictly ordered</li> <li>“Two-way Dataflow”</li> </ul> <h3 id="mark--storyteller">Mark / Storyteller</h3> <ul> <li>Visual VCS with Story Board</li> <li>His primary complaint is that he doesn’t see how the programmer thought about the problem and solved it.</li> <li>I really think you can get all the benefit of this with smaller, more verbose commit messages on a standard VCS, which is general best-practices anyway</li> <li><a href=""></a></li> </ul> <h3 id="toby-schachman--shadershop">Toby Schachman / Shadershop</h3> <ul> <li>@NYC MIT Media Lab analogue</li> <li>How do we communicate to a computer over a spacial channel?</li> <li>Shadershop = shaders in ‘photoshop’</li> <li>a Shader is a fn of xy -> rgba</li> <li>This is cool!!</li> <li>Pseudo random number generator = high-amplitude sin sampled by fract (flatten out to fractional components)</li> </ul> <h3 id="kaya">Kaya</h3> <ul> <li>Declarative Reactive</li> <li>Object Query Language</li> <li>Better query language for tabular / spreadsheet data</li> </ul> <h3 id="céu">Céu</h3> <ul> <li>Structured Reactive Programming</li> <li><code class="highlighter-rouge">await</code>, composition, synchronous execution</li> <li>Neat GUI programming ideas</li> <li><a href=""></a></li> </ul> <h3 id="joel--codehint">Joel / CodeHint</h3> <ul> <li>Dynamic and Interactive Synthesis for Modern IDEs</li> <li>Autocomplete for the modern age</li> <li>incorporates some concepts from lighttable</li> <li>for Java only now</li> </ul> <h3 id="julien--facebook--hack">Julien / Facebook / Hack</h3> <ul> <li>Evolving PHP</li> <li>Julien = one of the language designers for Hack <ul> <li>oCaml programmer at heart</li> </ul> </li> <li>Whatever you choose, in 10-15 years it’ll be outdated</li> <li>FB PHP <ul> <li>over 10M sloc</li> <li>Monolithic</li> <li>reinvesting in mercurial and git to make them scale</li> <li>pushing twice a day</li> <li>mostly migrated to Hack (except for php libs)</li> </ul> </li> <li>hack = statically typed language for hhvm, compatible with php, same representation at runtime</li> <li>instantaneous type-checking, with gradual typing</li> </ul> <h2 id="2014-09-18">2014-09-18</h2> <h3 id="keynote---the-mess-were-in">Keynote - The Mess We’re In</h3> <ul> <li>Joe Armstrong - one of the creators of Erlang</li> <li>What’s going wrong and why, physical limits of computation</li> <li>Software’s getting worse over time. When it doesn’t work we don’t understand why</li> <li>We’ve created billions of man-hours of work to do in the future!</li> </ul> <p>–</p> <ul> <li>Bad code is code you can’t immediately understand, code that requires a brain shift to understand</li> <li>6 32-bit integers can be in the same number of states as the number of atoms on earth</li> <li>need 2^7633587786 universes to have the same number of states as any one laptop</li> </ul> <p>–</p> <ul> <li>failure - you cant handle failure with just one computer</li> <li>a neat exercise might be RSA in roman numerals</li> <li>new programmers have no common language (old-school: sh, make, C)</li> <li>efficiency vs. clarity - balance between abstraction and speed</li> <li>naming is hard</li> <li>byzantine general problem, causality <ul> <li>2-phase commit breaks the laws of physics ;)</li> </ul> </li> <li>simultaneity - observers see different things based on location</li> <li>entropy always increases</li> <li>c^2/h = the bremmerman limit - how fast things can vibrate, or change state. The fastest clock rate you can get</li> <li>the ultimate 1kg computer - a black hole <ul> <li>10^51 ops/sec, lasts for 10^-21 second, emits data through quantum radiation</li> <li>Hawkins radiation and quantum entanglement</li> <li>conventional - 10^9 op/s</li> </ul> </li> <li>the real ultimate computer <ul> <li>the entire universe - 10^123 ops so far, can store 10^92 bits</li> <li>information theory - if it takes more than 10^123 to crack a code, it’s uncrackable</li> </ul> </li> <li>entropy reverser - “Let’s break the 2nd law of thermodynamics!”</li> <li>Naming objects <ul> <li>URIs aren’t perfect. hashes are useful, validatable, perfect. (a la darknet)</li> <li>Algorithms for finding hashed data - chord, kademlia. basic P2P systems</li> <li>combined you get gittorrent ;)</li> </ul> </li> <li>collapse <ul> <li>find all files</li> <li>merge all <em>similar</em> files - maybe least compression difference: size(C(A)) ~ size(C(A+B)). if identical, compressed concat should be tiny bit larger. Works for small data, not big data. There are other better methods</li> </ul> </li> <li>computing is about controlling complexity, and we’ve failed miserably</li> <li>make small, validatable systems, and connect them</li> <li>computers are using more energy than air traffic, etc. we need to make computers operate more efficiently</li> <li>let’s clean up the mess we’ve made</li> </ul> <h3 id="unix-smalltalk">Unix smalltalk</h3> <ul> <li>neat dynamic symbol loading, autoloading C libraries from Node as proof of concept</li> </ul> <h3 id="lolchat---league-of-legends-chat">Lolchat - League of Legends Chat</h3> <ul> <li>lolwut?</li> <li>7.5M concurrent players!</li> <li>1b events routed per server per day</li> <li>11k messages/sec!</li> <li>Using XMPP protocol, but with their own modifications</li> <li>Used ejabberd at the beginning - was good out of the box but they customized it later</li> <li>Riak - database</li> <li>rescheduling queries for later processing</li> <li>cloned Riak set for ETL jobs</li> <li>rewrote most of ejabberd - 5-10% is left from open-source! <ul> <li>removed unnedded code, optimized certain flow paths, wrote lots of tests</li> <li>example: asymmetric friendships caused too much messaging overhead, changed protocol to be symmetric friendship</li> <li>example: removed muc router for multi-user chat</li> </ul> </li> <li>changes to erlang <ul> <li>patched erlang and otp to remove some generic stuff they didn’t need for better overall performance</li> <li>added transactional multi-server code reloading</li> </ul> </li> <li>started with mysql but moved to riak for performance, stability, and flexibility (schema changing speed)</li> <li>Riak - truly masterless, so fully HA <ul> <li>CRDT libraries help with write conflicts (dropping C in CAP)</li> <li>scaled linearly</li> </ul> </li> <li><em>lessons learned</em> <ul> <li><em>key to success is to understand what our system is actually doing</em> <ul> <li>built over 500 realtime counters to monitor things</li> <li>each metric and counter has threshholds to define normal and abnormal <ul> <li>using graphite, zabbix, and nagios</li> </ul> </li> </ul> </li> <li>use Feature Toggles!</li> <li>patch bugs on the fly</li> <li>logging important - log healthy state as much as failure state <ul> <li>using <a href="">Honu?</a></li> </ul> </li> <li>always load-test code. generate metrics on load-test environment and learn about it. Simulate failures in test too</li> <li>be ready for failure - things will fail that are out of your contorl</li> </ul> </li> </ul> <h3 id="sociology-of-programming-languages">Sociology of programming languages</h3> <ul> <li>who adopts what</li> <li>keeping perceived adoption pain low</li> <li>programming is actually social</li> <li>design smarter by exploiting social foundations</li> <li>ecological model of adoption <ul> <li>music spreads through friends (people)</li> </ul> </li> <li>hammerprinciple data + 2-week intensive survey + mooc data + scraping sourceforge = <a href=""></a></li> <li>lots of room in the long tail for niche languages</li> <li>managed languages are much easier to learn</li> <li>Peter Norvig quote about learning at least half a dozen languages</li> <li>diffusion of innovation: <ul> <li>knowledge, persuasion, decision, trial, confirmation</li> <li>diffusions catalysts: clear relative advantage, observable, trialability and compatibility</li> <li>make something observable and it’ll catch on much better</li> </ul> </li> <li>dataviz and renderfarms tonight <a href="">@lmeyerov</a></li> </ul> <h3 id="rules--ryanbrush">Rules / <a href="">@ryanbrush</a></h3> <ul> <li>intelligent systems derive their power form the knowledge they posses, not how it’s encoded</li> <li>structure your rules system as a graph / network <ul> <li>Forgy’s thesis gave rise to expert systems</li> <li>They were overhyped - lots of intellectually dishonest promises were made</li> </ul> </li> <li>expert systems were mostly forgotten in the 90s</li> <li>Martin Fowler on rules engines in 2009 <ul> <li>it doesn’t end well…</li> <li>good for simple problems but problems don’t stay simple</li> </ul> </li> <li>talking about logical constraint systems (prolog-ish)</li> <li><a href=""></a></li> <li>Agile works when iteration is cheap</li> <li>tools from unagile industries: <ul> <li>blueprints - unambiguous specification that describes our system</li> <li>floorplan - simplified projection of a blueprint</li> </ul> </li> <li>rules are a tool for developer to simplify code by minimizing semantic gap</li> </ul> <h3 id="idris">Idris</h3> <ul> <li>Dependent types = types dependent on values</li> <li>NICTA on SEO4 - formally verified kernel</li> <li>Adventures in Extraction - Wouter Swierstra</li> <li>extraction = taking formally verified dependently typed code and creating executable code <ul> <li>extraction was inefficient 4 years ago at least</li> </ul> </li> <li>idris is making dependent types more practical than coq</li> <li>iridium - window manager like xmonad (60% idris, 40% obj-c for mac apis)</li> <li><em>brain melt</em></li> <li>Algebraic laws lead to correctness guarantees</li> </ul> <h3 id="crdts-etc">CRDTs etc</h3> <ul> <li>CP systems - concensus protocol, like Chubby, Doozer, ZooKeeper, Consul, etcd (<code class="highlighter-rouge">Raft</code> is latest hipster CP)</li> <li>AP - Cassandra, Riak, Mongo, Couch <ul> <li>eventual consistency</li> <li>all are different and rarely provable guarantees</li> </ul> </li> <li>delay, drop, out of order, duplication <ul> <li>CP abstracts these away</li> <li>AP allow them to happen and deal with it</li> </ul> </li> <li>CALM principle <ul> <li>Consistency As Logical Monotonicity</li> <li>A system as it’s accepting messages should only grow in one direction (a counter that only gets bigger) bloom lang</li> <li>ACID 2.0 - Associative Commutative Idempotent Distributed <ul> <li>reification of CALM</li> <li>CRDT <ul> <li>conflict-free replicated data type, provably consistent without strong consensus</li> </ul> </li> </ul> </li> </ul> </li> </ul> <h4 id="crdts">CRDTs</h4> <ul> <li>increment-only counter - increment or read <ul> <li>Need associative, commutative, and idempotent function</li> <li>addition is associative, commutative, not idempotent</li> <li>Set union - associative, commutative, idempotent</li> <li>on track plays, you can use userid as set key to union - gset crdt</li> <li>read - read all values and rely on ACI to give correct value</li> </ul> </li> <li>convenient solution to a problem but it requires bending the problem</li> <li>devops - acknowledged that developers are the best people to run their own code in production. Devs are ops.</li> <li>soundcloud event - timestamp, actor, verb, thing <ul> <li>distribution methods: <ul> <li>fan-out on write</li> <li>fan-in on read (much nicer for products mostly) <ul> <li>can be slow</li> </ul> </li> </ul> </li> <li>CRDT Sets - G-set, 2p-set, or-set, roshi set <ul> <li>roshi - single logical set represented by 2 physical sets - add set and remove set</li> </ul> </li> <li>built with sharded redis zset with lua extension</li> </ul> </li> <li>basically reimplemented Cassandra in go</li> <li><a href=""></a></li> </ul> <h3 id="finagle-and-clojure---sam-neubart">Finagle and Clojure - Sam Neubart</h3> <ul> <li>finagle-clojure - highly concurrent rpc on the jvm</li> <li>“your server as a function” - finagle paper</li> <li>makes distributed systems obvious</li> <li>finagle works with zipkin</li> <li>build with netty - async io on jvm</li> <li>uses Futures! <ul> <li>3 states - undefined (pending), success, error</li> </ul> </li> <li>blocks on IO, locks, and waiting for futures <ul> <li>composes futures to stay async</li> </ul> </li> </ul> <h2 id="2014-09-19">2014-09-19</h2> <h3 id="nada-amin--programming-should-eat-itself">Nada Amin / Programming should eat itself</h3> <ul> <li>Programming to understand programming</li> <li>Reflective language Black in Scheme</li> <li>TABA / convolution</li> <li>very academic</li> </ul> <h3 id="evan-czaplicki---elm--frp">Evan Czaplicki - Elm / FRP</h3> <ul> <li><a href="">@czaplic</a> wrote Elm</li> <li>FRP - dealing with the world <ul> <li>in elm, it’s the signal graph</li> <li>explicitly structured time</li> <li>signals are infinite</li> </ul> </li> <li>FRP lets you do time-travel</li> <li><a href="">higher-order functional reactive programming in bounded space</a> <ul> <li>linear types (out of idris)</li> <li>maybe not actually useful</li> </ul> </li> <li>async dataflow - imperative FRP <ul> <li>flatten : Signal (Signal a) -> Signal a</li> <li>ReactiveExtensions ReactiveCocoa Bacon.js</li> </ul> </li> <li>arrowized FRP - Yampa, Netwire, Automaton (elm) <ul> <li>swapping in and out Signal handlers</li> <li>abstraction replacement for pure functions and modules</li> <li>helpful for music..</li> </ul> </li> <li>you can hook up to elm from non-elm stuff (with something like bacon.js etc)</li> <li><a href=""></a></li> </ul> <h3 id="purescript---bodil">Purescript - <a href="">@bodil</a></h3> <ul> <li>JS sux d00d</li> <li>game engine - functional, reactive, animation stream in game loop</li> <li>“elm - if haskell were designed by a usability expert”</li> <li>constraint - low deliverable size and unpredictable environment</li> <li>originally built with typescript and baconjs (rxjs is more powerful) and html canvas <ul> <li>game loop reactive stream</li> <li>in production</li> </ul> </li> <li>once you’ve done haskell you can’t go back</li> <li>purescript focuses on producing very neat js code <ul> <li>haskelly syntax</li> <li>close to the js</li> <li>actually pure - purely functional</li> <li>effects & ffi (monads and js access)</li> </ul> </li> </ul> <h3 id="rich-hickey---transducers">Rich Hickey - Transducers</h3> <ul> <li>Transducers - extracting the essence of map, filter, et al, recasted as process transformations</li> <li>you can transduce a process that is a succession of steps that ingests an input</li> <li>a seeded left reduce, more as a process than something that’s building a thing</li> <li>transduce - to lead across</li> <li>example: put the baggage on the plane, as you do that <ul> <li>break apart pallets,</li> <li>remove bags that smell like food,</li> <li>label heavy bags</li> </ul> </li> <li>conveyances, sources, and sinks are irrelevant in process definition</li> <li>transducers are fully composable</li> <li>hard to model in strictly typed systems because each step returns a different fixed type <ul> <li>sounds like a good problem for Ruby! (trololololol)</li> </ul> </li> <li>early termination support (take-while non-ticking?)</li> </ul> <h3 id="clojurescript">Clojurescript</h3> <ul> <li>C.A.R. Hoare - building without deficiencies. There’s a significant difference between simple and easy. Ease doesn’t necessarily imply simplicity.</li> <li>@Prismatic: Still working our their core product, need to iterate fast. Using clojure on the backend</li> <li>global mutable state = trouble</li> <li>yeaaaah no sell on why I’d do this instead of others</li> </ul> <h3 id="haste-full-stack-haskell-for-non-phd-candidates">Haste: Full-Stack Haskell for Non-PhD Candidates</h3> <ul> <li><a href="">@lasericus</a> and <a href="">@coopernurse</a></li> <li>industry developers, wanted to build some stuff in Haskell but didn’t know where to go</li> <li>language properties: performance, productivity, safety</li> <li>Haste - Haskell -> JS compiler</li> <li>Haste project people would like to write something that overall spans client and server, but that’s not required</li> <li>cabal install haste; haste-boot</li> <li>netwire mentioned again</li> <li>Has FFI support - ccall and ffi</li> <li>ccall is much faster but requires type declaration</li> <li>exported functions go in Haste js namespace</li> <li>compiled js is not awesome</li> <li>you can test with Hspec</li> <li>Haskell’s Integer is not the same as JS’s Number! Hspec can lie!</li> <li>Pure-haskell libraries will work! (from hackage) with haste-inst</li> <li>could use a better API for DOM manip</li> <li>upenn CS 194 - learn haskell better <a href=""></a></li> </ul> <h3 id="8-fallacies-of-distributed-computing---stephen-asbury">8 Fallacies of Distributed Computing - Stephen Asbury</h3> <ul> <li>list on wikipedia</li> <li>Fallacy: a wrong belief, a false idea, or a mistaken idea</li> <li>backhoes suck - they kill your internets</li> <li>seen this all before, going to another talk…</li> </ul> <h3 id="game-in-haskell">game in haskell</h3> <ul> <li>eleria - FRP haskell</li> <li>network in her examples is the set of things that make state</li> <li>generate signals for all the things!</li> <li>never use unsafecoerce!</li> <li>used openAL for sound, not threadsafe but worked</li> <li>keyframe interpolated or skeletal animation</li> <li>made objects in blender to make keyframes (it’s not user-friendly)</li> <li>physics - 2d library = chipmunk / hipmunk (haskell bindings) <ul> <li>not easy to combine with FRP…</li> </ul> </li> <li>it’s far from perfect..</li> <li>making a game is much harder to get the UX right than the code</li> <li>[Nikki and the robots] is commercially made hasklel with QT, open-source code</li> <li>game studio made haskell sdl window on mobile</li> <li>chucklefish is hiring haskell game devs (wayward tides)</li> </ul> <h3 id="visualizing-persistent-data-structures--dann-toliver">Visualizing Persistent Data Structures / Dann Toliver</h3> <ul> <li>Data structures are “accidentally” complicated</li> <li>people love to complicate data structure language</li> <li>abstract vs. concrete data structures <ul> <li>abstract - stack, queue, list, array</li> <li>concrete - linked list, array</li> <li>array - list with random access support and the data structure that supports it</li> <li>adjectives usually mean concrete, unless there are too many, like self-balancing binary search tree… or too few, like priority queue</li> <li>proper name in it then it’s always concrete ;)</li> </ul> </li> <li>persistent data structure</li> <li>fully-persistent data structures - includes changes over time, like git</li> <li>confluently persistent - you can merge a branch back into the main</li> <li><em>batched queue</em> - 2 stacks, push onto one, pop the other, when pop stack empties pop/push all from push stack to pop stack</li> <li><em><a href="">hash array mapped trie</a></em> - fast, great for maps, dandy vectors, constant time</li> <li>very cool js viz of data structure values</li> <li>mori vs. fb vector queues</li> </ul> <h3 id="our-shared-joy-of-programming">Our shared joy of programming</h3> <ul> <li>take care of your personal joy: <ul> <li>Get enough sleep</li> <li>eat well, exercise</li> <li>keep interested and keep learning</li> <li>code can pull you out of darkness</li> </ul> </li> <li>Sharing joy increases our personal joy, binds us as a community, lifts us up, and makes us more than ourselves</li> <li><a href="">A little video ;)</a></li> </ul> <img src="" height="1" width="1" alt=""/> Free and Open Source 2014-09-14T00:00:00-04:00 <h3 id="open-source-open-communities">Open Source, Open Communities</h3> <p>Open source is really great. I wouldn’t be where I am today without it. We’re all standing on the backs of giants. Think about it—if we hadn’t had the open-source movement, we’d all be paying thousands of dollars for access to mediocre software that would allow us to write slightly less mediocre software in carefully defined boundaries. I really love open source.</p> <p>I also love the communities that form around open-source. I would definitely not know how to do what I do without the wholehearted support of the communities I’ve been a part of.</p> <h3 id="ideastuff">Ideastuff</h3> <p>Communities thrive on the open exchanges of ideas, especially when they share their ideas with new people who question, challenge, and help forge clarity. New people find groups through a variety of ways, but they’re much less likely to join if there’s a cost involved.</p> <p>Similarly, new people are less likely to seek out a new technology if there’s a cost to learn it.</p> <p>Technology thrives on new ideas. Software itself is pure idea, and without a free and open exchange of that stuff it tends to wilt and die.</p> <h3 id="access">Access</h3> <p>All of us have benefited from free and open software, we all owe a debt to the people who created it and to the communities who helped create those people. I work hard to keep the meetups I’m involved with free because I believe in freely giving back to the communities that have gotten me where I am. I don’t take sponsorships for The Ruby Hangout because my costs are minimal, and I make an effort to keep in-person event sponsorships limited to space, food, and other necessary costs.</p> <p>The <a href="">Arlington Ruby Users’ Group</a> has a really amazing mentorship program. Experts freely give their time to help new people learn Ruby and progress in their careers. These are highly skilled people who could be billing a lot of money for their time giving it away for free. Because they believe in what I believe.</p> <h3 id="paid-content">Paid Content</h3> <p>I heard about a meetup recently that charges for membership. There are blogs you can only read if you pay. And there’s at least one mailing list that you can only get on with money. The paid content in each of these is training material or access to the experts.</p> <p>I don’t begrudge people their right to make money, but I also don’t like putting up barriers to content. These barriers, if enough come around (and there are decent monetary incentives to do so), could keep new people from joining our communities. That could stop the flow of new ideas into our discussions and could promote community rot.</p> <h3 id="free-communities">Free Communities</h3> <p>I believe in free, open-source software and free, open-source ideas. I believe in community. I believe in growth and change and continual improvement through continual re-examination. I believe new people with new ideas are they only way to do that. Free communities are strong communities. Strong communities create amazing software that I want to use. Let’s all do what we can to strengthen our communities.</p> <p>If you sell training or help to developers, please be awesome and do something like <a href="">Avdi’s Postcard Offer</a>. Offer new people a way to get in for free, help them out and they’ll help you out eventually. Or even better—spend time teaching new people for free. The <a href="">Learn Ruby meetup</a> in DC is a perfect example of people spending their personal time helping others level up. Let’s grow our community together!</p> <img src="" height="1" width="1" alt=""/> Minecraft Mod with RubyBukkit 2013-01-19T00:00:00-05:00 <p>The other day I went to <a href="">CoderDojoDC</a> and it seemed like every kid there was obsessed with Minecraft. I recently interviewed <a href="">Charles Nutter</a>, who mentioned you could mod Minecraft with <a href="">JRuby</a>. I wanted to get some experience with it so I could help the kids out, so I figured I’d give it a shot. It wasn’t hard!</p> <p>I did this with Ubuntu linux. YMMV with other OS’s, but it shouldn’t be that much different.</p> <h3 id="gather-your-forces">Gather your forces</h3> <p>You have to have a few things installed to begin writing your mod:</p> <ul> <li>First off, you need <a href="">Minecraft</a> itself.</li> <li>Download <a href="">RubyBukkit</a> from their <a href="">downloads page</a> (I used version <a href="">0.8</a>)</li> <li>Go to <a href="">JRuby’s downloads page</a> and download the “Complete .jar” (I used 1.7.2)</li> <li>Follow the <a href="">“Get CraftBukkit”</a> instructions. At the time I’m writing this, I needed to get the <a href="">beta build</a> to be compatible with the version of Minecraft the client was running, so if you see an error connecting to the server, try that, just replace <code class="highlighter-rouge">craftbukkit.jar</code> in the instructions with the beta one.</li> </ul> <p>At this point you should be able to start the craftbukkit server and you’ll see some output like:</p> <figure class="highlight"><pre><code class="language-text" data-23:04:48 [INFO] Starting minecraft server version 1.4.7 23:04:48 [INFO] Loading properties 23:04:48 [INFO] Default game type: SURVIVAL 23:04:48 [INFO] Generating keypair (etc)</code></pre></figure> <h3 id="rubybukkit">RubyBukkit</h3> <p>Now you need to set up RubyBukkit. Move the .jar file you downloaded from RubyBukkit’s website (<code class="highlighter-rouge">RubyBukkit.jar</code>) into the plugins folder in the minecraft server’s main folder. In there, create a folder called <code class="highlighter-rouge">RubyBukkit</code>, and in that folder put your JRuby .jar file and name it <code class="highlighter-rouge">jruby.jar</code>. In the end you should have something like this:</p> <figure class="highlight"><pre><code class="language-text" data-$ find plugins/ plugins/ plugins/RubyBukkit.jar plugins/RubyBukkit plugins/RubyBukkit/jruby.jar</code></pre></figure> <p>This time when you start the craftbukkit server you should see (among lots of other text):</p> <figure class="highlight"><pre><code class="language-text" data-lang=...</code></pre></figure> <p>If you see that, you’re ready to program! If not, RubyBukkit is pretty helpful, so look at its error messages. If there’s nothing from RubyBukkit at all, maybe you didn’t install it correctly.</p> <h3 id="plugins">Plugins</h3> <p>As my minecraft server was playing with a brand new world, I didn’t have a home or even very good tools. I did have some dirt, though, so I wrote this plugin:<">end</span></code></pre></figure> <p>You can see the plugin system is event driven, so <code class="highlighter-rouge">onEnable</code> in my <code class="highlighter-rouge">AwesomeDirt</code> <em>diamond pickaxe</em>. After adding that recipe to the server, I now have some pretty awesome dirt!</p> <p>To get it to work, I saved that code into a file called <code class="highlighter-rouge">awesome_dirt.rb</code> and placed it in the RubyBukkit folder in the plugins folder, so <code class="highlighter-rouge">plugins/RubyBukkit/awesome_dirt.rb</code></p> <p><img src="/img/diamond.png" alt="it's like magic!" /></p> <h3 id="digging-holes">Digging holes</h3> <p>Of course, even diamond pickaxes aren’t fast enough sometimes, so I modified my code to add the <code class="highlighter-rouge">/dig</code> command:<="n">commands</span> <span class="ss">:dig</span> <span class="o">=></span> <span class="p">{</span> <span class="ss">:description</span> <span class="o">=></span> <span class="s2">"digs a tunnel"</span><span class="p">,</span> <span class="ss">:usage</span> <span class="o">=></span> <span class="s2">"/dig"</span> <span class=">def</span> <span class="nf">onCommand</span><span class="p">(</span><span class="n">sender</span><span class="p">,</span> <span class="n">command</span><span class="p">,</span> <span class="n">label</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="k">case</span> <span class="n">command</span><span class="p">.</span><span class="nf">name</span> <span class="k">when</span> <span class="s1">'dig'</span> <span class="c1"># Sender is the player who ran the command</span> <span class="n">loc</span> <span class="o">=</span> <span class="n">sender</span><span class="p">.</span><span class="nf">location</span> <span class="n">dig</span><span class="p">(</span><span class="n">loc</span><span class="p">)</span> <span class="k">end</span> <span class="kp">true</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">dig</span><span class="p">(</span><span class="n">loc</span><span class="p">)</span> <span class="c1"># Yaw is the easiest way to get a 2d-coordinate player facing</span> <span class="n">dir</span> <span class="o">=</span> <span class="p">(</span><span class="n">loc</span><span class="p">.</span><span class="nf">yaw</span> <span class="o">/</span> <span class="mf">90.0</span><span class="p">).</span><span class="nf">round</span><span class="p">.</span><span class="nf">abs</span> <span class="c1"># map it into this array for easier comprehension</span> <span class="n">direction_facing</span> <span class="o">=</span> <span class="p">[</span><span class="ss">:south</span><span class="p">,</span> <span class="ss">:west</span><span class="p">,</span> <span class="ss">:north</span><span class="p">,</span> <span class="ss">:east</span><span class="p">,</span> <span class="ss">:south</span><span class="p">][</span><span class="n">dir</span><span class="p">]</span> <span class="n">world</span> <span class="o">=</span> <span class="n">loc</span><span class="p">.</span><span class="nf">world</span> <span class="n">size</span> <span class="o">=</span> <span class="mi">3</span> <span class="n">size</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="o">|</span><span class="n">delta_y</span><span class="o">|</span> <span class="c1"># 0, 1, 2</span> <span class="n">size</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="o">|</span><span class="n">delta_left_right</span><span class="o">|</span> <span class="n">delta_a</span> <span class="o">=</span> <span class="n">delta_left_right</span> <span class="o">-</span> <span class="mi">1</span> <span class="c1"># -1, 0, 1</span> <span class="n">size</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="o">|</span><span class="n">delta_front</span><span class="o">|</span> <span class="n">delta_b</span> <span class="o">=</span> <span class="n">delta_front</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># 1, 2, 3</span> <span class="n">floored_x</span> <span class="o">=</span> <span class="n">loc</span><span class="p">.</span><span class="nf">x</span><span class="p">.</span><span class="nf">floor</span> <span class="n">floored_z</span> <span class="o">=</span> <span class="n">loc</span><span class="p">.</span><span class="nf">z</span><span class="p">.</span><span class="nf">floor</span> <span class="n">block_y</span> <span class="o">=</span> <span class="n">loc</span><span class="p">.</span><span class="nf">y</span><span class="p">.</span><span class="nf">floor</span> <span class="o">+</span> <span class="n">delta_y</span> <span class="c1"># which blocks we pick are dependent on which way we're looking</span> <span class="n">block_x</span><span class="p">,</span> <span class="n">block_z</span> <span class="o">=</span> <span class="k">case</span> <span class="n">direction_facing</span> <span class="k">when</span> <span class="ss">:north<">:south<">:east<">when</span> <span class="ss">:west<">end</span> <span class="n">block</span> <span class="o">=</span> <span class="n">world</span><span class="p">.</span><span class="nf">getBlockAt</span><span class="p">(</span><span class="n">block_x</span><span class="p">,</span> <span class="n">block_y</span><span class="p">,</span> <span class="n">block_z</span><span class="p">)</span> <span class="c1"># 0 is Air. See</span> <span class="n">block</span><span class="p">.</span><span class="nf">setTypeId</span><span class="p">(</span> <span class="mi">0</span> <span class="p">)</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span></code></pre></figure> <p!</p> <p>You can see the <code class="highlighter-rouge">onCommand</code> callback is called for the <code class="highlighter-rouge">/dig</code> command.</p> <p><img src="/img/hallways.png" alt="My lazy house" /></p> <h3 id="useful-stuff">Useful stuff</h3> <p>In the craftbukkit server console, you can run the <code class="highlighter-rouge">reload</code> command to reload your plugin. This way I was able to get a nice quick dev/test loop (write some code, save the file, <code class="highlighter-rouge">reload</code> in the server, test it in the client, repeat).</p> <p>In the client itself, you can hit F3 to get some debug info including things like where you are, the direction you’re facing, and all kinds of other stuff. Invaluable for a plugin developer!</p> <p>Getting some debug output from your own plugin isn’t too bad, you can either use <code class="highlighter-rouge">sender.sendMessage("some string")</code> to print stuff on the client or just <code class="highlighter-rouge">puts</code> to see stuff written out to the craftbukkit server console. Not magic but effective.</p> <h3 id="last-thoughts">Last thoughts</h3> <p>Doing math in a coordinate system is probably beyond most of these kids right now, but adding recipes will probably be pretty simple, and I imagine there are a number of other relatively easy things we could try, too.</p> <p>I’m mostly very impressed by how simple it was to get going with this. Kudos to the Bukkit team for their great infrastructure, and to RubyBukkit for making it possible with JRuby!</p> <p>Update: <a href="">Evan Light</a> mentioned that using <a href="">Purugin</a> makes this all even easier. Give it a shot!</p> <img src="" height="1" width="1" alt=""/> Measuring Rails Boot Time 2012-09-07T00:00:00-04:00 <p>Our main rails app is pretty slow to load, so I hacked together a really simple report to show what’s going on during boot. This system could use a lot of improvement to aggregate together requires, but it’s enough to draw some immediate conclusions.</p> <p>First, I created this script that overrides <code class="highlighter-rouge">Kernel.require</code>:</p> <figure class="highlight"><pre><code class="language-ruby" data-<span class="no">Kernel</span><span class="p">.</span><span class="nf">require</span> <span class="s1">'singleton'</span> <span class="k">class</span> <span class="nc">BootMeasurement</span> <span class="kp">include</span> <span class="no">Singleton</span> <span class="k">def</span> <span class="nf">initialize</span> <span class="vi">@req_starts</span> <span class="o">=</span> <span class="p">{}</span> <span class="vi">@req_times</span> <span class="o">=</span> <span class="p">{}</span> <span class="k">end</span> <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">start</span><span class="p">(</span><span class="n">requirement</span><span class="p">)</span> <span class="n">instance</span><span class="p">.</span><span class="nf">start</span><span class="p">(</span><span class="n">requirement</span><span class="p">.</span><span class="nf">to_s</span><span class="p">)</span> <span class="k">end</span> <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">finish</span><span class="p">(</span><span class="n">requirement</span><span class="p">)</span> <span class="n">instance</span><span class="p">.</span><span class="nf">finish</span><span class="p">(</span><span class="n">requirement</span><span class="p">.</span><span class="nf">to_s</span><span class="p">)</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">start</span><span class="p">(</span><span class="n">req</span><span class="p">)</span> <span class="vi">@first</span> <span class="o">||=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="vi">@req_starts</span><span class="p">[</span><span class="n">req</span><span class="p">]</span> <span class="o">||=</span> <span class="p">[]</span> <span class="vi">@req_starts</span><span class="p">[</span><span class="n">req</span><span class="p">]</span> <span class="o"><<</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">finish</span><span class="p">(</span><span class="n">req</span><span class="p">)</span> <span class="k">raise</span> <span class="s2">"Requirement </span><span class="si">#{</span><span class="n">req</span><span class="si">}</span><span class="s2"> unstarted!"</span> <span class="k">unless</span> <span class="vi">@req_starts</span><span class="p">.</span><span class="nf">include?</span> <span class="n">req</span> <span class="vi">@req_times</span><span class="p">[</span><span class="n">req</span><span class="p">]</span> <span class="o">||=</span> <span class="p">[]</span> <span class="vi">@req_times</span><span class="p">[</span><span class="n">req</span><span class="p">]</span> <span class="o"><<</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="o">-</span> <span class="vi">@req_starts</span><span class="p">[</span><span class="n">req</span><span class="p">].</span><span class="nf">last</span> <span class="vi">@last</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">now</span> <span class="k">end</span> <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">report</span> <span class="n">instance</span><span class="p">.</span><span class="nf">report</span> <span class="k">end</span> <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">fmt</span><span class="p">(</span><span class="n">time</span><span class="p">)</span> <span class="s2">"</span><span class="si">#{</span><span class="n">time</span><span class="p">.</span><span class="nf">round</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="si">}</span><span class="s2"> sec"</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">report</span> <span class="k">return</span> <span class="k">unless</span> <span class="vi">@req_times</span><span class="p">.</span><span class="nf">any?</span> <span class="n">lng</span> <span class="o">=</span> <span class="vi">@req_times</span><span class="p">.</span><span class="nf">keys</span><span class="p">.</span><span class="nf">max</span><span class="p">{</span><span class="o">|</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="o">|</span> <span class="n">a</span><span class="p">.</span><span class="nf">length</span> <span class="o"><=></span> <span class="n">b</span><span class="p">.</span><span class="nf">length</span> <span class="p">}.</span><span class="nf">length</span> <span class="vi">@req_times</span><span class="p">.</span><span class="nf">map</span> <span class="k">do</span> <span class="o">|</span><span class="n">req</span><span class="p">,</span> <span class="n">times</span><span class="o">|</span> <span class="n">ttime</span> <span class="o">=</span> <span class="n">times</span><span class="p">.</span><span class="nf">inject</span><span class="p">(</span><span class="mi">0</span><span class="p">){</span><span class="o">|</span><span class="n">s</span><span class="p">,</span> <span class="n">e</span><span class="o">|</span> <span class="n">s</span> <span class="o">+</span> <span class="n">e</span> <span class="p">}</span> <span class="p">[</span><span class="n">req</span><span class="p">,</span> <span class="n">ttime</span><span class="p">]</span> <span class="k">end</span><span class="p">.</span><span class="nf">sort</span><span class="p">{</span><span class="o">|</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="o">|</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o"><=></span> <span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="p">}.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">req</span><span class="p">,</span> <span class="n">ttime</span><span class="o">|</span> <span class="nb">puts</span> <span class="s2">"</span><span class="si">#{</span><span class="n">req</span><span class="p">.</span><span class="nf">ljust</span><span class="p">(</span><span class="n">lng</span><span class="p">,</span> <span class="s1">' '</span><span class="p">)</span><span class="si">}</span><span class="s2">: </span><span class="si">#{</span><span class="no">BootMeasurement</span><span class="p">.</span><span class="nf">fmt</span><span class="p">(</span><span class="n">ttime</span><span class="p">)</span><span class="si">}</span><span class="s2">"</span> <span class="k">end</span> <span class="nb">puts</span> <span class="s2">"Total time spent requiring: </span><span class="si">#{</span><span class="no">BootMeasurement</span><span class="p">.</span><span class="nf">fmt</span><span class="p">(</span><span class="vi">@last</span> <span class="o">-</span> <span class="vi">@first</span><span class="p">)</span><span class="si">}</span><span class="s2">"</span> <span class="k">end</span> <span class="k">end</span> <span class="k">alias</span> <span class="n">kernel_base_require</span> <span class="nb">require</span> <span class="k">def</span> <span class="nf">require</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="no">BootMeasurement</span><span class="p">.</span><span class="nf">start</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="n">kernel_base_require</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="no">BootMeasurement</span><span class="p">.</span><span class="nf">finish</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="k">end</span></code></pre></figure> <p>Then in <code class="highlighter-rouge">boot.rb</code>, I require it:</p> <figure class="highlight"><pre><code class="language-ruby" data-<span class="nb">require<">'..'</span><span class="p">,</span> <span class="s1">'require_timer'</span><span class="p">)</span> <span class="nb">require</span> <span class="s1">'rubygems'</span> <span class="c1"># Set up gems listed in the Gemfile.</span> <span class="no">ENV</span><span class="p">[</span><span class="s1">'BUNDLE_GEMFILE'</span><span class="p">]</span> <span class="o">||=</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'../../Gemfile'</span><span class="p">,</span> <span class="kp">__FILE__</span><span class="p">)</span> <span class="nb">require</span> <span class="s1">'bundler/setup'</span> <span class="k">if</span> <span class="no">File</span><span class="p">.</span><span class="nf">exists?</span><span class="p">(</span><span class="no">ENV</span><span class="p">[</span><span class="s1">'BUNDLE_GEMFILE'</span><span class="p">])</span></code></pre></figure> <p>Then I run this simple runner script:</p> <figure class="highlight"><pre><code class="language-ruby" data-<span class="no">BootMeasurement</span><span class="p">.</span><span class="nf">report</span> <span class="nb">puts</span> <span class="s2">"Done"</span></code></pre></figure> <p>And I see something like</p> <figure class="highlight"><pre><code class="language-text" data-user@host:~/src/rails_app (develop) $ time bundle exec rails r booted.rb ( lots of lines elided... ) exception_notifier/notifier : 1.37 sec yard-cucumber : 1.63 sec net/ssh : 2.07 sec net/ssh/gateway : 2.09 sec capistrano/configuration/connections : 2.17 sec capistrano/configuration : 3.25 sec /home/user/src/rails_app/config/environment.rb : 14.24 sec /home/user/src/rails_app/config/application : 29.57 sec Total time spent requiring: 43.82 sec Done real 0m48.486s user 0m46.247s sys 0m1.344s</code></pre></figure> <p>Not perfect, but gives me some insight!</p> <img src="" height="1" width="1" alt=""/> On Entrepreneurship 2012-03-18T00:00:00-04:00 <p>You live in a city on the ocean. Your fellow citizens are generally part of two groups: normal people and people who have won medals. The people with medals are accorded higher honors and have access to the best things in life. You, of course, want a medal.</p> <p>The problem is, the only way to get a medal is to swim across the ocean. Everyone who makes it across gets a medal. You even get free transportation back to the city.</p> <p>Swimming across that ocean sounds pretty tempting. It’s just a swim, right? It’s only a few miles. You can do it. You’ve been training.</p> <p>You decide today’s the day. You go down to the beach and look out over the ocean. Hey, the sun’s even shining. This will be easy!</p> <p>You jump in and as you start swimming across, to your horror you find hands grabbing your ankles trying to pull you under! You start kicking and fighting, but you’re not prepared for this. You’re dragged under.</p> <p>Somehow you find you can breathe, but now you’re stuck at the bottom of the ocean with a bunch of sad and angry people. They tell you the only way back to the city from here is to pull down some other poor soul who’s trying to swim across. If you can grab them, you’ll be let go.</p> <p>Eventually you manage to grab an ankle and get out of the ocean. But then you’re back to the city. Those people with medals are even more aggravating—how did they make it across? What’s so special about them? You can do this!</p> <p>You spend more time training, you even join a gym and find some like-minded people. You figure if enough of you swim together in a group, you can kick off the grabbing hands, avoid the jagged rocks, and make it to the island. You have a plan. It’s going to work.</p> <p>You all go down to the beach. You get in your formation and dive in. You feel the hands grabbing your ankles but your plan is working! Your team is swimming across and making headway.</p> <p>Halfway across people start getting tired. It turns out a few miles is pretty far to swim! You’re still kicking away those grabbing hands and that’s never getting easier. Plus you’re getting hungry.</p> <hr /> <p>Sometimes (right now), that’s what entrepreneurship is like. You’re fighting as hard as you can to get to that island and be a success. There are pitfalls—jagged rocks, people trying to drag you down—at every moment. The goal is in plain view (when waves don’t crash on you and obscure your vision), but it’s a long way across. The only motivators are your fellow swimmers and the knowledge that others have done it, and not all of them have big fancy boats to ferry them across.</p> <p>The rewards are real, the dangers are real, and the crossing is exhilarating.</p> <img src="" height="1" width="1" alt=""/> Testing Rails Memory Usage With Valgrind 2011-12-13T00:00:00-05:00 <p><strong>TL;DR</strong>: Ruby 1.9.2 leaks memory with rails apps, switch to 1.9.3.</p> <p>We’ve been having some trouble running out of memory on our production servers ever since we upgraded our app to Rails 3.1 and Ruby 1.9.2 (p290). Our unicorn processes will gradually use up all the memory on our (m1.large) servers (7.5Gb) over the course of 24 hours or so.</p> <p>Today one of our developers came across some topics (<a href="">1</a>, <a href="">2</a>) on StackOverflow, as well as a <a href="">post on HN</a> that mentioned it might be a bug in ruby 1.9.2. I wanted to investigate that claim empirically, so I needed to find a tool that could measure memory consumption.</p> <p>After a little googling, I was reminded of <a href="">Valgrind</a>, a suite of tools for testing applications. Valgrind has an excellent memory usage analyzer, <a href="">Memcheck</a>.</p> <p>I was having some trouble running it and honestly got a little frustrated, but <a href="">Evan Weaver’s blog post about testing ruby with valgrind</a> at least gave me hope it was possible. I eventually trolled through enough of the (excellent) <a href="">valgrind documentation</a> and found that if I ran valgrind with <code class="highlighter-rouge">--trace-children=yes</code> that I could get the full results from testing my rails app.</p> <h3 id="setup">Setup</h3> <p>I used version 3.7.0 of valgrind, which I built from source. Ubuntu also ships version 3.6.1, which should work the same. You can simply run <code class="highlighter-rouge">sudo apt-get install valgrind</code> to get it. Otherwise it’s easy to install from <a href="">source</a>.</p> <p>I’m using RVM to manage my rubies. Ruby supports valgrind internally as of 1.9 with the –with-valgrind configure option. It’s apparently on by default, but if you’re paranoid you can pass the additional configure flag with RVM by doing:</p> <figure class="highlight"><pre><code class="language-text" data-rvm install 1.9.2 -C --with-valgrind</code></pre></figure> <p>RVM’s <code class="highlighter-rouge">-C</code> option will pass subsequent options to the configure script.</p> <p>In order to more accurately test ruby, I wrote a test script to ensure my application was exercised moderately. It’s a simple script which just loads some data into memory:</p> <figure class="highlight"><pre><code class="language-ruby" data-<span class="no">Order</span><span class="p">.</span><span class="nf">all</span><span class="p">.</span><span class="nf">map</span><span class="p">{</span><span class="o">|</span><span class="n">o</span><span class="o">|</span> <span class="n">o</span><span class="p">.</span><span class="nf">customer</span> <span class="p">}</span></code></pre></figure> <p>To actually execute valgrind, I ran:</p> <figure class="highlight"><pre><code class="language-text" data-valgrind \ --log-file=valgrind_output.log \ --trace-children=yes \ bundle exec rails runner test.rb</code></pre></figure> <h3 id="testing">Testing</h3> <p>Valgrind outputs a <code class="highlighter-rouge">HEAP SUMMARY</code> and a <code class="highlighter-rouge">LEAK SUMMARY</code> at the end of program execution. These are what I’m focusing on to determine memory changes between 1.9.2 and 1.9.3.</p> <p>Here’s the raw output:</p> <p><strong>1.9.2-p290 Results:</strong></p> <figure class="highlight"><pre><code class="language-text" data-HEAP SUMMARY: in use at exit: 187,561,529 bytes in 3,197,878 blocks total heap usage: 19,991,955 allocs, 16,794,077 frees, 6,663,565,008 bytes allocated LEAK SUMMARY: definitely lost: 51,217,761 bytes in 543,305 blocks indirectly lost: 126,656,843 bytes in 2,508,233 blocks possibly lost: 3,542,851 bytes in 48,230 blocks still reachable: 6,144,074 bytes in 98,110 blocks suppressed: 0 bytes in 0 blocks Rerun with --leak-check=full to see details of leaked memory For counts of detected and suppressed errors, rerun with: -v ERROR SUMMARY: 1857 errors from 21 contexts (suppressed: 5 from 5)</code></pre></figure> <p><strong>1.9.3-p0 Results:</strong></p> <figure class="highlight"><pre><code class="language-text" data-HEAP SUMMARY: in use at exit: 5,373,469 bytes in 83,901 blocks total heap usage: 19,385,645 allocs, 19,301,744 frees, 6,601,997,814 bytes allocated LEAK SUMMARY: definitely lost: 6,536 bytes in 54 blocks indirectly lost: 5,899 bytes in 93 blocks possibly lost: 496 bytes in 3 blocks still reachable: 5,360,538 bytes in 83,751 blocks suppressed: 0 bytes in 0 blocks Rerun with --leak-check=full to see details of leaked memory For counts of detected and suppressed errors, rerun with: -v ERROR SUMMARY: 2053 errors from 17 contexts (suppressed: 4 from 4)</code></pre></figure> <h3 id="analysis">Analysis</h3> <p>As you can see, 1.9.2 leaked around 51M, whereas 1.9.3 leaked only 6.5k. In block terms, that’s a <strong>100,000x increase in leakage</strong>.</p> <p>The only thing that changed between these reports was the version of ruby. It seems there is definitely a memory leak running at least our rails 3.1 app on ruby 1.9.2. We’ll be upgrading to 1.9.3 as soon as possible.</p> <p>Additionally, our app eats about 6.6Gb of memory performing this simple test. I also ran a runner script with no ruby operations (just load the environment and quit) and the app still consumed 4.3Gb. We definitely need to look into what’s going on to load all that data. For reference, here’s the abbreviated output of <code class="highlighter-rouge">rake stats</code>:</p> <figure class="highlight"><pre><code class="language-text" data-+-------------+-------+-------+---------+---------+-----+-------+ | Name | Lines | LOC | Classes | Methods | M/C | LOC/M | +-------------+-------+-------+---------+---------+-----+-------+ | Controllers | 11079 | 9065 | 89 | 855 | 9 | 8 | | Helpers | 1089 | 937 | 2 | 102 | 51 | 7 | | Models | 22278 | 14202 | 170 | 1609 | 9 | 6 | | Libraries | 17941 | 13447 | 183 | 1274 | 6 | 8 | +-------------+-------+-------+---------+---------+-----+-------+</code></pre></figure> <img src="" height="1" width="1" alt=""/> Ruby DCamp Retrospective 2011-09-21T00:00:00-04:00 <p>I attended <a href="">Ruby DCamp</a> this year. It’s a programmers’ event where you camp out (in cabins). There’s a code retreat the first day and then subsequent days are an <a href="">open-spaces</a> event.</p> <h3 id="the-code-retreat">The Code Retreat</h3> <p>The code retreat involved programming <a href="">Conway’s Game of Life</a> over and over again. Each time you get 45 minutes to work on the problem. You and another (pseudo-randomly selected) person pair program and use <a href="">TDD</a>. At the end of the 45 minutes, you delete all the work you’ve done. The goal is not necessarily to create a program that runs the algorithm, but rather to hone your craft and focus on how you pair-program and how you effectively use TDD.</p> <p>I ended up involved in only three of the total (six or so) sessions. Each was a unique experience, and eye-opening. It made me remember why we, as a community, care so much about TDD and other agile practices: they really work.</p> <h3 id="the-open-spaces-sessions">The Open-Spaces Sessions</h3> <p>Saturday and Sunday were self-organized sessions. The topics ranged from specific (Programming with <a href="">Coffeescript</a> or using <a href="">DCI</a>) to broad (Effective pairing practices, Intro to statistics).</p> <p>Sunday had a number of hacking sessions where we worked on actually building something. These were especially rewarding: I continued with the Game of Life theme and built a version using <a href="">Backbone.js</a> and with <a href="">Erlang</a>.</p> <h3 id="new-concepts">New Concepts</h3> <p>The sessions around DCI, presenters, and fast-testing were probably the most influential to how I’m planning to work in the future. I’ve been moving towards the idea of breaking apart my thick models for awhile (some of the models we work with at Optoro are over a thousand lines long). These concepts give a strong conceptual framework to use while refactoring our models down to something actually maintainable.</p> <p>Thanks again to <a href="">@elight</a> and everyone who attended for making DCamp such a great event!</p> <img src="" height="1" width="1" alt=""/> Shut Up, HAProxy! 2011-03-10T00:00:00-05:00 <p>We use <a href="">HAProxy</a> to load-balance requests across multiple Rails backends. It works great, but man does it clutter up the logs. Every N seconds (2 in our case), HAProxy requests our root url (DashboardsController#index) to ensure the site is up. This results in lots of log entries like this:</p> <figure class="highlight"><pre><code class="language-text" data-Processing DashboardsController#index (for 10.0.0.205 at 2011-03-07 06:42:20) [GET] Parameters: {"action"=>"index", "controller"=>"dashboards"} Redirected to Filter chain halted as [:login_required] rendered_or_redirected. Completed in 1ms (DB: 0) | 302 Found []</code></pre></figure> <p>Every. Two. Seconds.</p> <p>This made it really hard to read the logs, let alone <code class="highlighter-rouge">cap tail</code>. I finally got fed up and created this initializer:</p> <figure class="highlight"><pre><code class="language-ruby" data-<span class="k">module</span> <span class="nn">ActionController</span> <span class="k">class</span> <span class="nc">Base</span> <span class="c1"># Yup, these are class methods. ActionController is interesting---there's a</span> <span class="c1"># class-level `process` and an instance-level one. They take different</span> <span class="c1"># sets of arguments, too. We want to interrupt this at the class level,</span> <span class="c1"># because that's where we have access to `logger` (via a cattr_accessor)</span> <span class="k">class</span> <span class="o"><<</span> <span class="nb">self</span> <span class="c1"># Keep the old process method around</span> <span class="k">alias</span> <span class="n">orig_process</span> <span class="n">process</span> <span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">response</span><span class="p">)</span> <span class="k">if</span> <span class="n">haproxy_request?</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="c1"># I've never had to use this method before. </span> <span class="c1"># It's a nice solution, too bad I have to </span> <span class="c1"># construct a Proc for it.</span> <span class="n">logger</span><span class="p">.</span><span class="nf">silence</span> <span class="k">do</span> <span class="n">orig_process</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">response</span><span class="p">)</span> <span class="k">end</span> <span class="k">else</span> <span class="n">orig_process</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">response</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">haproxy_request?</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="c1"># Unlike most people, HAProxy doesn't send a User-Agent.</span> <span class="n">request</span><span class="p">.</span><span class="nf">parameters</span><span class="p">[</span><span class="ss">:controller</span><span class="p">].</span><span class="nf">to_s</span> <span class="o">==</span> <span class="s1">'dashboards'</span> <span class="o">&&</span> <span class="n">request</span><span class="p">.</span><span class="nf">parameters</span><span class="p">[</span><span class="ss">:action</span><span class="p">]</span> <span class="o">==</span> <span class="s1">'index'</span> <span class="o">&&</span> <span class="n">request</span><span class="p">.</span><span class="nf">user_agent</span><span class="p">.</span><span class="nf">blank?</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span></code></pre></figure> <p>It works with Rails 2.3. I’m sure you can do it with Rails 3 somehow—in fact I’m betting it’s easier in Rails 3—but I’m working with what I’ve got.</p> <p>And now I can go back to reading the logs like a sane person.</p> <img src="" height="1" width="1" alt=""/> Net::HTTP Alternatives 2011-02-10T00:00:00-05:00 <p>Here at <a href="">Optoro</a> we’ve been building some external tools that interact with our website via http. For simplicity’s sake, we’ve been using <a href="">curl</a>.</p> <p>I was discussing this with some friends when someone recommended I check out <a href="">Curb</a>. I was already in the middle of transitioning to <a href="">HTTParty</a>, due to its improved syntax, but I figured I’d check them all out in a head-to-head HTTP deathmatch.</p> <p>I wrote this simple <a href="">Sinatra</a> app to hit for testing purposes:</p> <figure class="highlight"><pre><code class="language-ruby" data-<span class="nb">require</span> <span class="s1">'rubygems'</span> <span class="nb">require</span> <span class="s1">'sinatra'</span> <span class="n">get</span> <span class="s1">'/'</span> <span class="k">do</span> <span class="s2">"Hi"</span> <span class="k">end</span> <span class="n">post</span> <span class="s1">'/'</span> <span class="k">do</span> <span class="s2">"HiPost"</span> <span class="k">end</span></code></pre></figure> <p>And then a <a href="" title="Benchmark Code Gist">benchmark suite</a>:</p> <div class="shortCode"> <figure class="highlight"><pre><code class="language-ruby" data-<span class="nb">require</span> <span class="s1">'rubygems'</span> <span class="nb">require</span> <span class="s1">'httparty'</span> <span class="nb">require</span> <span class="s1">'curb'</span> <span class="nb">require</span> <span class="s1">'net/http'</span> <span class="nb">require</span> <span class="s1">'benchmark'</span> <span class="kp">include</span> <span class="no">Benchmark</span> <span class="no">RUNS</span> <span class="o">=</span> <span class="mi">1000</span> <span class="n">url</span> <span class="o">=</span> <span class="s1">''</span> <span class="nb">puts</span> <span class="s2">"Measuring GETs"<="c1"># NOTE: This works slightly faster without URI.parse, but I'm trying to make this a little more real-world.</span> <span class="no">Net</span><span class="o">::</span><span class="no">HTTP</span><span class="p">.</span><span class="nf">get</span> <span class="no">URI</span><span class="p">.</span><span class="nf">parse</span><span class="p">(</span><span class="n">url</span><span class="p">)<">get</span><span class="p">(</span><span class="n">url<="no">RUNS</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="no">Curl</span><span class="o">::</span><span class="no">Easy</span><span class="p">.</span><span class="nf">perform</span><span class="p">(</span><span class="n">url</span><span class="p">)</span> <span class="k">end</span> <span class="k">end</span> <span class="c1"># NOTE: This situation might not be typical, but it is a lot faster.<">perform</span> <span class="k">end</span> <span class="k">end</span> <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"curl"</span><span class="p">)</span> <span class="k">do</span> <span class="no">RUNS</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="sb">`curl "</span><span class="si">#{</span><span class="n">url</span><span class="si">}</span><span class="sb">" 2>/dev/null`</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span> <span class="n">params</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'q'</span> <span class="o">=></span> <span class="s1">'test'</span><span class="p">}</span> <span class="nb">puts</span> <span class="s2">"Measuring POSTs"<="no">Net</span><span class="o">::</span><span class="no">HTTP</span><span class="p">.</span><span class="nf">post_form</span> <span class="no">URI</span><span class="p">.</span><span class="nf">parse</span><span class="p">(</span><span class="n">url</span><span class="p">),</span> <span class="n">params<">post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="ss">:body</span> <span class="o">=></span> <span class="n">params<="no">Curl</span><span class="o">::</span><span class="no">Easy</span><span class="p">.</span><span class="nf">http_post</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">curb_params</span><span class="p">)</span> <span class="k">end</span> <span class="k">end<">http_post</span> <span class="n">curb_params</span> <span class="k">end</span> <span class="k">end</span> <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"curl"</span><span class="p">)</span> <span class="k">do</span> <span class="n">"-F </span><span class="se">\"</span><span class="si">#{</span><span class="n">k</span><span class="si">}</span><span class="s2">=</span><span class="si">#{</span><span class="n">v</span><span class="si">}</span><span class="se">\"</span><span class="s2">"</span> <span class="p">}.</span><span class="nf">join</span><span class="p">(</span><span class="s2">" "</span><span class="p">)</span> <span class="no">RUNS</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="sb">`curl -X POST -s </span><span class="si">#{</span><span class="n">curl_params</span><span class="si">}</span><span class="sb"> "</span><span class="si">#{</span><span class="n">url</span><span class="si">}</span><span class="sb">" 2>/dev/null`</span> <span class="k">end</span> <span class="k">end</span> <span class="k">end</span></code></pre></figure> </div> <p>Here are the results:</p> <div class="highlight"><code><pre> $ ruby test_http_clients.rb Measuring GETs user system total real Net::HTTP 0.520000 0.200000 0.720000 ( 1.334052) HTTParty 0.670000 0.250000 0.920000 ( 1.616191) Curb 0.330000 0.200000 0.530000 ( 1.477893) Curb-reuse 0.110000 0.040000 0.150000 ( 0.830893) curl 0.060000 0.980000 1.040000 ( 8.760388) Measuring POSTs user system total real Net::HTTP 0.730000 0.180000 0.910000 ( 1.577040) HTTParty 0.780000 0.240000 1.020000 ( 1.677723) Curb 0.370000 0.150000 0.520000 ( 1.425708) Curb-reuse 0.160000 0.030000 0.190000 ( 0.849151) curl 0.110000 1.130000 1.240000 (1202.826407) </pre></code></div> <p>Clearly, libcurl-based <a href="">Curb</a> is the fastest alternative. It’s not all that much faster than (pure-ruby) <a href="">HTTParty</a>, though, so I think the improved syntax of <a href="">HTTParty</a> will keep me on that. What’s truly interesting though is how slow shelling-out to curl is. Even though the ‘total’ time is negligibly more, the ‘real’ time it takes to open that subprocesses and execute <a href="">curl</a> is far longer, 8.7 seconds total for plain GETs, and a whopping 1202 seconds for POSTs.</p> <img src="" height="1" width="1" alt=""/>
https://feeds.feedburner.com/loki/DqPy
CC-MAIN-2021-21
refinedweb
20,512
62.98
How Do Multimethods Work? There are a number of tricky challenges to getting multimethods working. They are: How Are Return Types Determined? Different specialized methods should be able to return different types. That way, for example, a + method on numbers can return a number, while a + specialized to strings can return strings. Dynamically, that's easy. But the static checker needs to be able to determine this too. This is actually fairly straightforward to solve. During type-checking, we'll statically determine the set of methods that could match, based on the known static types of the arguments. The return type of the method from the type-checker's perspective is then the union of those types. For example: def double(n Int -> Int) n * 2 def double(s String -> String) s ~ s var foo = double(123) Here, the type-checker can determine that foo is an Int because the only method whose type is a subtype of the type of 123 is the Int one. A slightly more complex example: Omitting Covered Methods To be as accurate as possible, it would be ideal if it was smart enough to not include the return type of methods that can be statically determined to be completely covered by another one: def add(left Int, right Int -> Int) left + right def add(left Object, right Object -> String) left ~ right def foo = add(1, 2) Here, it should know that foo is an Int because even though both methods could match, the first one covers the second. How Are the Methods Ordered? Since methods can be defined pretty much anywhere in Magpie it's hard to figure out which order the specialized methods should be tested. CLOS handles this by prefering the most specialized methods first, but "most specialized" probably isn't well-defined in Magpie with interfaces. One radical option is to just ditch interfaces and go with a more CLOS-like multiple inheritance of classes approach. I'm not crazy about the whole mixins/delegates system anyway, so that might be an improvement. How Do We Ensure At Least One Pattern Will Match? One of the basic and most useful features of the static checker is catching errors like: def foo(i Int) ... foo("not int") In the presence of multimethods testing that gets a little funkier. I think this case will actually be easy. All we do is the same logic to statically determine which cases could match. If the set is empty, then we report an error. That should cover cases like the above. How Do Abstract Methods Work? One really nice feature of OOP languages is the ability to define abstract methods in base classes. The type-checker can then ensure that all derived classes implement that method. Magpie accomplishes something similar with interfaces. If you try to pass a concrete type where an interface is expected, it will statically verify that the type satisfies the interface. We definitely do not want to lose the ability to say "Any type used in this context requires this capability." There's two components to this. First, we need to be able to define abstract methods in base classes. Then the type checker must ensure that for all derived classes, there are specialized methods that completely cover that one. Determining total cover in multimethods may be a bit tricky, but I hope it's resolvable. (That feature is also needed to ignore the return type of completely covered methods.) With that, we can generate static errors when a derived class doesn't implement all of the abstract methods it inherits. The second piece is ensuring that classes that have abstract methods can't be constructed and passed around. Ensuring that Derived implements Base's abstract methods isn't very helpful if you could actually end up with an instance of just Base that you're trying to dispatch on. Not sure how to handle that yet. The solution may just be, "don't do that" and generate an error at runtime on a failed match. How Do Interfaces Work? A very common use case in Magpie and other OOP languages is to define a function that takes an argument of any type that implements a certain interface. In other words, any object that has certain capabilities. Basing this on interfaces instead of base classes dodges the brittle base class problem. Magpie's current interface system makes it even more flexible since existing classes can retroactively implement new interfaces. How does this translate to multimethods? For example: def ~(left Stringable, right Stringable) String concat(left string, right string) end The goal here is that this method can be called on any arguments that have a string getter, and that it should be a static error to try calling with an argument that doesn't. Without interfaces, what is the type signature of that function? One option would be the C++ solution. An "interface" becomes just a class with no state and some abstract methods. Classes that implement that interface would have to explicitly inherit from it. Then, the existing support for making sure abstract methods are covered would cover this too. It would look something like: class Stringable end def abstract string(arg Stringable -> String) Int extends(Stringable) def string(arg Int -> String) ... How Do Constructors Work? CLOS doesn't really place much emphasis on constructors. When you define a class, you instantiate it by calling: (make-instance 'my-class :slot1 "blah" :slot2 "boof") So basically you specify the class and all of the slot values, much like construct() in Magpie. We can take that and make it nicer by having a class define a new method that specializes the new generic function with the class being constructed, and a record of its fields. That would get us to what CLOS supports. If you want to define your own ctor, just create a different new method that specializes on the class and a different set of arguments, like so: class Point var x Int var y Int end // The above gives us: Point new(x: 1, y: 2) // i.e. new(Point, (x: 1, y: 2)) // If we want a different ctor, just do: def class method Point new() new(0, 0) Point new() // i.e. new(Point, ()) How Do Chained Constructors Work? The above handles classes with no inheritance (or at least no base classes that in turn require construction). What about ones that do? The CLOS answer is to just union the fields together. If Base has field a and Derived has b, to instantiate a derived, you'd do this: Derived new(a: "a", b: "b") This is because CLOS doesn't emphasize encapsulating state, but I'm really not crazy about that, especially when it comes to private fields. A class should own its internal state and should be able to use its constructor as the interface for that. One option would be to chain constructors like this: class Base1 var a end class Base2 var d end class Derived : Base1, Base2 var f end // By default, this defines: Derived new(Base1: (a: 123), Base2: (d: 234), f: 345 -> Derived) // If we want to use different ctors for base: def class method Base1 new(b Int, c Int -> Base1) new(b + c) def class method Base2 new(e String -> Base2) new(Int parse(e)) // Now we can do: Derived new(Base1: (100, 23), Base2: "234", f: 345) This is a little fishy though because constructors create objects instead of initializing them. So when we call the constructors for Base1 and Base2, we'll create two objects and then, I guess, have to copy those fields over to the "real" one. That feels kind of gross. Ignoring that for now, though, the semantics for built-in new would be: obj = new empty object obj.class = the class for each property in arg record if property name is a base class name invoke new with the base class and the property's value get the resulting object and copy its fields to obj else if property name is a field on the class initialize the field with the property value end end Initialize Instead of Construct Now that I think about it, we may be able to resolve the fishiness by making new just initialize this instead of returning a new one. In the above examples, all of the new methods return their class type, and the ultimate built-in new does too. Instead of that, we could replace new with init. That doesn't return anything. Instead, the expectation is that any init method will eventually bottom out on the built-in one. The built-in init, like new, takes a record of field values and base class values. Now there is a single built-in new method. Its semantics are: create an empty object, _newObj call init(), passing in the argument passed to new() return _newObj The built-in init() does: for each property in arg record if property name is a base class name invoke init() with the base class and the property's value else if property name is a field on the class initialize the field on _newObj with the property value end end Problem solved, I think. This also cleans things up a bit. It always felt tedious to have explicitly declare the return type of new() to be the created class. What About Factories? What intended nice feature of the existing new() semantics is that a constructor doesn't have to always create and return a new object. It can return a cached one or a subclass or pretty much anything. That's a nice feature to maintain. I think we can support this with the above idea too. All you would need to do is specialize new() with a different argument type and you'll hit that method instead. If you want to swap out the "real" new() with one that takes the same argument type, well... we'll have to see if it's possible to replace a method.
http://magpie.stuffwithstuff.com/design-questions/how-do-multimethods-work.html
CC-MAIN-2017-30
refinedweb
1,678
69.82
Ruby on Rails Developer Series: Spinning Up a JSON API in Minutes Stay connected Welcome to the first of four Ruby on Rails Developer Series. In this series, the goal is to outline how to strengthen your API with Postgres, how to dockerize your project and add security layers to mitigate attacks to your application. In this article, we'll cycle through building a quick API-only application uses the JSON API from Active Model Serializer. Then construct a basic CRUD Controller API example on retrieving the User information. While the process is outlined and best practices are used. The goal of the series is to make you feel confident as an engineer in building a structured project with Ruby on Rails. Let's Begin Let's start off by using the --api command in the console to provision an api only preset. rails new rails-json-api-test --api This will generate the following: app/controllers app/assets app/helpers app/models config Objective CRUD Our goal is to use the ActiveModel::Serializer - JSON API - which is included by default in your Gemfile when you create an application using the --api directive. We will then work toward spinning up a basic CRUD endpoint for a user. Below is the endpoint we plan to implement and http methods we plan to send to the API. Path: /api/v1/users GET POST PUT DELETE Next, we need to generate the basic User Model that we want to create using the rails generate command for Models: First, we need to set up our database. In this example, we will be using PG (Postgres) and will set up the minimum requirement to allow us to proceed to build our API and come back to this in the next article. gem pg Then we need to set up our database.yml file Then we're ready to create the database and build our table. rake db:create rails g model User first_name:string last_name:string email:string That should generate something like this: invoke active_record create db/migrate/20190521020122_create_users.rb create app/models/user.rb invoke test_unit create test/models/user_test.rb create test/fixtures/users.yml Now let's work on the serializer side of things of how the API will respond to the request. We will want to uncheck this in the gemfile: gem 'active_model_serializers', '~> 0.10.0' When we make the controller we will need the namespaces to be setup: For the namespace to change from Api::V1::UsersController to API::V1:UsersController we need to modify the inflection file which was generated in config/initializers/inflections.rb. We will then need to uncomment and add this to the file: ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym 'API' end Lock down your routes to ONLY ALLOW these method requests. Rails.application.routes.draw do namespace :api, path: '' do namespace :v1 do resources :users, only: [:index, :show, :create, :update, :destroy] end end end This is what our controller looks like to be able to support our methods: class API::V1::UsersController < ApplicationController rescue_from ActiveRecord::RecordNotFound, with: :record_not_found def index users = User.all render json: users, each_serializer: UserSerializer, adapter: :json_api, status: 200 end def show user = User.find(params[:id]) render json: user, serializer: UserSerializer, adapter: :json_api, status: 200 end def create user = User.new(user_params) render json: user, serializer: UserSerializer, adapter: :json_api, status: 200 if user.save! end def update user = User.find(params[:id]) render json: user, serializer: UserSerializer, adapter: :json_api, status: 200 if user.update(user_params) end def destroy user = User.find(params[:id]) render json: user, serializer: UserSerializer, adapter: :json_api, status: 200 if user.destroy! end private def record_not_found render json: { message: 'Record Not Found!'}, adapter: :json_api, status: 404 end end Responding with JSON JSON API is a format that works to optimize http(s) requests mainly to promote more productivity and efficiency. JSON API comes with strong caching functionality as data changes affect fewer resources. You can simply add this to the Serializer to implement basic key-based cache expiration: cache key: 'user', expires_in: 3.hours Conclusion We have just spun up a JSON API in a few minutes for our User Table. We have left some items for the next part of the series to strengthen our API-based application. In the next article, we will further work on building a strong JSON API and using Postgres to your advantage. This project is available on my repo here Additional resources Learn how to tame the Jenkins JSON API with Depth and "Tree." How do JSON and XML compare? Find out here. Discover what JSON Schema is and what role it plays. Stay up to date We'll never share your email address and you can opt out at any time, we promise.
https://www.cloudbees.com/blog/ror-developer-series-spinning-up-a-json-api-in-minutes/
CC-MAIN-2021-17
refinedweb
796
54.83
I am trying to acheive parallal thread execution. for example t1, t2, and t3 are three threads , each performing a task to print multiplication table. I want to execute them in a sequence -------------------------------- | t1 | t2 | t3 | -------------------------------- | 2 | 3 | 4 | | 4 | 6 | 8 | | 6 | 9 | 12 | | .. | .. | .. | |------------------------------| import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SynchronizationExample1 { public static void main(String[] args) { ExecutorService es = Executors.newFixedThreadPool(3); for(int i=1; i<=10; i++){ es.execute(new Task(i)); } es.shutdown(); while(!es.isTerminated()){ } System.out.println("finished all task"); } } public class Task implements Runnable { private int i; public Task(int i){ this.i = i; } @Override public void run() { System.out.println(Thread.currentThread().getName()+ "Start counter = " + i); processMessage(); System.out.println(Thread.currentThread().getName()+ "End counter"); } public void processMessage(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } pool-1-thread-1Start counter = 1 pool-1-thread-3Start counter = 3 pool-1-thread-2Start counter = 2 pool-1-thread-1End counter pool-1-thread-1Start counter = 4 pool-1-thread-3End counter pool-1-thread-3Start counter = 5 pool-1-thread-2End counter pool-1-thread-2Start counter = 6 pool-1-thread-1End counter pool-1-thread-1Start counter = 7 pool-1-thread-3End counter pool-1-thread-3Start counter = 8 pool-1-thread-2End counter pool-1-thread-2Start counter = 9 pool-1-thread-1End counter pool-1-thread-1Start counter = 10 pool-1-thread-3End counter pool-1-thread-2End counter pool-1-thread-1End counter finished all task I am trying to acheive parallal thread execution. for example t1, t2, and t3 are three threads , each performing a task to print multiplication table. I want to execute them in a sequence. That is a contradiction in terms. You can do things in parallel or in sequence, but you cannot do both at the same time. (It is like running and riding a bicycle at the same time!) As @Thilo states, the simple, practical (and best) solution is not to do this with multiple threads. Just use one thread and a for loop. If you are intent on doing this using multiple threads, then you need the threads to synchronize. (That is what appears to be the problem with your current code. You have no synchronization ... just three "free running" threads and sleep() calls. That approach is never going to be reliable.) For instance, until you get to the end. (You will need to do something special then ...) This notification could take the form of 3 separate "channels" (primitive mutexes, latches, semaphores, queues, whatever) for each three pairs of threads, or a single "channel" where each thread wait for its turn. (There are other ways to solve this too ... but we don't need to go into that here.)
https://codedump.io/share/vApk7tPzxTPT/1/how-to-make-multiple-threads-run-parallally-such-that-execution-of-threads-takes-place-one-after-the-other
CC-MAIN-2017-26
refinedweb
464
59.09
.tax.decl.parser;20 21 import java.io.*;22 23 import org.netbeans.tax.decl.*;24 25 /** Utility parser parsing multiplisity marks. */26 public class MultiplicityParser {27 28 /** Parse model content.29 * @param model string without starting delimiter.30 */31 public String parseMultiplicity (ParserReader model) {32 33 int ch = model.peek ();34 switch (ch) {35 case '?': case '+': case '*':36 37 try {38 model.read (); //use peeked character39 } catch (IOException ex) {40 ex.printStackTrace ();41 }42 43 return new String ( new char[] {(char) ch});44 45 default:46 return ""; // NOI18N47 }48 }49 50 }51 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/netbeans/tax/decl/parser/MultiplicityParser.java.htm
CC-MAIN-2018-26
refinedweb
108
62.95
So I'm designing a sort of my_numeric_cast template<typename To, typename From> constexpr To my_numeric_cast(From); template<> constexpr float my_numeric_cast<float, int>(int i) { return i; } You cannot write a template function specialization for which no template argument makes the body valid in C++. The result if you do so is an ill formed program with no diagnostic required. This includes the primary specialization. So most of the answers here are simply undefined behaviour. They may work, but they are not valid C++. They may work today, but after a library upgrade a compiler upgrade or a different build target they could fail in completely different and surprising ways. Relying on UB with no strong reason is a bad idea. On the plus side, we can do away with template specialization and fix your problem in one fell swoop: template<class T>struct tag_t{}; // may need `constexpr tag_t(){}` on some compilers template<class T>constexpr tag_t<T> tag{}; template<class T, class F> constexpr T my_numeric_cast(F, tag_t<F>)=delete; // generates compile time error constexpr float my_numeric_cast(int i, tag_t<float>) { return i; } // not a template! Could be if you want it to be. template<typename To, typename From> constexpr To my_numeric_cast(From f){ return my_numeric_cast(f, tag<To>); } and done. =delete generates friendly messages. Program is well formed. Implementing casts is no longer a specialization. You can even implement it in the namespace of a type being cast to or from as ADL is enabled. If you solve a problem with template function specialization, reconsider. They are fragile, do not work like class template specialization or function overloading (while looking like both of them!), and usually are not the best solution to anything. There are exceptions when it may be a good idea, but they are quite rare, and given how rare they are avoiding the quirky feature may still be worth it.
https://codedump.io/share/nroBdKwBcSER/1/sfinae-to-make-base-template-always-result-in-error
CC-MAIN-2018-17
refinedweb
315
54.83
I need help with an assignment I am working on. Here is the assignment: count all the even numbers between X and Y, where X and Y are entered by the user. Do not include X and Y. EXAMPLE 1: Please enter an integer: 0 Please enter another integer: 10 The number of even numbers between 0 and 10 is 4 EXAMPLE 2: Please enter an integer: 10 Please enter another integer: 0 The number of even numbers between 10 and 0 is 4 Note that the numbers can be entered in any order (that is, the lower one does not have to come first). I have it just about finished but it is not working properly. Each time I run it, I don't get 4, it keeps changing. I know it's gotta be something small that I am missing, but could you help me. Here is what I have: #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; int main() { int min, max, number = 0; unsigned seed = (unsigned long) (time(NULL)); srand(seed); cout << "Please enter an integer: "; cin >> min; cin.ignore(); cout << "Please enter another integer: "; cin >> max; int range = max - min + 1; for (int counter = 0; counter <= number; counter++) { int number = rand()/100%range + min; cout << "The number of even numbers between " << min << " and " << max << " is " << number; break; } cout << endl; } What is wrong with this program that the number printed keeps changing?
https://www.daniweb.com/programming/software-development/threads/116519/pseudo-random-numbers-printing-the-number-of-even-numbers-between-0-and-10
CC-MAIN-2017-17
refinedweb
239
70.67
Up to [cvs.NetBSD.org] / src / external / mit / expat / dist / amiga Request diff between arbitrary revisions Default branch: expat, MAIN Current tag: MAIN Revision 1.1.1.1 / (download) - annotate - [select for diffs] (vendor branch), Fri Apr 6 10:23:27 2012 UTC (13 months, 1 week ago) by spz Branch: expat,, expat-2-1-0, agc-symver-base, agc-symver, HEAD Branch point for: yamt-pagecache Changes since 1.1: +0 -0 lines Diff to previous 1.1 (colored) import of expat 2.1.0 Fixes CVE-2012-1147, CVE-2012-1148 and CVE-2012-0876 (other security issues have been previously fixed in our tree) relevant Changes:.1 / (download) - annotate - [select for diffs], Fri Apr 6 10:23:27 2012 UTC (13 months, 1 week ago) by spz Branch point for: MAIN Initial revision This form allows you to request diff's between any two revisions of a file. You may select a symbolic revision name using the selection box or you may type in a numeric name using the type-in text box.
http://cvsweb.netbsd.org/bsdweb.cgi/src/external/mit/expat/dist/amiga/expat_68k.h?only_with_tag=MAIN
CC-MAIN-2013-20
refinedweb
176
61.26
. > >Where's the bug here? And by whose standards is it a bug? >(I should check the FSSTND before I ask that question, to see if > it reserves /bin, /usr/bin, and so forth for the distribution > provider, but my copy is at home. I don't think it does) I was under the impression that /usr/local was the right place - as opposed to /bin and /usr/bin - for software not supplied by the distributor in virtually every variant of Unix under the sun. We don't expect to support people who try to encroach on the C library's namespace - if you redefine printf you get what you deserve. The FSSTND says, among other things: Locally installed software should be placed within /usr/local rather than /usr unless it is being installed to replace or upgrade software in /usr. In the case of Debian, if part of some package is worth upgrading or replacing then there should be a .deb file to do it; so there is no call for local administrators to install things outside /usr/local (from a FSSTND POV). ttfn/rjk
https://lists.debian.org/debian-devel/1995/08/msg00162.html
CC-MAIN-2018-05
refinedweb
186
66.07
The very first alpha version of Vue 3 is released! There are a lot of exciting features coming with version 3: Vue exposes its reactivity system behind the new Composition API. If you haven't heard about it, I recommend reading the RFC describing it. At first, I was a bit skeptical, but looking at React's Hooks API, which is a bit similar, I decided to give it a shot. In this article, we will be building a movie search application using the Composition API. We won't be using object-based components. I will explain how the new API works and how can we structure the application. When we finish, we will see something similar to this: The application will be able to search for movies via the Open Movie Database API and render the results. The reason for building this application is that it is simple enough not to distract the focus from learning the new API but complex enough to show it works. If you are not interested in the explanations, you can head straight to the source code and the final application. Setting up the project For this tutorial, we will be using the Vue CLI, which can quickly generate the necessary environment. npm install -g @vue/cli vue create movie-search-vue cd movie-search-vue npm run serve Our application is now running on and looks like this: Here you can see the default folder structure: If you don't want to install all the dependencies on your local computer, you can also start the project on Codesandbox. Codesandbox has perfect starter projects for the most significant frameworks, including Vue. Enabling the new API The generated source code uses Vue 2 with the old API. To use the new API with Vue 2, we have to install the composition plugin. npm install @vue/composition-api After installing, we have to add it as a plugin: import Vue from 'vue'; import VueCompositionApi from '@vue/composition-api'; Vue.use(VueCompositionApi); The composition plugin is additive: you can still create and use components the old way and start using the Composition API for new ones. We will have four components: - App.vue: The parent component. It will handle the API calls and communicate with other components. - Header.vue: A basic component that receives and displays the page title - Movie.vue: It renders each movie. The movie object is passed as a property. - Search.vue: It contains a form with the input element and the search button. It gives the search term to the app component when you submit the form. Creating components Let's write our first component, the header: <template> <header class="App-header"> <h2>{{ title }}</h2> </header> </template> <script> export default { name: 'Header', props: ['title'], setup() {} } </script> Component props are declared the same way. You name the variables that you expect from the parent component as an array or object. These variables will be available in the template( {{ title }}) and in the setup method. The new thing here is the setup method. It runs after the initial props resolution. The setup method can return an object and the properties of that object will be merged onto the template context: it means they will be available in the template. This returned object is also the place for placing the lifecycle callbacks. We will see examples for this in the Search component. Let's take a look at the Search component: <template> <form class="search"> <input type="text" : <input @ </form> </template> <script> import { ref } from '@vue/composition-api'; export default { name: 'Search', props: ['search'], setup({ search }, { emit }) { const movieTitle = ref(search); return { movieTitle, handleSubmit(event) { event.preventDefault(); emit('search', movieTitle.value); }, handleChange(event) { movieTitle.value = event.target.value } } } }; </script> The Search component tracks keystrokes and stores the input's value on a variable. When we are finished and push the submit button, it emits the current search term up to the parent component. The setup method has two parameters. The first argument is the resolved props as a named object. You can use object destructuring to access its properties. The parameter is reactive, which means the setup function will run again when the input properties change. The second argument is the context object. Here you can find a selective list of properties that were available on this in the 2.x API ( attrs, slots, parent, root, emit). The next new element here is the ref function. The ref function exposes Vue's reactivity system. When invoked, it creates a reactive mutable variable that has a single property value. The value property will have the value of the argument passed to the ref function. It is a reactive wrapper around the original value. Inside the template we won't need to reference the value property, Vue will unwrap it for us. If we pass in an object, it will be deeply reactive. Reactive means when we modify the object's value (in our case the value property), Vue will know that the value has changed, and it needs to re-render connected templates and re-run watched functions. It acts similar to the object properties returned from the data method. data: function() { return { movieTitle: 'Joker' }; } Gluing it together The next step is to introduce the parent component for the Header and Search component, the App component. It listens for the search event coming from the Search component, runs the API when the search term changes, and passes down the found movies to a list of Movie components. <template> <div class="App"> <Header : <Search : <p class="App-intro">Sharing a few of our favourite movies</p> <div class="movies"> <Movie v- </div> </div> </template> <script> import { reactive, watch } from '@vue/composition-api'; import Header from './Header.vue'; import Search from './Search.vue'; import Movie from './Movie.vue'; const API_KEY = 'a5549d08'; export default { name: 'app', components: { Header, Search, Movie }, setup() { const state = reactive({ search: 'Joker', loading: true, movies: [], errorMessage: null }); watch(() => { const MOVIE_API_URL = `{state.search}&apikey=${API_KEY}`; fetch(MOVIE_API_URL) .then(response => response.json()) .then(jsonResponse => { state.movies = jsonResponse.Search; state.loading = false; }); }); return { state, handleSearch(searchTerm) { state.loading = true; state.search = searchTerm; } }; } } </script> We introduce here two new elements: reactive and watch. The reactive function is the equivalent of Vue 2's Vue.observable(). It makes the passed object deeply reactive: takes the original object and wraps it with a proxy (ES2015 Proxy-based implementation). On the objects returned from reactive we can directly access properties instead of values returned from the ref function where we need to use the value property. If you want to search for equivalents in the Vue 2.x API, the data method would be the exact match. One shortcoming of the reactive object is that we can not spread it into the returned object from the setup method. The watch function expects a function. It tracks reactive variables inside, as the component does it for the template. When we modify a reactive variable used inside the passed function, the given function runs again. In our example, whenever the search term changes, it fetches the movies matching the search term. One component is left, the one displaying each movie record: <template> <div class="movie"> <h2>{{ movie.Title }}</h2> <div> <img width="200" : </div> <p>{{ movie.Year }}</p> </div> </template> <script> import { computed } from '@vue/composition-api'; export default { name: "Movie", props: ['movie'], setup({ movie }) { const altText = computed(() => `The movie titled: ${movie.Title}`); return { altText }; } }; </script> The Movie component receives the movie to be displayed and prints its name along with its image. The exciting part is that for the alt field of the image we use a computed text based on its title. The computed function gets a getter function and wraps the returned variable into a reactive one. The returned variable has the same interface as the one returned from the ref function. The difference is that it's readonly. The getter function will run again when one of the reactive variables inside the getter function change. If the computed function returned a non-wrapped primitive value, the template wouldn't be able to track dependency changes. Cleaning up components At this moment, we have a lot of business logic inside the App component. It does two things: handle the API calls and its child components. The aim is to have one responsibility per object: the App component should only manage the components and shouldn't bother with API calls. To accomplish this, we have to extract the API call. import { reactive, watch } from '@vue/composition-api'; const API_KEY = 'a5549d08'; export const useMovieApi = () => { const state = reactive({ search: 'Joker', loading: true, movies: [] }); watch(() => { const MOVIE_API_URL = `{state.search}&apikey=${API_KEY}`; fetch(MOVIE_API_URL) .then(response => response.json()) .then(jsonResponse => { state.movies = jsonResponse.Search; state.loading = false; }); }); return state; }; Now the App component shrinks only to handle the view related actions: import Header from './Header.vue'; import Search from './Search.vue'; import Movie from './Movie.vue'; import { useMovieApi } from '../hooks/movie-api'; export default { name: 'app', components: { Header, Search, Movie }, setup() { const state = useMovieApi(); return { state, handleSearch(searchTerm) { state.loading = true; state.search = searchTerm; } }; } } And that's it; we finished implementing a little application with the new Composition API. Wrapping it up We have come a long way since generating the project with Vue CLI. Let's wrap it up what we learned. We can use the new Composition API with the current stable Vue 2 version. To accomplish this, we have to use the @vue/composition-api plugin. The API is extensible: we can create new components with the new API along with old ones, and the existing ones will continue to work as before. Vue 3 will introduce many different functions: setup: resides on the component and will orchestrate the logic for the component, runs after initial propsresolution, receives propsand context as an argument ref: returns a reactive variable, triggers re-render of the template on change, we can manipulate its value through the valueproperty. reactive: returns a reactive object (proxy-based), triggers re-render of the template on reactive variable change, we can modify its value without the valueproperty computed: returns a reactive variable based on the getter function argument, tracks reactive variable changes and re-evaluates on change watch: handles side-effects based on the provided function, tracks reactive variable changes and re-runs on change I hope this example has made you familiar with the new API and removed your skepticism as it did with me. Discussion The function is called as an event handler and the searchTermcomes from the data passed to emit. I have tried out the application on Codesandbox and it is working. Am I missing something? You're right. I misread the definition. awesome composition api of vue, and you can also try concent composition api for react! here is an online example: stackblitz.com/edit/concent-regist... more details see github.com/concentjs/concent hope you like it, concent is a predictable、zero-cost-use、progressive、high performance's enhanced state management solution for react _^ Interesting solution, definitely an eye-catcher thx _, concent is born for react, and power react from inside to outside. 1 predictable: concent take over react.setState, and dispatch feature is base on setState, so every state changing behavior is predictable, no matter use setState or dispatch see demo below: stackblitz.com/edit/cc-zero-cost-use 2 zero-cost-use: cause setState can be interactive with store, so you can use concent by register api on your classical react class writing without changing any code. see demo below: stackblitz.com/edit/cc-course-hell... 3 progressive you can separate your business logic code to reducer from class later. it will keep your view clean. see demo below: stackblitz.com/edit/cc-multi-ways-... 4 high performance with watchedKeys, renderKey, lazyDispatch, delayBroadcast features, concent render every view block only when it really need to been re-rendered see watchedKeys demo: stackblitz.com/edit/concent-watche... see renderKey demo: stackblitz.com/edit/concent-todoli... 5, enhance react computed, watch, effect, setup and etc... both of them are designed for react honestly see demo below: stackblitz.com/edit/hook-setup because concent is quick new, so very less people know it, hope u can try it and give me feedback. by the way: my en is not good, wish u understand what I said_^ Thank you for writing and explaining things. Now we're tracking the change with handleChange()function. As we use to do in React. What about v-modelapproach here? Can we use it with composition API? Correct me if I am wrong I'm a bit late to the party - as I just started using the composition API myself - but it's definitely possible to use v-model, as before. Just remember to set the variable you wish to assign to v-modelin the setup()function, using a ref(). As in const newMovieName = ref('');and use v-model="newMovieName". If destructured, won't be reactivity of propsparameter lost? I think it can be the case as soon as your props get updated. Similar to the case where you destructure the a reactiveobject instead of using toRefs? Normally. as far as I understand the whole concept, you must wrap with toRefsa value, which you want to spread or destructure in order to retain its reactivity. And in case of props, which you pass as parameter to setup()you can't use destructuring inside function signature, e.g setup({name}), because as soon as the nameprop will be updated, you end up with its old value due to lost of reactivity. Destructuring is supported only for properties of context, so I suppose this should work: setup(props, {attrs, emit}). There are many movies app like netflix, Hulu, but there are many other apps like bobby, Coto I would also like to create an app like that, it's very helpful Vue Composition API to create such app's. I try and submit feedback here. Wow! Bet interesting app. Will definitely try it myself. Thanks for sharing. Don't you want to put your api key in a .env instead of ... this ? It is a piece of good advice, will move it to an environment variable. May it need this app Hotstar Awesome man! Nice work! Awesome demo. Thanks for sharing!
https://dev.to/blacksonic/build-a-movie-search-app-using-the-vue-composition-api-5218
CC-MAIN-2020-50
refinedweb
2,388
56.25
Post your Comment prepare statement prepare statement sir i want example of prepare statement Nested If Statement Nested If Statement In this section you will study about the Nested-if Statement in jsp.... Here we are providing you an example using Nested-If statement. In the example, we The Switch statement with the next case after executing the first statement. Here is an example.... To avoid this we can use Switch statements in Java. The switch statement is used... of a variable or expression. The switch statement in Java is the best way to test Use if statement with LOOP statement with Example The Tutorial illustrate a example from if statement with LOOP statement. In this example we create a procedure display that accept... Use if statement with LOOP statement   Switch Statement switches to statement by testing the value. import java.io.BufferedReader; import... Enter the number 3 Tuesday Description: - In this example, we are using switch case statement. The program displays the name of the days according to user SQL And Statement with Example The Tutorial illustrates an example from SQL AND Statement... SQL AND Statement The SQL AND operator is used to show you the filter records JDBC Prepared Statement Example JDBC Prepared Statement Example Prepared Statement is different from Statement object... Prepared Statement Example. The code include a class JDBC JSP If statement Example JSP If statement Example In this section with the help of example you will learn about the "If" statement in JSP. Control statement is used... a simple JSP program. Example : This example will help you to understand how to use if else statement in java if else statement in java if else statement in java explain with example jdbc-prepare statement jdbc-prepare statement explain about prepared statement with example if else statement in java if else statement in java explain about simple if else statement and complex if else statement in java with an example Switch Statement example in Java Switch Statement example in Java   ... for implementing the switch statement. Here, you will learn how to use the switch statement... also provides you an example with complete java source code for understanding update statement in mysql update statement in mysql i am looking for mysql update statement example. Thanks Prepared statement JDBC MYSQL Prepared statement JDBC MYSQL How to create a prepared statement in JDBC using MYSQL? Actually, I am looking for an example of prepared statement. Selecting records using prepared statement in JDBC GOTO Statement in java GOTO Statement in java I have tried many time to use java goto statement but it never works i search from youtube google but e the example on net are also give compile error. if possible please give me some code with example Continue and break statement is an example of break and continue statement. Example - public class ContinueBreak... is an example of break and continue statement. Example - public class ContinueBreak... statement in java program? The continue statement restart the current Prepared Statement Example the PreaparedStatement. In this example we will execute a SQL statement using PreparedStatement object. In this example we will use "INSERT INTO" SQL statement... is used to make the SQL statement execution efficient. In Java, when we use JDBC Update Statement Example .style1 { text-align: center; } JDBC Update Statement Example JDBC update statement is used to update the records of a table using java application program. The Statement object returns an int value that indicates how many UPDATE Statement The UPDATE Statement The UPDATE statement is used to modify the data in the database table through a specified criteria. In the given syntax of update statement the keyword SET JDBC Batch Process With Prepare Statement Example JDBC Batch Process With Prepare Statement Example: In this example, you can learn about jdbc batch process with prepare statement. First of all, we... will create a prepare statement object as: PreparedStatement stmt = null Use HANDLER Statement in Cursors The Tutorial illustrate an example from 'Use HANDLER Statement... Use HANDLER Statement in Cursors Use HANDLER Statement in Cursor is used to define C Goto Statement C Goto Statement This section explains you the concept of 'goto' statement in C. The goto statement is a jump statement which jumps from one point to another point mysql select statement - SQL statement code. Implement the following code. import java.sql.*; public class...); Statement st = con.createStatement(); ResultSet rs... for more information with example Thanks JDBC Batch Example With SQL Select Statement JDBC Batch Example With SQL Select Statement: In this example, we are discuss about SQL select statement with JDBC batch process. We will create SQL select statement and execute it in a result set and after that fetch SQL SELECT DISTINCT Statement statement to show all unique records from database. In this example... SQL SELECT DISTINCT Statement In this example we will show you the usage of Distinct If statement in java 7 If statement in java 7 This tutorial describes the if statement in java 7. This is one kind of decision making statement. There are various way to use if statement with else - If Statement : If statement contains one boolean Use DEFAULT Statement in Procedure Use DEFAULT Statement in Procedure The Tutorial illustrate an example 'Use DEFAULT Statement in Procedure'. To understand 'Default Statement in Procedure', we create for statement for statement for(int i=0;i<5;i++); { system.out.println("The value of i is :"+i); } if i end for statement what will be the output got the answer.. it displays only the last iteration that is "The value of i Post your Comment
http://www.roseindia.net/discussion/48946-JSP-If-statement-Example.html
CC-MAIN-2015-18
refinedweb
932
53.92
[REPOST: I've already posted this three days ago, but I haven't seen it on the list, nor I've seen any reply, so I suppose it's vanished somewhere. I apologize to those who get it twice] On 8 Jan, Guy Maor wrote: > Fabrizio Polacco <fpolacco@icenet.fi> writes: > >> I recently managed to add some sources in my -dbg shared lib packages, >> to make them easily debuggable. (See bug#16038 on 30 Dec) > > I rather liked your solution to the problem of debuggable shared libs, > but you need to figure out a way to not need to be root to build > it. (maybe you already did?) I did. You don't need any more to be in group "src" or to change mode to /usr/src (being root wasn't required to build, although obviously worked :-) You should read my last post to bug#16038 (what's the url?) for a long explanation of what I've done. Anyway I applied my ideas both to libdb2 and liblockdev0g; the latter is a pristine debian source of only 20k, so I think it is simpler to examine. The idea behind all this is to have a -dbg package that permits debugging (of the library, not of your program) just out of the box, without any need for unpacking, patching sources, etc. It is quite annoying, when debugging a program, to have to skip library's routines without having the possibility to inspect the code and the data. This method permits to add one or more libraries to your debug simply installing the relative -dbg packages, which I suggest to keep on your machine in .deb format, as those libs are usually highly compressable. To debug: 1) install the -dbg package. 2) become the owner of the executable on which you want to run gdb, 3) preload the debug location with LD_LIBRARY_PATH=/usr/lib/debug gdb <executable> Note that only step one must be repeated for each of the libraries you want to debug, while the other two are relative to the debug session. Step 2 can be a problem when debugging setuid programs; in case the program is owned by a non-login user, become root and issue su user -c "LD_LIBRARY_PATH=/usr/lib/debug gdb <executable>" Anyway, with this method you can run gdb also on "preinstalled" executables, when you want to debug the library itself (no need to compile an ad-hoc program just to have the relative objects loaded). To build the -dbg lib: 1) provide the needed sources for listing in gdb. 2) put in the symbol table of the lib the exact location of the sources. 3) build unstripped shared libs compiled with -DDEBUG. 4) name the lib with the "soname" used in the runtime lib. 5) install the lib in a location NOT known by ld.so 6) DON'T run ldconfig with that location The following description seems to be more appropriate for debian-mentors that debian-policy. I put it here just to avoid future endless discussion on "how this could be ever done?" :-) 1) provide the needed sources for listing in gdb. the correct place is IMHO /usr/src/<package><version> (whatever else?) I do this in the debian/rules makefile with the following command: # ==== sources ==== ${install_sources} <NOTE> to avoid involution of code in the debian/rules file, I use the "define" ability of make; I also put all these defines in a separated file (that I copy in all my packages) that goes included in the debian/rules file. </NOTE> define install_sources for src in `strings -a ${d_ulib}/debug/* | grep '$(abs_src)' | sort -u` ; \ do for fullname in $${src} ; \ do fulldir=`dirname $${fullname}` ; \ ${install_dir} ${d_build}$${fulldir} ; \ localname=`echo $${fullname} | sed 's,^${abs_src}/,,'` ; \ ls $${localname} 2>/dev/null \ && ${install_data} $${localname} ${d_build}$${fullname} ; \ done; done; endef this_dir=${shell pwd} abs_src = /usr/src/$(shell basename ${this_dir}) d_build = ${absolute_d_build} d_ulib = ${d_build}/usr/lib install_dir = install -p -o root -g root -m 755 -d install_data = install -p -o root -g root -m 644 2) put in the symbol table of the lib the exact location of the sources. This step is the most difficult to accomplish, as the debianized source can be located everywhere (by policy). The first solution was to provide a symlink to the absolute location where the sources _will_ be installed, and compile adding that path to the sources names. See bug#16038 to see why this wasn't a good idea :-) Now I used a different solution, which may have different problems on different packages (and different makefiles). The makefiles I built for those two libs use implicit rules (I like simplicity :-), so I used the overwriting method to do something different when compiling for the -dbg package (sources should be recompiled ad-hoc for -dbg using -DDEBUG, which should be not set when compiling for runtime lib) ifdef create_debug_lib _SRCDIR_: ln -sf . $@ # overwriting implicit rule %.o: %.c _SRCDIR_ @echo "=== overwritten rule .o:.c ($@: $^) ===" ${COMPILE.c} -S _SRCDIR_/$< -o $*.ss sed 's,^.stabs \"_SRCDIR_\/,.stabs \"${abs_src}/,' $*.ss > $*.s ${COMPILE.s} -o $@ $*.s ${RM} $*.ss $*.s endif # create_debug_lib This fragment have to be included in the makefile. In the rules file, when compiling the -dbg package, issue ${MAKE} shared CFLAGS="-g3 -O2 -fPIC -DDEBUG" create_debug_lib=1 where the setting of the var "create_debug_lib" has the effect to overwrite the implicit rule, getting the change of the pathname in the symbol table. This provides step two. The problem is that most of the upstream author have "strange" ideas on how a makefile should be done, and probably you have to change it to get what you want. In that cases I find more simple for me (and for a reader also) to create a new makefile from scratch. I did so for libdb2, after having wasted hours to modify the upstream one :-) The new makefile uses the old one to build a list of objects, and let the implicit rules do all the rest; it fills only one screen. It's my opinion that the _only_ skill that we should require in a Debian Developer is GNU Make knowledge. That's all. comments wellcome.]
https://lists.debian.org/debian-policy/1998/01/msg00027.html
CC-MAIN-2016-44
refinedweb
1,021
56.08
). Embrace, Extend, Extinguish (Score:2, Insightful) JavaScript programs are TypeScript programs. 'Nuff said. and it isn't good for C# developers who now have confirmation that Ander Hejlsberg is looking elsewhere for his future. It's C++ all the way down! Re: (Score:2) How exactly do you "extinguish" something that's free, open source and cross-platform from the get go? (yes, TypeScript is all three) Re: (Score:3) That still doesn't make any sense. There's no implementation to install here - TypeScript compiler outputs portable, standards-compliant JavaScript code that runs the same on any browser (and also Node.js etc). Re: (Score:3, Insightful) Um, the Apache License is significantly more free than the GPL. Just sayin'. Re: (Score:2) For varying perspectives on what constitutes "free." Re: (Score:2) nearly sane. What are google's two js replacements? (Score:5, Interesting) Dart, obviously. But what is the other one? Anyone know what the article writer was talking about? Re: (Score:3, Informative) Clojure: [clojure.org] Don't think it's formally Google anymore. Re: (Score:2) Clojure is pretty cool, and it compiles to the JVM code, but I have never heard about it being a replacement for JavaScript. In which sense would it replace JavaScript? Re: (Score:2) Id say GWT if i had to guess. Many options, all wrong (Score:3) Probably one of Go, Closure, Java (via GWT), or C (via NaCl), though I suppose one might see Python and (again) Java (this time, via AppEngine) as "replacements" for server-side JavaScript in the form of Node.js, though that's even a bigger stretch than the others. Dart is the only one that is actually an effort in the direction of a general JavaScript replacement, though. Re: (Score:2) I don't think that qualifies as a language, but maybe that's what the author meant. Re: (Score:2) Go is meant as a system language. I don't think complexity has anything to do with it. But maybe the author meant C, in the form of Google NaCl (Native Client). Re: (Score:2) Yeah, that's probably it. Always forget about salt. Re: (Score:3) CoffeeScript isn't a google creation. As another poster pointed out, its probably NaCl. I am still busy with silverlight (Score:5, Funny) Sorry.. I am still busy with silverlight... Oooppss. that did not work.... Re: (Score:3, Funny) In related news, I just released a game in HyperCard. CoffeeScript, Dart and this - screw it all (Score:5, Insightful) Fix JavaScript or give us something like Python minus the dangerous bits in the browser. Re:CoffeeScript, Dart and this - screw it all (Score:4, Interesting) Obligatory: [xkcd.com] Note: please do not mod this post up. Yes, it is completely relevant, and funny, but I can't take credit for it. :p (On the other hand, I request it not get modded down just because you don't like xkcd, either. Relatedly, why the frell don't you?) Re: (Score:2) You know you could always post as an AC Re: (Score:2) No, I just totally forgot about it. I never post AC, mostly because I forget about it every time there's a reason I might want to, which is rarely enough that I am going to keep forgetting about it. :p Re:CoffeeScript, Dart and this - screw it all (Score:5, Funny) Yeah, well, you sound like a... person who... isn't very good at comebacks. Also, your mom. Re: (Score:3) You could definitely benefit from attending Simile School [youtube.com]. Do you have a karma allergy? (Score:5, Funny) Obligatory: [xkcd.com] Note: please do not mod this post up. Note: please do mod this post up Re: (Score:3, Insightful) It makes me cry whenever I hear JavaScript being used as an 'assembler'. CPU performance, memory usage, and power consumption be damned! Re: (Score:3) "looking for transpiler: php to javascript" - [stackoverflow.com] And it would appear someone is working on a PHP to JS compiler. [harmony-framework.com] Re:CoffeeScript, Dart and this - screw it all (Score:4, Informative) Re:CoffeeScript, Dart and this - screw it all (Score:4, Insightful) Fix JavaScript or give us something like Python minus the dangerous bits in the browser. Full Python is a relatively heavy language (compared to, say, Lua), and I would be less than thrilled if all browsers had to implement a Python interpreter in addition to the Javascript interpreter they would still require for compatibility. Besides, Python is all dangerous bits. I think a lightweight virtual machine would be a natural successor. If they had done it in the 90s it would be a considerably worse legacy than Javascript was, but I think we're ready for it now. Some desirable properties would be: (LLVM bytecode is NOT suitable for this; it is first and foremost a compiler IR, and is not intended for cross-platform use.) Re: (Score:2) Re: (Score:2) Something like Python? I thought you wanted something better? Re: (Score:2) "This is not a solution. It's a mess." Indeed. These companies are not creating JavaScript replacements because they just want it their way, there are real issues with using JavaScript for large developments. Why are we still waiting for basic features like optional static typing and classes to be added to JavaScript? Static typing is a very important feature. From it flows not just basic type checking, but also autocompletion (a major productivity booster), ease of re-factoring and useful code analysis (what functions use this particular type The problem is not with Javascript (Score:5, Interesting) Javascript works well for what it was intended to do: adding dynamic functionality to webpages. It only has problems when it's used for something it was not intended to do like building web-based applications or the Flash-like animations of HTML5. These are very different use cases, and I don't think one language to cover them all is a good idea. Developing new languages for the new web technologies is the way to go. Re: (Score:2) Re: (Score:2) Re: (Score:3) It's cool to hate javascript. Hence, all the sheep repeating the meme -- hence the lack of specifics. In reality, js is fairly painless to use and, once you know what to avoid, you can use it to write some nice clean and maintainable code. Here's the weird part. While it's cool to hate javascript it's also cool to love jQuery. Weird, as all it does is make your code less efficient, less readable, and more difficult to maintain. (Abuse of jQuery abounds -- I've seen it included to do astonishingly simpl Re: (Score:2) Re: (Score:2) Re:CoffeeScript, Dart and this - screw it all (Score:4, Informative) Well, gaming consoles run JavaScript (in their browsers, or at least the Xbox will at some point), and most of them (PS3 being the exception) don't run Java. Smartphones run Javascript, while even Android doesn't really run Java (there are a few niche platforms that do, though). Every single PC has at least one, and probably quite a few, javascript engines (Windows ships with at least two: the one in IE and Windows Script Host). Neither Windows nor OS X ships with Java anymore. Aside from Windows-NT-based ones (again, Android doesn't count), I don't know of a single tablet that can run Java. They all support Javascript, though. Many dumbphones can run (a subset of) Java, but these days many of them can run Javascript too. Nearly all of the larget Personal Media Players of recent years can run Javascript; I don't know of any that run Java. In absolute numbers, I don't know what the balance is. However, in terms of the way that customers interact with their devices, Javascript is a lot more widely used than Java. Re: (Score:2) Re: (Score:2) I think TypeScript should be forked and renamed to Douche# to better fit in Microsoft's pantheon of languages. They made their Java clone, now they have their Dart clone and they're written by the same guy! I like the not so subtle FUD... (Score:2, Informative). Lol, how cute. You're trying to create FUD. Re: (Score:3) I do think CoffeeScript is pretty compelling, though I'm not sure how much I like it... a lot of what's in TypeScript is based on efforts with EcmaScript in the past/future, so it lines up a little better. I think there's room for CoffeeScript, Haxe and TypeScript. TS will probably get a bit more tra Aside from Microsoft's history.... (Score:5, Interesting) Re:Aside from Microsoft's history.... (Score:4, Informative) Exactly, it's basically a preprocessor for javascript that allows your IDE to help you write better code. Re: (Score:2) 0 day exploit found in TypeScript (Score:5, Funny) I'm going to leave this here as a placeholder for the inevitable... Oh FFS (Score:2) We already have, what, a couple *hundred* languages to choose from at this point? [wikipedia.org] Can we knock it off with the new effing languages already? Don't these people have anything more useful to do? Re: (Score:2) We already have, what, a couple *hundred* languages to choose from at this point? Almost as many as we have Linux distros! Re: (Score:2) Yeah people! Stop thinking about new ways of doing things! Get in line with the One True Way! Article title misleading. (Score:2, Informative) It doesn't replace anything. Its simply a higher level language that compiles to cross-compatible JS. And its open standard to boot. Not seeing any negatives about it. JS is a mess and MS is attempting to clean it up. I'd rather use Script# (Score:2) to compile my C# algorithms to Javascript. See [scriptsharp.com]. It's by a Microsoft guy so hopefully it gets official support some day. all these languages what am I to do? (Score:2, Insightful) Sticking with C. How many computer languages do we need? Really? It's bad enough that you don't trust javascript from webpages, now i have a new type not to trust? Microsoft, i don't trust you, never have. fuck typescript, fuck Windows 8, and well, fuck you. Re:all these languages what am I to do? (Score:4, Informative) c? to write client-side code run by the browser? are you high? Re: (Score:3) Sticking with C. And now you don't have to be left out of the web page revolution... Check out [github.com] which is a LLVM backend for javascript. They have ported a big portion of the standard C libraries, STL, and a number of other things. Its pretty funny, but you can run boat loads of old emulators, games, you name it in a browser now. I find this useful, ignore the FUD! (Score:2) As a cocoa programmer tasked with implementing yet another embedded htmlfucking5 project thanks to Adobe Edge, I wish Javascript would die. After looking at the myriad of patterns for my current project - a Javascript client REST API - I came to the swift conclusion that most of them are silly, namespace polluting, self initializing mindfucks. I gave up looking at patterns, found a preloader (lab.js - although require.js is looking good) and wrote my own module pattern objects to satisfy the clarity, structu Playground seems borked (Score:2) Re: (Score:2) Obviously by design. I call for web byte-code (Score:5, Interesting) So can we finally have a specification that is not bound to a specific implementation? Why in all what is good and holy, do we need the limitation of JavaScript? Just make a byte-language specification, just like the CLR or Java Byte-Code for the DOM stuff. Then everyone are free to use Python, Ruby, Java or what else as a language, the browser needs only to interpret the Byte-Code that the language-compiler is producing (just like with Java and javac, where you can use any language you like to produce the Java byte-code). If you are really worried about open source, then answer me this: What is the difference between this [jquery.com] and byte-code? There is none, because both are not human-readable. So why not just to agree to a byte-code that interfaces the DOM and html5 and then we can use any language we like to generate the byte-code? Wouldn't it be nice to fire up your favorite IDE or editor and just write Python or Ruby (or insert here your favorite language) for your web-page? But no, we just have to use JavaScript until the end of the universe. PS: most browsers are compiling JavaScript to a byte-language anyway nowadays, because then they can optimize the byte-code so JS will run faster. Re: (Score:3) The problem with adding any new language is that it requires support from all browsers to be at all useful. I don't think that's necessarily true. Think about a near-future world in which Chrome -- and only Chrome -- has a Dart VM, and suppose that Google's dream of Dart bytecodes being an order of magnitude faster to download and running an order of magnitude faster is realized. Google will then invest in writing all of their web apps in Dart, using the generated Javascript code in browsers that don't support Dart but running Dart bytecodes wherever possible. End result: Google's web apps are an order of mag Re: (Score:2, Insightful) Bullshit. Look at other languages that compile to JavaScript that also don't pollute the standard: The summary is just wrong. JavaScript isn't being replaced. It's being enhanced in an entirely compatible and most importanly voluntary way. Re: (Score:3) Re:DEFINITELY No!!! (Score:5, Insightful) The probem isn't so much with C# the language/toolset. The problem is that in order for Microsoft to sell you new tools and tech it has to periodically change them just enough so you feel enough pain to shell out for new stuff. The other problem is that while C# is good for development it is clear that it is no longer an object of adoration in Microsoft's strategy. C# will always be around but it won't get the resources that the 'new hotness' team gets (eg. TypeScript). Meanwhile, those that use other tools (standard C++, Java etc) will keep plodding along, continuously evolving. If you know Aesop's Tortoise versus the Hare fable then this is what is happening now. Those who always watch the speed of the hare miss the fact that a new hare is entered into the race every few years. Meanwhile, those not distracted by the hare are watching the tortoise and see how it is less flashy but progresses continuously. If you built your tech on the tortoise you still have good solutions. If you build your tech with the hare then every few years you either have to rebuild your tech for the new hare (expensive! this is what CTOs worry about and code-monkeys don't), drop your existing investment and start building again for the new hare (expensive and wasteful), or stay with old tech (painful, and now surpassed by the tortoise). Re: (Score:2) Re: (Score:2) Look at the incompatibilities introduced by their past technologies: C# (copycat from Java) and simply calling it C# You might as well whinge that Java is an incompatible copycat of Delphi, C# was never meant to be compatible with Java in any way, or do you not have any understanding of what C# is? The lack of cross-platform is the killer for C# (yes there is Mono but it's never up to the same version as the MS CLR). Web Form (.NET 2.0) What are you suggesting it was supposed to be compatible with? Active Directory (vs LDAP). Again, Active Directory and LDAP were never meant to be compatible. If you want to jump on the anti-microsoft bandwagon at least try and write a po Re: (Score:2) I'm positive that when Microsoft hired Anders they uttered a sentence like "We want to clone Java so it only runs on Windows." And then .Net was born. Re:Remember the old addage (Score:5, Insightful) Rubbish. Not a good view of the technology. You might want to watch the channel 9 video and see how the language works before sounding the war horns. Essentially it's an overlay on javascript code that allows the developer to infer useful information about their code. The output from the "compiler" is bog standard javascript, no microsoft extensions at all. So if the "carpet" ever got pulled out from under you, all you would do is go back to editing the standard .js directly. Re: (Score:3) Re:Remember the old addage (Score:4, Insightful) I think you are missing the point. While it is good the output is 'bog standard' Javascript what really matters is that the source is not 'bog standard Javascript'. Once you start writing in TypeScript you are forever bound to Microsoft. Now there may be compatible implementations but you may get a situation like C# where Microsoft's implementation is not only the foremost, but also the only complete one. They did a similar trick in years past with C++, where they had so many extensions that you pretty much needed for Windows development that once you started down their C++ path, forever would it dominate your project's destiny. These days their compiler will accept 'bog standard' C++, however to get real stuff done you still have to start using Windows constructs and interfaces (due to Microsoft producing APIs that look like like 'plain vanilla' C++; as many other APIs try to do). As others have pointed out, "All the roads lead to Microsoft, but none lead out". Now Microsofties could complain that the open source proponents are whining unfairly about this and it is resticting their, "Freedom to innovate". To that I say simply this, "How about you instead spend the effort on making your browser work like everyone else's?". The amount of workarounds and hacks required to compensate for the borked and agonizingly slow way that Internet Explorer handles (what should be) cross-platform Javascript is 'criminal'. The wastage in businesses and the entire IT industry caused by handling Internet Explorer's brokenness should make them blush. Sure, innovate and make the Javascript experience the best on Microsoft tools and platforms, but don't do it by creating more 'islands' than you have already. As others have pointed out, TypeScript may be tech flavor-du-jour for Microsoft at the moment (since they're trying to push their mobile solutions), but just like all their other tech it will have a limited shelf-life. You are better choosing truly cross-platform and long lasting tech for building solutions on. Historical examples: C#.NET (still used widely but not getting the Microsoft focus it once did), Visual Basic, COM/DCOM, OLE, C/C++ Win32 etc etc Yes you can still develop with these, but once upon-a-time they were the shizzle promoted by Microsoft and now people have to spend their time maintaining them with old and outdated tools. Meanwhile solutions developed with Standard C/C++, Java, etc get better tools and there are code changes required to maintain them are far more minor. Bet your solution on the long-lived tech stacks (and increase your long-term profits!). Re:Remember the old addage (Score:5, Informative) Once you start writing in TypeScript you are forever bound to Microsoft. I see you're unfamiliar with the concept of open source: git clone [codeplex.com] Re:Remember the old addage (Score:4, Insightful) He means in the 'dictating policy and direction' way. But that wouldn't make sense because the beauty of open source is that if you don't like the direction that the project steward is taking it in you can just fork it, simple. Re:Remember the old addage (Score:4, Insightful) He means in the 'dictating policy and direction' way. People here forget the concept of Opportunity Cost. Everything costs you some resource: Time, money, brain nurons, carbohydrate energy in your blood, at least something. I use a simple text editor because I don't want to learn Emacs. I don't decry the tyranny of Emacs, of the evilness that is Stallman locking me into a particular set of key sequences. Oh my deity! Stallman is dictating policy and direction for my text editor!! I just say "I don't want to spend my energy there". Everything pushes you to a direction. Microsoft does. JavaScript does. ECMAscript does. C does. C++ does. Scheme does. If you're worried that the direction Microsoft pushes you leads to a bad path, fine. But don't kid yourself that by choosing something else that you're no longer being pushed. Re: (Score:3) And how about patents? Would you bet against me if I said that Microsoft had a bunch of patents pending related to TypeScript? They released it under the Apache 2.0 license so patents aren't an issue, moreover typescript just emits javascript so the end result that is actually used is just plain javascript anyway. Re: (Score:2) I suck at editing: s/due to Microsoft producing APIs that look like like 'plain vanilla' C++/due to Microsoft producing not APIs that look like like 'plain vanilla' C++/ Re:Remember the old addage (Score:4, Insightful) While it is good the output is 'bog standard' Javascript what really matters is that the source is not 'bog standard Javascript'. Most of it is actually bog standard ES6 (for example, classes). The only proprietary bit here are type annotations. Which you can ignore altogether if you want, and then you just get a free, open-source implementation of a convenient subset of ES6 that spits out ES5. Anyway, this is open source (Apache license), and the implementation is itself written in TS, and runs on Node.js. In other words, it is in no way locked into any existing Microsoft technologies, completely self-sufficient, and you can fork and mod it to your heart's content, on any platform. There is no way to "extinguish" it for Microsoft from this point on, nor control you should you choose to use it, now or in the future. Re: (Score:3) You cannot ignore the annotations if the majority of libraries you are attempting to use are 'tainted' with them. Sure you can. You just run the TS compiler on them, get JS output, and stick to that. It's quite intentionally outputting well-formatted JS that very closely mimicks the original code - to the point where language spec itself defines how exactly transformation happens. Right now it's not comment-preserving, but they intend to change that, too. This all will work much better once they start targeting ES6 directly, rather than ES5. Also note that annotations are purely compile time hints (for warnings, IDE too Re: (Score:3) The type annotations/inferences are features that would have been in ES3, had it not been tanked by committee. Re: (Score:3) Re:Remember the old addage (Score:4, Informative) Re: (Score:3) If you're going to criticize something, at least get your facts straight. The C# yield keyword has nothing to do with Thread.yield(), it's for easier implementation of lazy iterators. And there is a very good reason why it is a feature of the language: it actually changes how the method behaves at a fairly deep level. Upon hitting the yield keyword, execution leaves the method and returns there only when another item from the iterator is requested. That's why it can't be just a library. Re: (Score:2) Frankly, If Microsoft can Extinguish the JavaScipt Name I'm all for it. I'm sick of explaining to everyone on earth that Javascript is NOT Java when I tell them they should get rid of the Virus targeted Java Runtime they do not need or updated in three years, but have on their machine just waiting for the next drive by virus to say hello. Re: (Score:3) Just keep calling it "ECMA Script" until it sticks. Good luck. Re:Remember the old addage (Score:5, Funny) Just keep calling it "ECMA Script" until it sticks. For some reason, "ECMA" always makes me think of "ACNE". Now it will for you, too ;-) You're welcome. Re:Remember the old addage (Score:5, Insightful) Embrace, Extend, Extinguish. Microsoft freely admits it, and when everyone jumps on the TypeScript bandwagon, the carpet will be pulled out from under you. How is this shit modded 'Insightful'? Karma whoring at its best, capitalizing on the nerd rage of geeks frothing at the mouth whenever Microsoft does anything. The fact is it is under an Apache 2.0 license, the spec is available and there are already 5 forks, so unless you have a fundamental misunderstanding of what EEE means you're just trolling. Re: (Score:3) Re: (Score:2, Insightful) Exactly this. Another attempt by microsoft to comandeer a standard and lock people in as they manipulate it to be incompatible. Re:Remember the old addage (Score:5, Insightful) Is it just me or are the MS shills getting even more stupid? When Apache 2.0-licensed, publicly available (on Git), already forked code is somehow getting you "locked in" and "manipulated to be incompatible" i think it's safe to say the stupidity lies with all the anti MS morons with their senseless EEE rhetoric. Although given you think pointing out that this is about as open as it can get which makes it the exact opposite of "locking people in" is being a "shill" you're probably not much different. Re: (Score:3) Rather, it seems MS is trying desperately to become more relevant and trustworthy in the open source space. So much so that they will toss their hat in the ring any chance they get. Javascript seems like a good opportunity, if you're looking at it from their perspective. Re:Remember the old addage (Score:4, Insightful) research.microsoft.com has been advancing lots of open source functional languages that use type inference and no one has been getting burned. The research group lets them do cutting edge research and then another research group builds an implementation for more mainstream languages and then it gets pulled in by product management. So I'd say in the open source language arena the public has learned the opposite. I'll agree it is different with products as opposed to technologies. Re: (Score:2) if prototypical inheritance is so great, why does almost everyone write a class-like wrapper around it to make it useful? Re: (Score:2) if prototypical inheritance is so great, why does almost everyone write a class-like wrapper around it to make it useful? Probably because they haven't read this. [crockford.com] Re: (Score:2) ugh, Crockford considered harmful. 1) it's not compatible with ES5. 2) it doesn't handle overridden methods/constructor 3) you can't efficiently & cleanly get private/protected members 4) it misses the point, just because you can do all these clever things with prototypes doesn't mean that you should. exposing the mechanics of all this stuff to the programmer is a disaster - it results in reams of confused questions on stackoverflow, and tools that need to solve the halting problem. Re: (Score:2) Or they read the first three paragraphs and go "I don't get it and I want to use OO like those C++ guys" and deliberately choose to ignore probably the most useful aspect of JavaScript. Re: (Score:2) it may be the 'probably the most useful aspect', but it's still a leak of the implementation details of a half-baked feature. how many of 'those C++ guys' are raving about how cool it is to mainpulate **this in your constructor? none. why not? because it's foolish and the language already provides rich abstractions for many of the sensible things you could do there, and more importantly prevents you from doing most of the idiotic things. same reason most of the 'compile-to-javascript' languages, as3, JIT eng Re: (Score:3) Re: (Score:2) i fail to see how any of that has anything to do with or is limited to prototype chains, except maybe performance where it can only hurt. function programming techniques don't require prototype-based inheritance. event driven callbacks, async, neither. Re:Full classes? (Score:4, Informative) Doesn't JavaScript have a better system altogether? Prototypical inheritance? Classes feel awful in comparison. These classes are just syntactic sugar, and are fully defined in terms of prototypes and constructor functions. The exact translation is detailed in the language spec, but it's easier to just go here [typescriptlang.org] and see how exactly it maps TS code to JS code, live, as you type it. Here's a simple example with inheritance translates as follows: As you can see, it's all fairly idiomatic JS. Furthermore: And doesn't the next revision have support for classes? I keep forgetting the name of it, H s... oh Harmony? I'm sure Harmony has a lot of things planned to extend the language massively to bring it up to standards even comparable to other languages. Indeed it does, and TypeScript classes are directly borrowed from there. Furthermore, the team has said that they will keep tracking ES6 (since it's still a draft), and amending TS accordingly so that their class syntax and semantics remain in sync. Re: (Score:3, Informative) v8 (and other optimized JavaScript implementations) have decent performance despite JavaScript the language. Re:Full classes? (Score:4, Informative) I know a little bit about compilers. "Every number is a float" is one of them in JavaScript. "All objects are associative arrays" is another. "Object prototypes are mutable everywhere" is yet another. Some, yes, but many also come from tracing the flow of data as the program runs to figure out which pessimizations inherent to the semantics of JavaScript it's safe to undo. That's why modern JavaScript JITs work so hard to perform side exits with their guard clauses to produce code that runs in as straight a line as possible. Ask Jim Blandy about it sometime. Perl would have to do similar optimizations. So would Python. So would Ruby. (It's instructive to talk to the people behind Rubinius and Unladen Swallow, if not people who've spent years optimizing Smalltalk implementations.) VS2012 as Node.js dev choice... (Score:2) Re: (Score:3) Beyond that, this is a lot different. This is a set of declarative extensions to JS that lean towards the next version of the standard and act as a pre-processor straight to JS proper. Not o
https://developers.slashdot.org/story/12/10/01/2011201/typescript-microsofts-replacement-for-javascript
CC-MAIN-2017-30
refinedweb
5,220
72.05
Codewind 0.8.0 Thursday 23 January 2020 ✨ New Features and Highlights for 0.8.0 ✨ Appsody - The codewind-appsody-extensionsupports passing environment options to the Appsody CLI using --docker-options. Che - The codewind-che-pluginsupports Helm 3, and the insecure non-default tiller was removed. IDEs (Both Eclipse and VS Code) VS Code - Push registry is no longer required unless a Codewind-style template source is enabled. - If you switch push registries, a warning appears that your namespace will be lost. - You can cancel image registry creation during the namespacestep, and you can use the Esckey to cancel the whole process. - You can navigate the remote connection settings page with keyboard shortcuts. List of Fixes - Updated Node.js Express server generator to 4.2.2 in Eclipse and VS Code - Updated Appsody CLI to v0.5.4 for the codewind-appsopdy-extension - Image Registry Manager push registry buttons are now toggles. - In Codewind 0.7.0, an incorrect network error appeared when attempting to connect to an uninstalled or failed remote Codewind instance: Authentication service unavailable. However, this network error is actually a connection error. This inaccuracy is corrected. - The remote settings page in VS Code is more responsive when the window is resized. - VS Code no longer stores the remote connection in extension data. VS Code now recognizes remote connections created in the Eclipse IDE.
https://www.eclipse.org/codewind/news08.html
CC-MAIN-2020-24
refinedweb
227
51.34
Hi I recently purchased the book "RealPython" and I've been scripting some apps on my own in Idle. Right now my intention is to start developing web apps. To acheive this I am going to use web2py framework but I have a hard time understanding how things work. For example, here is an app I made in Idle: which runs under "question("x")" def question(x): x = raw_input("What do you want? ") z = raw_input("Why do you want it? ") z = z.replace("my", "your") z = z.replace("I", "you") print "So you want", x, z print " " a = raw_input("and why do you want that? ") a = a.replace("because I want", "") print " " print "so you want",a print " " b = raw_input("And why do you want that? ") print " " print b, "- that's what's purposeful to you "" Now this is all fine.. but I can't just simply copy and paste this into web2py or load it as a module or something because it doesn't contain text fields on the screen or even a location where the output text will be shown and I have absolutely no idea how to do that or how to wrap my head around that. Any help would be greatly appreciated
http://forums.devshed.com/python-programming/940680-help-understanding-python-web-last-post.html
CC-MAIN-2018-13
refinedweb
206
79.5
Handle Thomson Reuters Web of Science™ export files Project description wosfile wosfile is a Python package designed to read and handle data exported from Thomson Reuters Web of Science™. It supports both tab-delimited files and so-called ‘plain text’ files. The point of wosfile is to read export files from WoS and give you a simple data structure—essentially a dict—that can be further analyzed with tools available in standard Python or with third-party packages. If you're looking for a ‘one-size-fits-all’ solution, this is probably not it. Pros: - It has no requirements beyond Python 3.6+ and the standard library. - Completely iterator-based, so useful for working with large datasets. At no point should we ever have more than one single record in memory. - Simple API: usually one needs just one function wosfile.records_from(). Cons: - Pure Python, so might be slow. - At the moment, wosfile does little more than reading WoS files and generating Record objects for each record. While it does some niceties like parsing address fields, it does not have any analysis functionality. Examples These examples use a dataset exported from Web of Science in multiple separate files(the maximum number of exported records per file is 500). Subject categories in our data import glob import wosfile from collections import Counter subject_cats = Counter() # Create a list of all relevant files. Our folder may contain multiple export files. files = glob.glob("data/savedrecs*.txt") # wosfile will read each file in the list in turn and yield each record # for further handling for rec in wosfile.records_from(files): # Records are very thin wrappers around a standard Python dict, # whose keys are the WoS field tags. # Here we look at the SC field (subject categories) and update our counter # with the categories in each record. subject_cats.update(rec.get("SC")) # Show the five most common subject categories in the data and their number. print(subject_cats.most_common(5)) Citation network For this example you will need the NetworkX package. The data must be exported as ‘Full Record and Cited References’. import networkx as nx import wosfile # Create a directed network (empty at this point). G = nx.DiGraph() nodes_in_data = set() for rec in wosfile.records_from(files): # Each record has a record_id, a standard string uniquely identifying the reference. nodes_in_data.add(rec.record_id) # The CR field is a list of cited references. Each reference is formatted the same # as a record_id. This means that we can add citation links by connecting the record_id # to the reference. for reference in rec.get("CR", []): G.add_edge(rec.record_id, reference) # At this point, our network also contains all references that were not in the original data. # The line below ensures that we only retain publications from the original data set. G.remove_nodes_from(set(G) - nodes_in_data) # Show some basic statistics and save as Pajek file for visualization and/or further analysis. print(nx.info(G)) nx.write_pajek(G, 'network.net') Other Python packages The following packages also read WoS files (+ sometimes much more): Other packages query WoS directly through the API and/or by scraping the web interface: - pywos (elsewhere called wos-statistics) - wos - wosclient Project details Release history Release notifications | RSS feed 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/wosfile/
CC-MAIN-2021-10
refinedweb
553
56.05
30 April 2010 10:44 [Source: ICIS news] TOKYO (ICIS news)--?xml:namespace> Production of ethylene increased 1.8% to 514,086 tonnes in March year on year, while propylene output rose 16% to 452,740 tonnes, according to the Ministry of Economy, Trade and Industry (METI). The country produced 212,726 tonnes of polyethylene (PE) in March, up 23% from the corresponding year-ago period, while output of polypropylene (PP) increased by 49% to 214,961 tonnes, the METI data showed. March production of pure benzene rose 18% to 384,907 tonnes from the year-ago period, while xylene output was up 11% to 526,673 tonnes, the ministry said. However, production of pure toluene fell 4.1% to 109,793 tonnes in March year on year, and paraxylene output decreased 4.4% to 276,368 tonnes, according to METI. Separately METI announced that Industries that primarily contributed to the increase in industrial output in March were electrical machinery, transport equipment, iron and steel, the ministry said. Japanese producers expect overall industrial production to rise 3.7% in April and decrease 0.3% in May, according to a survey by METI. Industries that were forecast to contribute to the increase in April were mainly general machinery, chemicals and information and communication electronics equipment, METI said. Industries such as transport equipment, fabricated metals and general machinery were projected to primarily contribute to the expected decrease in May, according to the ministry. The survey of production forecast is conducted monthly, which reflects changing business conditions and provides a view of where the economy is heading in the near future, according to the ministry. For more on ethylene, propylene,
http://www.icis.com/Articles/2010/04/30/9355306/japans-olefins-polyolefins-output-rises-in-march.html
CC-MAIN-2013-48
refinedweb
277
55.03
PyTorch Max: Get Maximum Value Of A PyTorch Tensor PyTorch Max - Use PyTorch's max operation to calculate the max of a PyTorch tensor < > Code: Transcript: This video will show you how to use PyTorch’s max operation to calculate the max of a PyTorch tensor. First, we import PyTorch. import torch Then we check what version of PyTorch we are using. print(torch.__version__) We are using PyTorch version 0.4.1. Let’s next create the tensor we’ll use for the PyTorch max operation example. tensor_max_example = torch.tensor( [ [ [1, 1, 1], [2, 2, 2], [3, 3, 3] ], [ [4, 4, 4], [5,50, 5], [6, 6, 6] ] ] ) So here we have torch.tensor which creates a floating tensor. We have a 2x3x3 tensor that we’re going to assign to the Python variable tensor_max_example. Visually, we can see that the max is going to be the number 50. Let’s print the tensor_max_example Python variable to see what we have. print(tensor_max_example) We see that it’s a PyTorch tensor, we see that it is 2x3x3, and we still visually see that the max is going to be 50. Next, let’s calculate the max of a PyTorch tensor using PyTorch tensor’s max operation. tensor_max_value = torch.max(tensor_max_example) So torch.max, we pass in our tensor_max_example, and we assign the value that’s returned to the Python variable tensor_max_value. Let’s print the tensor_max_value variable to see what we have. print(tensor_max_value) We see that the max value is 50. The one thing to note is that PyTorch returns the max value inside of a 0-dimensional tensor with the value of 50 inside of it. Let’s double check to see what it is by using Python’s type operation. type(tensor_max_value) We can see that it’s the class of torch.Tensor. So it is a PyTorch tensor that is returned with the max value inside of it. Let’s use PyTorch’s item operation to get the value out of the 0-dimensional tensor. torch.max(tensor_max_example).item() And now, we get the number 50. And just to make sure it’s a number, let’s use the Python type operation to check that this is actually a number. type(torch.max(tensor_max_example).item()) And we see that it is a Python of class "int" for integer. Perfect! We were able to use PyTorch’s max operation to calculate the max of a PyTorch tensor.
https://aiworkbox.com/lessons/pytorch-max-get-maximum-value-of-a-pytorch-tensor
CC-MAIN-2020-40
refinedweb
411
64.91
This C Program calculates the Sum of Series 1^2 + 2^2 + …. + n^2. Then the Sum of the series 1^2 + 2^2 + …. + n^2 = n(n + 1)(2n + 1) / 6. Here is source code of the C Program to Find the Sum of Series 1^2 + 2^2 + …. + n^2. The C program is successfully compiled and run on a Linux system. The program output is also shown below. /* * C Program to find the sum of series 1^2 + 2^2 + …. + n^2. */ #include <stdio.h> int main() { int number, i; int sum = 0; printf("Enter maximum values of series number: "); scanf("%d", &number); sum = (number * (number + 1) * (2 * number + 1 )) / 6; printf("Sum of the above given series : "); for (i = 1; i <= number; i++) { if (i != number) printf("%d^2 + ", i); else printf("%d^2 = %d ", i, sum); } return 0; } Output: $ cc pgm18.c $ a.out Enter maximum values of series number: 4 Sum of the above given series : 1^2 + 2^2 + 3^2 + 4^2 = 30. « Prev Page - C Program Count the Number of Occurrences of an Element in the Linked List using Recursion
https://www.sanfoundry.com/c-program-sum-series-n-power-2/
CC-MAIN-2018-34
refinedweb
189
73.58
Using DataLoader to batch API requests May 23, 2020 The Problem Let’s say you have a list of user ID as props and you want to fetch and render a list of user’s info. You may have an API that looks something like this: // url const url = '/api/get-users'; // input const input = { userIds: [1, 2, 3], }; // output const output = { users: [ // ...list of user object ], }; This is great, you pass in a list of user IDs and you get a list of user objects. You can simply do the fetching inside the list component and render the items after getting the list of user objects. This is simple enough, but let’s make things more challenging. What if there is a new component that also needs to fetch a list of users? The list of user ID might be different we cannot abstract the fetching logic because it is at the other side of the React tree. You can do another fetch in the new component, but this is not ideal because: - You can potentially save a request by combining the 2 requests - You might be requesting for the same data twice (some IDs might overlap) Wouldn’t it be great if somehow we can collect all the user IDs that needed to be fetched and combine them into a single request? Well, it turns out you can do just that using DataLoader! What is DataLoader? DataLoader is a generic utility to be used as part of your application’s data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching. I came across DataLoader when researching GraphQL. It is used to solve the N + 1 problem in GraphQL, you can learn more about it here. Essentially, it provides APIs for developers to load some keys. All the keys it collects within a single frame of execution (a single tick of the event loop) will be passed into a user-defined batch function. When using GraphQL, the batching function is usually a call to DB. But when using it in the browser, we can instead define the batching function to send an API request. It will look something like this: import DataLoader from 'dataloader'; async function batchFunction(userIds) { const response = await fetch('/api/get-users'); const json = await response.json(); const userIdMap = json.users.reduce((rest, user) => ({ ...rest, [user.id]: user, })); return userIds.map((userId) => userIdMap[userId] || null); } const userLoader = new DataLoader(batchFunction); Let’s see what’s going on here: - A DataLoader takes in a batch function The batch function accepts a list of keys and returns a Promise which resolves to an array of values. - The Array of values must be the same length as the Array of keys. - Each index in the Array of values must correspond to the same index in the Array of keys. - The result of our API might not be in the same order as the passed in user IDs and it might skip for any invalid IDs, this is why I am creating a userIdMapand iterate over userIdsto map the value instead of returning json.usersdirectly. You can then use this userLoader like this: // get a single user const user = await userLoader.load(userId); // get a list of user const users = await userLoader.loadMany(userIds); You can either use load to fetch a single user or loadMany to fetch a list of users. By default, DataLoader will cache the value for each key ( .load() is a memoized function), this is useful in most cases but in some situations you might want to be able to clear the cache manually. For example if there’s something wrong with the user fetching API and the loader is returning nothing for some keys, you probably don’t want to cache that. You can then do something like this to clear the cache manually: // get a single user const user = await userLoader.load(userId); if (user === null) { userLoader.clear(userId); } // get a list of user const users = await userLoader.loadMany(userIds); userIds.forEach((userId, index) => { if (users[index] === null) { userLoader.clear(userId); } }); With the power of React Hook, you can abstract this user fetching logic into a custom hook: // useUser.js import { useState, useEffect } from 'react'; import userLoader from './userLoader'; function useUser(userId) { const [isLoading, setIsLoading] = useState(false); const [user, setUser] = useState(null); useEffect(() => { const fetchUser = async () => { setIsLoading(true); const user = await userLoader.load(userId); if (user === null) { userLoader.clear(userId); } setUser(user); setIsLoading(false); }; fetchUser(); }, [userId]); return { isLoading, user, }; } export default useUser; // use it anywhere in the application const user = useUser(userId); Isn’t this great? Simply use useUser in a component and it will take care of the rest for you! You don’t need to worry about abstracting the fetching logic or caching the response anymore! Here is a quick demo: But what if the components do not render in a single frame? Worries not, DataLoader allows providing a custom batch scheduler to account for this. As an example, here is a batch scheduler which collects all requests over a 100ms window of time (and as a consequence, adds 100ms of latency): const userLoader = new DataLoader(batchFunction, { batchScheduleFn: (callback) => setTimeout(callback, 100), }); Ok, it looks pretty good so far, is there any downside by using DataLoader? From my experience, there is one tiny thing that bothers me when using DataLoader. Because DataLoader requires a single frame to collect all keys, it will take at least 2 frames to returns the results, even when it’s cached. Meaning if you have a loading indicator, it will still flash for a split second. I have yet to find a solution to this but I will update this post as soon as I find one. Conclusion By using DataLoader, you can easily batch requests initiated from different components anywhere in the render tree, and the result will be cached automatically, you also have the power to customize the scheduler and caching behavior. I have used React Hook as an example but you can easily use it in any other framework as well. What do you think of this pattern? Is there any other pitfalls that I haven’t considered? Let me know!
https://colloque.io/using-dataloader-to-batch-api-requests/
CC-MAIN-2022-40
refinedweb
1,042
61.16
Test::LectroTest - Easy, automatic, specification-based tests #!/usr/bin/perl -w use MyModule; # contains code we want to test use Test::LectroTest; Property { ##[ x <- Int, y <- Int ]## MyModule::my_function( $x, $y ) >= 0; }, name => "my_function output is non-negative" ; Property { ... }, name => "yet another property" ; # more properties to check here This module provides a simple (yet full featured) interface to LectroTest, an automated, specification-based testing system for Perl. To use it, declare properties that specify the expected behavior of your software. LectroTest then checks your software to see whether those properties hold. Declare properties using the Property function, which takes a block of code and promotes it to a Test::LectroTest::Property: Property { ##[ x <- Int, y <- Int ]## MyModule::my_function( $x, $y ) >= 0; }, name => "my_function output is non-negative" ; The first part of the block must contain a generator-binding declaration. For example: ##[ x <- Int, y <- Int ]## (Note the special bracketing, which is required.) This particular binding says, "For all integers x and y." (By the way, you aren't limited to integers. LectroTest also gives you booleans, strings, lists, hashes, and more, and it lets you define your own generator types. See Test::LectroTest::Generator for more.) The second part of the block is simply a snippet of code that makes use of the variables we bound earlier to test whether a property holds for the piece of software we are testing: MyModule::my_function( $x, $y ) >= 0; In this case, it asserts that MyModule::my_function($x,$y) returns a non-negative result. (Yes, $x and $y refer to the same x and y that we bound to the generators earlier. LectroTest automagically loads these lexically bound Perl variables with values behind the scenes.) Note: If you want to use testing assertions like ok from Test::Simple or is, like, or cmp_ok from Test::More (and the related family of Test::Builder-based testing modules), see Test::LectroTest::Compat, which lets you mix and match LectroTest with these modules. Finally, we give the whole Property a name, in this case "my_function output is non-negative." It's a good idea to use a meaningful name because LectroTest refers to properties by name in its output. Let's take a look at the finished property specification: Property { ##[ x <- Int, y <- Int ]## MyModule::my_function( $x, $y ) >= 0; }, name => "my_function output is non-negative" ; It says, "For all integers x and y, we assert that my_function's output is non-negative." To check whether this property holds, simply put it in a Perl program that uses the Test::LectroTest module. (See the "SYNOPSIS" for an example.) When you run the program, LectroTest will load the property (and any others in the file) and check it by running random trials against the software you're testing. Note: If you want to place LectroTest property checks into a test plan managed by Test::Builder-based modules such as Test::Simple or Test::More, see Test::LectroTest::Compat. If LectroTest is able to "break" your software during the property check, it will emit a counterexample to your property's assertions and stop. You can plug the counterexample back into your software to debug the problem. (You might also want to add the counterexample to a list of regression tests.) A successful LectroTest looks like this: 1..1 ok 1 - 'my_function output is non-negative' (1000 attempts) On the other hand, if you're not so lucky: 1..1 not ok 1 - 'my_function output is non-negative' falsified \ in 324 attempts # Counterexample: # $x = -34 # $y = 0 The exit code returned by running a suite of property checks is the number of failed checks. The code is 0 if all properties passed their checks or N if N properties failed. (If more than 254 properties failed, the exit code will be 254.) There is one testing parameter (among others) that you might wish to change from time to time: the number of trials to run for each property checked. By default it is 1,000. If you want to try more or fewer trials, pass the trials=>N flag: use Test::LectroTest trials => 10_000; playback_failures => "regression_suite_for_my_module.txt", record_failures => "failures_in_the_field.txt"; See Test::LectroTest::RegressionTesting for more. When you use this module, it imports all of the generator-building functions from Test::LectroTest::Generator into the your code's namespace. This is almost always what you want, but I figured I ought to say something about it here to reduce the possibility of surprise. A Property specification must appear in the first column, i.e., without any indentation, in order for it to be automatically loaded and checked. If this poses a problem, let me know, and this restriction can be lifted.::Compat lets you mix LectroTest with the popular family of Test::Builder-based modules such as Test::Simple and Test::More..
http://search.cpan.org/%7Etmoertel/Test-LectroTest-0.3500/lib/Test/LectroTest.pm
crawl-002
refinedweb
802
53.21
This documentation is archived and is not being maintained. Compiler Error CS1613 Visual Studio .NET 2003 The managed coclass wrapper class 'class' for interface 'interface' is invalid or cannot be found (are you missing an assembly reference?) An attempt was made to instantiate a COM object from an interface. The interface has the ComImport and CoClass attributes, but the compiler cannot find the type given for the CoClass attribute. To resolve this error, you can try one of the following: - Add a reference to the assembly that has the coclass (most of the time the interface and coclass should be in the same assembly). See /reference or Add Reference Dialog Box for information. - Fix the CoClass attribute on the interface. The following sample demonstrates correct usage of CoClassAttribute: // CS1613.cs using System; using System.Runtime.InteropServices; [Guid("1FFD7840-E82D-4268-875C-80A160C23296")] [ComImport()] [CoClass(typeof(A))] public interface IA{} public class A : IA {} public class AA { public static void Main() { IA i; i = new IA(); // This is equivalent to new A(). // because of the CoClass attribute on IA } } Show:
https://msdn.microsoft.com/en-us/library/9zc0sy3y(v=vs.71)
CC-MAIN-2017-22
refinedweb
179
57.16
import supported directory mode: (no extra options) Raw streams which can be concatenated without any further intervention are supported. Currently MPEG program streams (VOB) and raw Digital Video (DV) streams are supported in this mode. The sources are treated as a logical input stream and piped into the decoder. This way, most navigation options can be applied. option supported directory mode: (--dir_mode base [--no_split]) Source files that can not simply be concatenated with "cat", like AVI-files, can be processed in a row using the option "--dir_mode base" resulting in a sequence of output-files named: base-000.avi, base-001.avi, ... base-000.avi, base-001.avi, ... This is identical with calling each file separatly. However, for two-pass encoding or merging the resulting files on-the-fly, the additional option "--no_split" is required. This will result in one file named "base". In general, it's a good idea to move the various chunks of the big program stream, we previously ripped from a DVD, into a directory, we denote as vob_dir. Please see the DVD backup guide for details. We will need to put the "*.VOB" files into this extra directory to make the directory mode of tccat and transcode work. Please keep the vob_dirclean: A typical output of the command looks as follows:: This will eventually produce the 4 output files: movie-psu00.avi, movie-psu01.avi, movie-psu02.avi, movie-psu03.avi. junk trailers or film company/distributor intro logos and can be skipped with the additional option: --psu_chunks 2-4 -, latest 0.6.0pre5 snapshots provide another long option --no_split -.
http://idlebox.net/2006/apidocs/transcode-0.6.14.zip/core.html
CC-MAIN-2014-15
refinedweb
265
55.34
This is the mail archive of the binutils@sources.redhat.com mailing list for the binutils project. Daniel Jacobowitz <drow@mvista.com> writes: > On Sun, Feb 17, 2002 at 05:37:17PM -0800, Ian Lance Taylor wrote: > > Daniel Jacobowitz <drow@mvista.com> writes: > > > > >? > > > > What is in the bfd_default_vector array in your ld-new executable? > > Only shcoff_vec. Which is, of course, big endian. Yet GAS seems to be > producing coff-shl by default. This patch, which Nick checked in on November 15 with an unrelated ChangeLog entry, shows that gas will always generate a little endian object. 2001-11-15 Nick Clifton <nickc@cambridge.redhat.com> * cgen.c, config/obj-coff.c, config/tc-*.c: Update all occurances of md_apply_fix to md_apply_fix3. Make all md_apply_fix3 functions void. -- obj-coff.h 2001/03/08 23:24:22 1.11 +++ obj-coff.h 2001/11/15 21:28:54 1.12 @@ -121,10 +121,17 @@ #ifdef TE_PE #define TARGET_FORMAT "pe-shl" #else + +#if 0 /* FIXME: The "shl" varaible does not appear to exist. What happened to it ? */ #define TARGET_FORMAT \ (shl \ ? (sh_small ? "coff-shl-small" : "coff-shl") \ : (sh_small ? "coff-sh-small" : "coff-sh")) +#else +#define TARGET_FORMAT \ + (sh_small ? "coff-shl-small" : "coff-shl") +#endif + #endif #endif The shl variable disappeared in this patch on October 16. 2001-10-16 NIIBE Yutaka <gniibe@m17n.org>, Hans-Peter Nilsson <hp@bitrange.com> * config/tc-sh.c (shl): Remove. (big): New function. (little): Remove shl handling. Emit error for endian mismatch. (md_show_usage): Add description of -big. (md_parse_option): Handle OPTION_BIG. Remove shl handling. (OPTION_BIG): Add. (md_pseudo_table): Add .big. (md_longopts): Add -big. (md_begin): Don't set target_big_endian here. * config/tc-sh.h (TARGET_BYTES_BIG_ENDIAN): Remove. (LISTING_HEADER, COFF_MAGIC, TARGET_FORMAT): Use target_big_endian. (shl): Remove. * configure.in (endian): Default is big. (sh-*-pe*): Little endian. (cpu_type): Set sh for target sh*. * configure: Regenerate. I would guess that the October 16 patch was not tested for sh-coff. I imagine that the correct fix is to restore the old obj-coff.h setting of TARGET_FORMAT, but have it test target_big_endian rather than shl. Ian
https://sourceware.org/legacy-ml/binutils/2002-02/msg00615.html
CC-MAIN-2022-27
refinedweb
339
55.71
A value class that describes an index to an item in a data model. More... #include <Wt/WModelIndex> A value class that describes an index to an item in a data model. Indexes are used to indicate a particular item in a WAbstractItemModel. An index points to the item by identifying its row and column location within a parent model index. An index is immutable. The default constructor creates an invalid index, which by convention indicates the parent of top level indexes. Thus, a model that specifies only a list or table of data (but no hierarchical data) would have as valid indexes only indexes that specify the invalid model index as parent. Upon the model's choice, model indexes for hierarchical models may have an internal Id represented by a int64_t (internalId()), a pointer (internalPointer()). Indexes are created by the model, within the protected WAbstractItemModel::createIndex() methods. In this way, models can define an internal pointer or id suitable for identifying parent items in the model. When a model's geometry changes due to row or column insertions or removals, you may need to update your indexes, as otherwise they may no longer point to the same item (but instead still to the same row/column). Thus, if you store indexes and want to support model changes such as row or columns insertions/removals, then you need to react to the corresponding signals such as WAbstractItemModel::rowsInserted() to update these indexes (i.e. shift them), or even remove them when the corresponding row/column has been removed. When a model's layout changes (it is rearranging its contents for example in response to a sort operation), a similar problem arises. Some models support tracking of indexes over layout changes, using raw indexes. In reaction to WAbstractItemModel::layoutAboutToBeChanged(), you should encode any index which you wish to recover after the layout change using encodeAsRawIndex(), and in WAbstractItemModel::layoutChanged() you can obtain an index that points to the same item using decodeFromRawIndex(). Create an invalid WModelIndex. Returns a model index for which isValid() return false. Returns a model index for a child item. This is a convenience method, and is only defined for indexes that are valid(). It has the same function as WAbstractItemModel::index() but is less general because the latter expression may also be used to retrieve top level children, i.e. when index is invalid. Returns data in the model at this index. This is a convenience method for WAbstractItemModel::data(). Decodes a raw index (after a layout change). A raw index can be decoded, within the context of a model that has been re-layed out. This method returns a new index that points to the same item, or, WModelIndex() if the underlying model did not support encoding to raw indexes, or, if the item to which the index previously pointed, is no longer part of the model. Utility method to decode an entire set of raw indexes. Returns the depth (in a hierarchical model). A top level index has depth 0. Encode to raw index (before a layout change). Use this method to encode an index for which you want to recover an index after the layout change to the same item (which may still be in the model, but at a different location). An index that has been encoded as a raw index cannot be used for anything but decodeFromRawIndex() at a later point. Utility method for converting an entire set of indexes to raw. Returns the flags for this item. This is a convenience method for WAbstractItemModel::flags(). Returns the internal id. The internal id is used by the model to retrieve the corresponding data. This is only defined when the model created the index using WAbstractItemModel::createIndex(int, int, uint64_t) const. Returns the internal pointer. The internal pointer is used by the model to retrieve the corresponding data. This is only defined when the model created the index using WAbstractItemModel::createIndex(int, int, void *) const. Returns whether the index is a real valid index. Returns true when the index points to a valid data item, i.e. at a valid row() and column(). An index may be invalid for two reasons: Returns the model to which this (valid) index is bound. This returns the model that created the model index. Comparison operator. Comparison operator. Returns true if the index comes topologically before other. Topological order follows the order in which the indexes would be displayed in a tree table view, from top to bottom followed by left to right. An invalid index comes before all other indexes. Indexes encoded as raw index come after the invalid index and before all other indexes, and are ordered according to their internalId(). Comparison operator. Returns true only if the indexes point at the same data, in the same model. Returns an index to the parent. This is a convenience method for WAbstractItemModel::parent(). For a top level data item, the parent() is an invalid index (see WModelIndex()).
https://webtoolkit.eu/wt/wt3/doc/reference/html/classWt_1_1WModelIndex.html
CC-MAIN-2021-31
refinedweb
831
56.55
BME280 Temp/Hum sensor on battery power increasingly skips(?) operation Hi, I have a battery-operated temp/humidty sensor running on 2x AA batteries. Components are: - Arduino Pro 3.3v clone with 47uF bulk cap (LEDs and volt regulator removed) - BME280 - NRF24L01+ radio with 47uF bulk cap - 3.3v voltage booster/regulator w/ 100uF bulk cap and 0.1uF ceramic cap It's set to report temp/hum every 10 minutes. Upon reset, it works flawlessly for 3 to 4 days, and then it'd start skipping an operation maybe once every a few hours (i.e. no update received). As time progresses such skips get worse, sending updates once per hour to every few hours. Eventually it'd just stop updating. Funny thing is, upon reset it'd work fine again for another few days only to get worse again following the exact same pattern described above. I'm unsure whether it's "self-resetting" I do not see the typical MySensors presentation messages when the sensor goes live again. But the smartSleep() integer counter sometimes gets reset. I have two other identical sensors that are each powered via a 5v wall wart, and they NEVER display this symptom. So I'm pretty sure it's related to it being battery powered. The battery is connected to a 3.3v voltage booster along with 100uF electrolyte bulk capacitor AND 0.1uF ceramic capacitor, as instructed by MySensors.org website. All components (Arduino, sensor, and radio) are powered by the output from the same voltage booster. Has anyone experience a similar issue? What could be the culprit, and what can I do to fix this? Thanks! @gogopotato Try without the regulator, running the ProMini (through its Vcc input, regulator & LED disconnected), nRF24 and BME280 directly off 2xAA. I have an identical setup (without the big capacitors) that is running fine for weeks now. @Yveaux Are you running the system with only the LEDs removed, and you are using the Arduino built-in voltage regulator? My concern with this setup is that it wouldn't last long since you are starting at already-low 3.0v at max. How long do you think it would last? I am thinking of just using 4x AAs with built-in regulator if all else fails. This post is deleted! @gogopotato No, I removed both the LED and the regulator, so everything is driven directly from 2xAA. I have similar sensors (e.g. with Si7021 temp/hum sensor) which run for years on such setup. A steup converter will just reduce the battery lifetime due to its loss and power tends to be less stable than using batteries directly. Can you please paste your sketch? I found some here but I think is outdated, readings not working properly . Thanks ! @warmaniac Here's my code: // Enable and select radio type attached #define MY_RADIO_NRF24 #define MY_NODE_ID 11 //#define MY_PARENT_NODE_ID #include <SPI.h> #include <MySensors.h> #include <avr/wdt.h> //watchdog timer lib #include <Adafruit_Sensor.h> #include <Adafruit_BME280.h> // Change I2C address in Adafruit_BME280 library to "0x76" (line 32 in the library file) #include "Wire.h" Adafruit_BME280 bme; // I2C #define CHILD_ID_HUM 0 // RH #define CHILD_ID_TEMP_F 1 // temp in F // MyMessage to controler MyMessage msgT1(CHILD_ID_TEMP_F, V_TEMP); MyMessage msgH1(CHILD_ID_HUM, V_HUM); MyMessage msgE1(255, V_TEXT); // Debug message void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo("Nursery", "1.2"); present(CHILD_ID_TEMP_F, S_TEMP); present(CHILD_ID_HUM, S_HUM); } void setup() { startBME(); ServerUpdate(); // for first data reading and sending to controler } void loop() { smartSleep(600000); // sleep for 10 mins ServerUpdate(); } void startBME() { delay(1000); //just in case if (!bme.begin()) { send(msgE1.set("BME280 INIT FAIL")); #ifdef MY_DEBUG Serial.println("BME280 initialization failed!"); #endif while (1); } else send(msgE1.set("BME280 INIT SUCCESS")); delay(5000); //delay for 5 second before the 1st reading; prevents errant spike in sensor value #ifdef MY_DEBUG Serial.println("BME280 initialization success!"); #endif } void ServerUpdate() // used to read sensor data and send it to controller { bme.begin(); //re-initialize for each reading double TF, TC, P, H; TC = bme.readTemperature(); //read temp in C TF = TC * 9 / 5 + 32; // convert default Celcius reading to Fahrenheit H = bme.readHumidity(); if (TF < 0 || H == 100 || H == 0) { // if sensor values are in error, do nothing. } else { send(msgT1.set(TF, 1)); send(msgH1.set(H, 1)); } #ifdef MY_DEBUG Serial.print("T = \t"); Serial.print(TF, 1); Serial.print(" degF\t"); //Serial.print("T = \t"); Serial.print(TC, 1); Serial.print(" degC\t"); Serial.print("H = \t"); Serial.print(H, 1); Serial.print(" percent"); //Serial.print("P = \t"); Serial.print(P, 1); Serial.print(" mBar\t"); #endif } - gogopotato last edited by gogopotato This post is deleted! - gogopotato last edited by gogopotato @warmaniac hmm now that I am reviewing my code, I have "do nothing if value is error" logic. if (TF < 0 || H == 100 || H == 0) { // if sensor values are in error, do nothing. } else { send(msgT1.set(TF, 1)); send(msgH1.set(H, 1)); Perhaps the voltage booster is causing BME280 to behave badly? But then why would it work fine for the first few days? Do you think adding a bulk capacitor to BME280 would to stabilize power hence reducing errant readings? If so how big of a capacitor would I need? The mystery continues.... @Yveaux If step-up converter would only reduce the battery lifetime, why does Mysensors.org page suggest using one to extend battery life? I'm new to electronics so please bear with me! I had problem that BME is inaccurate outside , I'm using BME180 and BME 280 both works great inside readings are almost same , but when I put it outside temperature is much higher than real, I compare it with ds18b20 or with my standalone weather station + local weather station , it was almost same but BME is higher about 2 degrees @warmaniac yeah I think my BME280 is about +2 F than real temp. Anyway, do you have any suggestions as to resolving the issue? Maybe I should just replace it with DHT22. I had 5 pcs of DHT 11 and 3 pcs of DHT22 and there are seriously piece of sh.. humidity readings was very bad only temperature okay , than if you want to measure only temperature best way is buy waterproof ds18b20 , @gogopotato Taken from the BME280 datasheet: "Temperature measured by the internal temperature sensor. This temperature value depends on the PCB temperature, sensor element self-heating and ambient temperature and is typically above ambient temperature. " (does not explain very much ;-)) I have a good experience with this sensor when operated from a stable power source (3.3V ldo). Some boards of the boards sold are equiped with a LDO which can cause problems if you operate under a certain voltage. I had this one, is it OK ? I power it directly from 2xAA batteries, and can operate 1,71 to 3,7 volts as I saw in datasheet .Then you said that is problem of using because it has self heating problem ? @AWI This is the BME280 module I'm using, and looks like it's got an LDO built-in, am I correct? Vin is 1.8 - 5V DC. Maybe I should just bypass the voltage booster and supply power to the module directly from the battery...? @warmaniac That is the one without LDO (regulator). The self heating problem is not likely to occur if you are not constantly accessing the sensor and thus warming it. The main function of the temperature sensor is compensation for barometer and humidity reading. It is a rather complicated component with a lot of different settings and adjustments. I understand but it's mysterious thing , because indoor it works ok , but when I put it outside , readings are not correct , maybe it is not for outdoor usage @gogopotato And that one is with the LDO built in. You need to make sure that the sensor gets enough juice. I can't see which regulator is used but probably a 662K (XC6206) which is not likely to produce any voltage below 2.6V - AWI Hero Member last edited by AWI @warmaniac The sensor should be perfect for outdoor usage. At least you are not alone . This guy deserves some real credits doing the research and has some ideas on the cause in the article. (you can also take look at his wedding pictures there) conclusion: Thanks , I take a read after I finish in work. But I decided to use ds18b20 sealed version plus standalone humidity sensor , maybe it will be better Then I post some experiences. Maybe you can take a look on my photos too , I like landscapes photos , but sometimes I shooting weddings too - Scott Wilson last edited by My BME280 is around 1F hotter outside than a DS18B20 outside in another project. Not a big deal but I am also researching how to keep it cool. The library I am using is this one.
https://forum.mysensors.org/topic/6494/bme280-temp-hum-sensor-on-battery-power-increasingly-skips-operation/7
CC-MAIN-2019-13
refinedweb
1,488
66.84
By Tom Dykstra and Rick Anderson The Contoso University sample web application demonstrates how to create ASP.NET Core MVC web applications using Entity Framework Core CRUD (create, read, update, delete) repositories with EF, see the last tutorial in this series. In this tutorial, you’ll work with the following web pages: Customize the Details page The scaffolded code for the Students Index page left out the Enrollments property, because that property holds a collection. In the Details page, you’ll display the contents of the collection in an HTML table. In Controllers/StudentsController.cs, the action method for the Details view uses the SingleOrDefaultAsync method to retrieve a single Student entity. Add code that calls Include. ThenInclude, and AsNoTracking methods, as shown in the following highlighted code. public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var student = await _context.Students .Include(s => s.Enrollments) .ThenInclude(e => e.Course) .AsNoTracking() .SingleOrDefaultAsync(m => m.ID == id); if (student == null) { return NotFound(); } return View(student); } The Include and ThenInclude methods cause the context to load the Student.Enrollments navigation property, and within each enrollment the Enrollment.Course navigation property. You’ll learn more about these methods in the read related data tutorial. The AsNoTracking method improves performance in scenarios where the entities returned won’t be updated in the current context’s lifetime. You’ll learn more about AsNoTracking at the end of this tutorial. Route data The key value that’s passed to the Details method comes from route data. Route data is data that the model binder found in a segment of the URL. For example, the default route specifies controller, action, and id segments: app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); In the following URL, the default route maps Instructor as the controller, Index as the action, and 1 as the id; these are route data values. The last part of the URL ("?courseID=2021") is a query string value. The model binder will also pass the ID value to the Details method id parameter if you pass it as a query string value: In the Index page, hyperlink URLs are created by tag helper statements in the Razor view. In the following Razor code, the id parameter matches the default route, so id is added to the route data. <a asp-Edit</a> This generates the following HTML when item.ID is 6: <a href="/Students/Edit/6">Edit</a> In the following Razor code, studentID doesn’t match a parameter in the default route, so it’s added as a query string. <a asp-Edit</a> This generates the following HTML when item.ID is 6: <a href="/Students/Edit?studentID=6">Edit</a> For more information about tag helpers, see Tag helpers in ASP.NET Core. Add enrollments to the Details view Open Views/Students/Details.cshtml. Each field is displayed using DisplayNameFor and DisplayFor helpers, as shown in the following example: <dt> @Html.DisplayNameFor(model => model.LastName) </dt> <dd> @Html.DisplayFor(model => model.LastName) </dd> After the last field and immediately before the closing </dl> tag, add the following code to display a list of enrollments: > If code indentation is wrong after you paste the code, press CTRL-K-D to correct it. This. You see the list of courses and grades for the selected student: Update the Create page In StudentsController.cs, modify the HttpPost Create method by adding a try-catch block and removing ID from the Bind attribute. ); } This code adds the Student entity created by the ASP.NET MVC model binder to the Students entity entity for you using property values from the Form collection.) You removed ID from the Bind attribute because ID is the primary key value which SQL Server will set automatically when the row is inserted. Input from the user doesn’t set the ID value. Other than the Bind attribute, the try-catch block is the only change you’ve made to the scaffolded code. If an exception that derives from DbUpdateException is caught while the changes are being saved, a generic error message is displayed. DbUpdate ValidateAntiForgeryToken attribute helps prevent cross-site request forgery (CSRF) attacks. The token is automatically injected into the view by the FormTagHelper and is included when the form is submitted by the user. The token is validated by the ValidateAntiForgeryToken attribute. For more information about CSRF, see Anti-Request Forgery. Security note about overposting The Bind attribute that the scaffolded code includes on the Create method is one way to protect against overposting in create scenarios. For example, suppose the Student entity includes a Secret property that you don’t want this web page to set. public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public string Secret { get; set; } } create set that property. You can prevent overposting in edit scenarios by reading the entity from the database first and then calling TryUpdateModel, passing in an explicit allowed properties list. That’s the method used in these tutorials. An alternative way to prevent overposting that _context.Entry on the entity instance to set its state to Unchanged, and then set Property("PropertyName").IsModified to true on each entity property that’s included in the view model. This method works in both edit and create scenarios. Test the Create page The code in Views/Students/Create.cshtml uses label, input, and span (for validation messages) tag helpers for each field. Run the app, select the Students tab, and click Create New. Enter names and a date. Try entering an invalid date if your browser lets you do that. (Some browsers force you to use a date picker.) Then click Create to see the error message. This is server-side validation that you get by default; in a later tutorial you’ll see how to add attributes that will generate code for client-side validation also. The following highlighted code shows the model validation check in the Create method. ); } Change the date to a valid value and click Create to see the new student appear in the Index page. Update the Edit page In StudentController.cs, the HttpGet Edit method (the one without the HttpPost attribute) uses the SingleOrDefaultAsync method to retrieve the selected Student entity, as you saw in the Details method. You don’t need to change this method. Recommended HttpPost Edit code: Read and update Replace the HttpPost Edit action method with the following code. [HttpPost, ActionName("Edit")] [ValidateAntiForgeryToken] public async Task<IActionResult> EditPost(int? id) { if (id == null) { return NotFound(); } var studentToUpdate = await _context.Students.SingleOrDefaultAsync(s => s.ID == id); if (await TryUpdateModelAsync<Student>( studentToUpdate, "", s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate)) { try {ToUpdate); } These changes implement a security best practice to prevent overposting. The scaffolder generated a Bind attribute and added the entity created by the model binder to the entity set with a Modified flag. That code isn’t recommended for many scenarios because the Bind attribute clears out any pre-existing data in fields not listed in the Include parameter. The new code reads the existing entity and calls TryUpdateModel to update fields in the retrieved entity based on user input in the posted form data. The Entity Framework’s automatic change tracking sets the Modified flag on the fields that are changed by form input. When the SaveChanges method is called, the Entity Framework creates SQL statements to update the database row. Concurrency conflicts are ignored, and only the table columns that were updated by the user are updated in the database. (A later tutorial shows how to handle concurrency conflicts.) As a best practice to prevent overposting, the fields that you want to be updateable by the Edit page are whitelisted in the TryUpdateModel parameters. (The empty string preceding the list of fields in the parameter list is for a prefix to use with the form fields names.). Alternative HttpPost Edit code: Create and attach The recommended HttpPost edit code ensures that only changed columns get updated and preserves data in properties that you don’t want included for model binding. However, the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflicts. An alternative is to attach an entity created by the model binder to the EF context and mark it as modified. (Don’t update your project with this code, it’s only shown to illustrate an optional approach.) public async Task<IActionResult> Edit(int id, [Bind("ID,EnrollmentDate,FirstMidName,LastName")] Student student) { if (id != student.ID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update); } You can use this approach when the web page UI includes all of the fields in the entity and can update any of them. The scaffolded code uses the create-and-attach approach but only catches DbUpdateConcurrencyException exceptions and returns 404 error codes. The example shown catches any database update exception and displays an error message. Entity States following states: Added. The entity doesn’t yet exist in the database. The SaveChangesmethod issues an INSERT statement. Unchanged. Nothing needs to be done with this entity by the SaveChangesmethod. When you read an entity from the database, the entity starts out with this status. Modified. Some or all of the entity’s property values have been modified. The SaveChangesmethod issues an UPDATE statement. Deleted. The entity has been marked for deletion. The SaveChangesmethod issues a DELETE statement. Detached. The entity isn’t being tracked by the database context. In a desktop application, state changes are typically set automatically. You read an entity and make changes to some of its property values. This causes its entity state to automatically be changed to Modified. Then when you call SaveChanges, the Entity Framework generates a SQL UPDATE statement that updates only the actual properties that you changed. In a web app, the DbContext that initially reads an entity and displays its data to be edited is disposed after a page is rendered. When the HttpPost Edit action method is called, a new web request is made and you have a new instance of the DbContext. If you re-read the entity in that new context, you simulate desktop processing. But if you don’t want to do the extra read operation, you have to use the entity object created by the model binder. The simplest way to do this is to set the entity state to Modified as is done in the alternative HttpPost Edit code shown earlier. Then when you call SaveChanges, the Entity Framework updates all columns of the database row, because the context has no way to know which properties you changed. If you want to avoid the read-first approach, but you also want the SQL UPDATE statement to update only the fields that the user actually changed, the code is more complex. You have to save the original values in some way (such as by using hidden fields) so that they’re available when the HttpPost Edit method is called. Then you can create a Student entity using the original values, call the Attach method with that original version of the entity, update the entity’s values to the new values, and then call SaveChanges. Test the Edit page Run the app, select the Students tab, then click an Edit hyperlink. Change some of the data and click Save. The Index page opens and you see the changed data. Update the Delete page In StudentController.cs, the template code for the HttpGet Delete method uses the SingleOrDefaultAsync action method with the following code, which manages error reporting. public async Task<IActionResult> Delete(int? id, bool? saveChangesError = false) { if (id == null) { return NotFound(); } var student = await _context.Students .AsNoTracking() .SingleOrDefaultAsync(m => m.ID == id); if (student == null) { return NotFound(); } if (saveChangesError.GetValueOrDefault()) { ViewData["ErrorMessage"] = "Delete failed. Try again, and if the problem persists " + "see your system administrator."; } return View(student); } This code accepts an optional parameter that indicates whether the method was called after a failure to save changes. This parameter is false when the HttpGet Delete method is called without a previous failure. When it’s called by the HttpPost Delete method in response to a database update error, the parameter is true and an error message is passed to the view. The read-first approach to HttpPost Replace the HttpPost Delete action method (named DeleteConfirmed) with the following code, which performs the actual delete operation and catches any database update errors. [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var student = await _context.Students .AsNoTracking() .SingleOrDefaultAsync(m => m.ID == id); if (student == null) { return RedirectToAction(nameof(Index)); } try { _context.Students.Remove(student); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log.) return RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true }); } } This code retrieves the selected entity, then calls the Remove method to set the entity’s status to Deleted. When SaveChanges is called, a SQL DELETE command is generated. The create-and-attach approach to HttpPost If improving performance in a high-volume application is a priority, you could avoid an unnecessary SQL query by instantiating a Student entity using only the primary key value and then setting the entity state to Deleted. That’s all that the Entity Framework needs in order to delete the entity. (Don’t put this code in your project; it’s here just to illustrate an alternative.) [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { try { Student studentToDelete = new Student() { ID = id }; _context.Entry(studentToDelete).State = EntityState.Deleted; await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log.) return RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true }); } } If the entity has related data that should also be deleted, make sure that cascade delete is configured in the database. With this approach to entity deletion, EF might not realize there are related entities to be deleted. Update the Delete view In Views/Student/Delete.cshtml, add an error message between the h2 heading and the h3 heading, as shown in the following example: <h2>Delete</h2> <p class="text-danger">@ViewData["ErrorMessage"]</p> <h3>Are you sure you want to delete this?</h3> Run the app, select the Students tab, and click a Delete hyperlink: Click Delete. The Index page is displayed without the deleted student. (You’ll see an example of the error handling code in action in the concurrency tutorial.) Closing database connections To free up the resources that a database connection holds, the context instance must be disposed as soon as possible when you are done with it. The ASP.NET Core built-in dependency injection takes care of that task for you. In Startup.cs, you call the AddDbContext extension method to provision the DbContext class in the ASP.NET DI container. That method sets the service lifetime to Scoped by default. Scoped means the context object lifetime coincides with the web request life time, and the Dispose method will be called automatically at the end of the web request. Handling Transactions By default the Entity Framework implicitly implements transactions. In scenarios where you make changes to multiple rows or tables and then call SaveChanges, the Entity Framework automatically makes sure that either all of your changes succeed or they all fail. If some changes are done first and then an error happens, those changes are automatically rolled back. For scenarios where you need more control — for example, if you want to include operations done outside of Entity Framework in a transaction — see Transactions. No-tracking queries When a database context retrieves table rows and creates entity objects that represent them, by default it keeps track of whether the entities in memory are in sync with what’s in the database. The data in memory acts as a cache and is used when you update an entity. This caching is often unnecessary in a web application because context instances are typically short-lived (a new one is created and disposed for each request) and the context that reads an entity is typically disposed before that entity is used again. You can disable tracking of entity objects in memory by calling the AsNoTracking method. Typical scenarios in which you might want to do that include the following: During the context lifetime you don’t need to update any entities, and you don’t need EF to automatically load navigation properties with entities retrieved by separate queries. Frequently these conditions are met in a controller’s HttpGet action methods. You are running a query that retrieves a large volume of data, and only a small portion of the returned data will be updated. It may be more efficient to turn off tracking for the large query, and run a query later for the few entities that need to be updated. You want to attach an entity in order to update it, but earlier you retrieved the same entity for a different purpose. Because the entity is already being tracked by the database context, you can’t attach the entity that you want to change. One way to handle this situation is to call AsNoTrackingon the earlier query. For more information, see Tracking vs. No-Tracking. Summary You now have a complete set of pages that perform simple CRUD operations for Student entities. In the next tutorial you’ll expand the functionality of the Index page by adding sorting, filtering, and paging.
http://ugurak.net/index.php/2018/06/29/asp-net-core-mvc-with-ef-core-crud-2-of-10/
CC-MAIN-2018-47
refinedweb
2,936
55.34
Out of the Angle Brackets The XmlPreloadedResolver is a new type that we’ve been working on in SilverLight that provides the ability to load a DTD without a call to the network. The new type can act as a manually maintainable cache of DTD’s and XML Streams. Let’s look at two examples of how the XmlPreloadedResolver can be used. Example 1: The XmlPreloadedResolver can be used to pre-load an external DTD. In the following example, a user-defined DTD is pre-loaded into the resolver. The resolver is then used when loading the XML file. String strDtd = "<!ENTITY entity 'Replacement text'>"; String strXml = @"<!DOCTYPE doc SYSTEM 'myDtd.dtd'> <doc>&entity;</doc>"; System.Xml.Resolvers.XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(resolver.ResolveUri(null, "myDtd.dtd"), strDtd); XmlReaderSettings rs = new XmlReaderSettings(); rs.XmlResolver = resolver; rs.DtdProcessing = DtdProcessing.Parse; XmlReader reader = XmlReader.Create(new StringReader(strXml), rs); For the complete example, refer to: Example 2: The XmlPreloadedResolver also contains two well-known DTD sets: XHTML 1.0 and RSS 0.91. These two well known DTD sets can be enabled via the XmlKnownDtd enumeration. The following is an example of using the XmlPreloadedResolver to preload the XHTML 1.0 DTD into an XmlReaderSettings object. In this example, no network calls are needed to parse an XHTML file. XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.XmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10); XmlReader reader = XmlReader.Create("HTMLPage.html", settings); XDocument document = XDocument.Load(reader); For the complete example, refer to: Look for this new class in System.Xml.Resolvers namespace in a new DLL: System.Xml.Utils.dll that will be included as part of the upcoming SilverLight 2.0 SDK. Shayne BurgessProgram Manager | Data Programmability - and - Helena KotasSenior Software Development Engineer | Data Programmability PingBack from Is it Silverlight-specific, or will it also appear in the full version of the Framework? Writing all the code to preload local DTDs for XML files is possible there at the moment, but very tedious. Something like this would really help. Ditto the comment above, having this in the full framework would be incredibly useful. I would also like to chime in and vote +1 for getting this feature in the full .NET Framework. In a project at my previous employer we suffered through big performance problems when parsing XHTML 1.0 as XML using .NET 1.1. This happened when the XHTML contained hundreds of entity references. We were feeding the full XHTML DTD to the XML parser. Parsing performance degraded much faster than linearly with the number of entity references in the XHTML. As a workaround we had to manually strip the XHTML DTD down to contain just the entity definitions (ë etc). Performance become acceptable in that case. I hope these issues have been fixed. Hey ALLO___XHTML preloadER DTD FOR XML FILES OVER TIME MACHINES AND DRIVES do nothing OR WE'LL BE TALKING like PHYSICAL APPLICATIONS FOR THESES PROCEDURES OR PROCESSES i DO NOT BELIEVE in it and can't BE DONE BECAUSE IT's LIKE ME SAYING APPARENTLY I HAVE SIMOLTANEUS INITIATIVES and yello dog the OKAY user IN A FIGHTING SCENEREO. The thesis for resolving such an issue is nothing + not working.....understand no resolver droped well or be on the matter ecx. think my machine will not come on without a physical application process R.S.V.P;. Thanks for the feedback. Currently, the XmlPreloadedResolver is only in the SilverLight 2.0 SDK. We have talked about including it in the next version of the framework but we have not made a decision yet if we will. We will take this feedback into account, however, when we do make the decision. -Shayne
http://blogs.msdn.com/xmlteam/archive/2008/08/14/introducing-the-xmlpreloadedresolver.aspx
crawl-002
refinedweb
617
50.84
I have the following mapping in ObjectFactory.Initialize method: ObjectFactory.Initialize expression.For<IFoo>().Singleton() .Use<SomeFoo>() .Ctor<string>("url").Is(<fetch from config>) .Ctor<string>("username").Is(<fetch from config>) This ensures that my Ok, I have a singleton class GraphMaster which contains a number of system-wide values. I have a subclass GraphObject : GraphMaster which has graph specific data. By subclassing, I can access members of either the global class or subclass. And by using a singleton class, I can change the global variables anywhere and have them be reflected in all the subclasses. GraphMaster GraphObject : GraphMaster I have a service in my application which is a singleton.My application is being bloated with the use of spring framework. I am confused over to use the singleton service as 1: Plain Old Singleton [Access them statically when required] OR as a 2: Spring singleton bean. [Use DI to inject when required] Which approach is correct ? There is a pattern that I use from time to time, but I'm not quite sure what it is called. I was hoping that the SO community could help me out. The pattern is pretty simple, and consists of two parts: A factory method that creates objects based on the arguments passed in. Objects created by the factory. So far this is just a standard "factory" p I'm calling my custom factory that I created (PhotoServiceFactory), which is a singleton that allows me to get at a specific custom service type back (in this case FacebookService). FacebookService is also a singleton. In FacebookService I've exposed an instance of FacebookAlbumPhoto through a property. I did this because then I don't have to have a ton of the same code over and over again c I have the following error in my code Assignment has more non-singleton rhs dimensions than non-singleton This is the code: string =['d:facefaceffw' int2str(r) '_' int2str(Sel(nSelRow,t)) '.bmp']; A = imread(string); B = im2double(A); Train_Dat(:,:,s)=B; When I updated the code we got new err My goal ist to reference a function into an singleton/object body! # This result is my goal: var singletonObj_1 = (function () { return { custom_fn1 : function(){...}, custom_fn2 : function(){...} <<-- *But Imported }})(); So after importing, i am able to call I have two services, one that calls another. Both are marked as singletons as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]public class Service : IService And I set these up with a ServiceHost as follows: ServiceHost serviceHost = new ServiceHost(singleto I've tried putting the remote interface of another Singleton bean into another. However, the remote object will always be null. Is there any other way I could get around it? @Singletonpublic class SingletonBean1 implements SingletonBean1Remote { @EJB SingletonBean2Remote singletonBean2Remote; ... public SingletonBean1() { ... I started to develop my singleton class but I have a problem.What I want to do is have a search objects containing the values of the search form that I could use in several views.I want to have the ability to get the singleton in any view in order to perform the search or build the search form.So I have a set of values with a boolean for each to know if the variable has been i
http://bighow.org/tags/Singleton/1
CC-MAIN-2017-26
refinedweb
542
55.54
. You can easily download/install Aspose.Words for Java and Aspose.Words for Android via Java from Maven for evaluation. Free Trial The evaluation version is the same as the purchased one – the Trial version simply becomes licensed when you add a few lines of code to apply the license. The Trial version of Aspose.Words for Java and Aspose.Words for Android via Java without the specified license provides full product functionality, but inserts an evaluative watermark at the top of the document upon loading and saving and limits the maximum document size to a few hundred paragraphs. Temporary License If you wish to test Aspose.Words for Java and Aspose.Words for Android via Java without the limitations of the Trial version, you can also request a 30-day Temporary License. For more details, see the “Get a Temporary License” page. Purchased License After purchase, you need to apply the license file or include the license file as an embedded resource. This section describes options of how this can be done, and also comments on some common questions. A license is a plain text XML file that contains details such as product name, number of developers licensed, subscription expiry date, and so on. The file is digitally signed, so do not modify the file. Even inadvertent addition of an extra line break into the file will invalidate it. Aspose.Words JAR file - An embedded resource in the JAR is called Aspose.Words JAR - As a Metered License – a new licensing mechanism Often the easiest way to set a license is to place the license file in the same folder as Aspose.Words JAR and specify just the filename without the path. Use the SetLicense method to license a component. Calling SetLicense multiple times is not harmful, it just wastes processor time. Apply License Using a File or Stream Object When developing a class library, you can call SetLicense from the static constructor of your class that uses Aspose.Words. The static constructor will be executed prior to instantiating your class to ensure that the Aspose.Words license is installed correctly. Load a License from a File Using the SetLicense method, you can try to find the license file in the embedded resources or folder that contain the JARs of your application for further use. The following code example shows how to initialize a license from a folder: com.aspose.words.License license = new com.aspose.words.License(); license.setLicense("Aspose.Words.Java.lic"); Load a License from a Stream Object The following code example shows how to initialize a license from a stream using another SetLicense method: com.aspose.words.License license = new com.aspose.words.License(); license.setLicense(new java.io.FileInputStream("Aspose.Words.Java.lic")); Include the License File as an Embedded Resource A neat way to package a license with your application and make sure it will not be lost is to include it as an embedded resource. You can simply copy the LIC file to your project’s resource folder. Rebuilding the project should embed the .lic file into application .jar file. After that, you can apply for a license using the following code: License lic = new License(); lic.setLicense(Program.class.getResourceAsStream("Aspose.Words.Java.lic"));: Please note that you must have a stable Internet connection for the correct use of the Metered license, since the Metered mechanism requires the constant interaction with our services for correct calculations. For more details, refer to the “Metered Licensing FAQ” section. Changing the License File Name The license filename does not have to be “Aspose.Words.LIC”. You can rename it to your liking and use that name when setting a license in your application. “Cannot find license filename” Exception When you purchase and download a license, the Aspose website names the license file “Aspose.Words.LIC”. You download the license file using your browser. In this case, some browsers recognize the license file as XML and append the .xml extension to it, so the full file name on your computer becomes “Aspose.Words.lic.XML”. When Microsoft Windows is configured to hide extensions for known file types (unfortunately, this is the default in most Windows installations), the license file will appear as “Aspose.Words. LIC” in Windows Explorer. You will probably think that this is the real file name and call SetLicense passing it “Aspose.WordsLicense separately for each Aspose product that you use in your application. - Use the Fully Qualified License Class Name. Each Aspose product has a License class in its own namespace. For example, Aspose.Words has com.aspose.words.License and Aspose.Cells has com.aspose.cells.License class. Using the fully qualified class name allows you to avoid confusion as to which license applies to which product.
https://docs.aspose.com/words/java/licensing/
CC-MAIN-2022-27
refinedweb
797
57.47
java.util.*;interface Pet {void speak();}class Rat implements Pet {public void speak() { System.out.println("Squeak!"); }}class Frog implements Pet {public void speak() { System.out.println("Ribbit!"); }}public class InternalVsExternalIteration {public static void main(String[] args) {List<Pet> pets = Arrays.asList(new Rat(), new Frog());for(Pet p : pets) // External iterationp.speak();pets.forEach(Pet::speak); // Internal iteration}} The forloop represents external iteration and specifies exactly how it is done. This kind of code is redundant, and duplicated throughout our programs. With the forEach, however, we tell it to call speak(here, using a method reference which is more succinct than a lambda) for each element, but we don’t have to specify how the loop works. The iteration is handled internally, inside the forEach. This “what not how” is the basic motivation for lambdas. But to understand closures, we must look more deeply, into the motivation for functional programming itself.Functional Programming Lambdas/Closures are there to aid functional programming. Java 8 is not suddenly a functional programming language, but (like Python) now has some support for functional programming on top of its basic object-oriented paradigm. The core idea of functional programming is that you can create and manipulate functions, including creating functions at runtime. Thus, functions become another thing that your programs can manipulate (instead of just data). This adds a lot of power to programming. A purefunctional programming language includes other restrictions, notably data invariance. That is, you don’t have variables, only unchangeable values. This sounds overly constraining at first (how can you get anything done without variables?) but it turns out that you can actually accomplish everything with values that you can with variables (you can prove this to yourself using Scala, which is itself nota pure functional language but has the option to use values everywhere). Invariant functions take arguments and produce results without modifying their environment, and thus are much easier to use for parallel programming because an invariant function doesn’t have to lock shared resources. Before Java 8, the only way to create functions at runtime was through bytecode generation and loading (which quite messy and complex). Lambdas provide two basic features: More succinct function-creation syntax. The ability to create functions at runtime, which can then be passed/manipulated by other code. Closures concern this second issue.What is a Closure? A closure uses variables that are outside of the function scope. This is not a problem in traditional procedural programming – you just use the variable – but when you start producing functions at runtime it does become a problem. To see the issue, I’ll start with a Python example. Here, make_fun()is creating and returning a function called func_to_return, which is then used by the rest of the program:# Closures.pydef. I asked why the feature wasn’t just called “closures” instead of “lambdas,” since it has the characteristics of a closure? The answer I got was that closure is a loaded and ill defined term, and was likely to create more heat than light. When someone says “real closures,” it too often means “what closure meant in the first language I encountered with something called closures.” I don’t see an OO versus FP (functional programming) debate here; that is not my intention. Indeed, I don’t really see a “versus” issue. OO is good for abstracting over data (and just because Java forces objects on you doesn’t mean that objects are the answer to every problem), while FP is good for abstracting over behavior. Both paradigms are useful, and mixing them together has been even more useful for me, both in Python and now in Java 8. (I have also recently been using Pandoc, written in the pure FP Haskell language, and I’ve been extremely impressed with that, so it seems there is a valuable place for pure FP languages as well).
http://m.dlxedu.com/m/detail/5/433932.html
CC-MAIN-2018-30
refinedweb
649
54.73
09 November 2010 14:56 [Source: ICIS news] RIO DE JANEIRO (ICIS)--?xml:namespace> Brazilian producers were taking advantage of Cione was speaking on the sidelines of the Latin American Petrochemical Association (APLA) annual meeting. As a result of the low tariffs, Brazilian prices are often competitive with local material as well as with US and Asian imports, according to Colombian buyers. The tariff for low density polyethylene (LDPE) is 5%, while linear low density and high density PE (HDPE) tariffs are 1.95%. Polypropylene (PP) homopolymers pay 3.7% Logistics are not that favourable, considering that product must be shipped from production centres in For more on PE.
http://www.icis.com/Articles/2010/11/09/9408727/apla-10-braskem-focuses-on-colombia-market-with-new-office.html
CC-MAIN-2013-20
refinedweb
109
53.92
Sets and gets the value of the file creation mask. Standard C Library (libc.a) #include <sys/stat.h> mode_t umask (CreationMask) mode_t CreationMask; The umask subroutine sets the file-mode creation mask of the process to the value of the CreationMask parameter and returns the previous value of the mask. Whenever a file is created (by the open, mkdir, or mknod subroutine), all file permission bits set in the file mode creation mask are cleared in the mode of the created file. This clearing allows users to restrict the default access to their files. The mask is inherited by child processes. If successful, the file permission bits returned by the umask subroutine are the previous value of the file-mode creation mask. The CreationMask parameter can be set to this value in subsequent calls to the umask subroutine, returning the mask to its initial state. This subroutine is part of Base Operating System (BOS) Runtime. The chmod subroutine, mkdir subroutine, mkfifo subroutine, mknod subroutine, openx, open, or creat subroutine, stat subroutine. The sh command, ksh command. The sys/mode.h file. Shells Overview in AIX Version 4.3 System User's Guide: Operating System and Devices. Files, Directories, and File Systems for Programmers in AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs.
https://sites.ualberta.ca/dept/chemeng/AIX-43/share/man/info/C/a_doc_lib/libs/basetrf2/umask.htm
CC-MAIN-2022-40
refinedweb
216
58.38
We seek to explore the essential functions of Python objects and classes in this article. You’ll find out what a class is, how to make one, and how to use one in your application. Objects and Classes in Python Python is a computer language that focuses on objects. In contrast to procedure-oriented programming, object-oriented programming places a greater emphasis on objects. A collection of data, i.e., variables and methods (functions) that act on that data, is an object. On the other hand, a class is a blueprint for that item. A class can be compared to a home’s rough sketch (prototype). It covers all of the floors, doors, and windows, among other things. We construct the house based on these descriptions. The item in this illustration is a house. We can come up with various objects from a given class, just as we can make many houses from a house’s plan. A class instance is sometimes known as an object, and producing this object is known as instantiation. Consider the case where you want to keep track of the number of cows with various characteristics such as breed and age. The first list element maybe the cow’s breed, while the second element may be age. What if there are more than one hundred different cows? How do you go about telling which one is supposed to be which? What if you wanted to give these cows other abilities? Essentially, there is no easy way, which is precisely why classes are required. A class is responsible for creating a user-defined data structure with its data members and member methods. The latter helps access and utilization through the establishment of the class instance. In essence, a class is similar to an object’s blueprint. Some considerations for the Python class: - The term class is used to create classes. - The variables that make up a class are known as attributes. - The dot (.) operator can be used to access attributes that are always public. For example, Myclass.Myattribute OOP Terminology Overview - A class easily stands out as a user-defined prototype for an object that defines a set of qualities that all objects in the class must have. Data members, including class variables, instance variables, and methods, are the attributes accessed using dot notation. - Class variable: A class’s variable is a variable that all instances of the class share. It is a class variable or instance variable that holds data linked with a class, and its object is a data member. Class variables are defined within a class but outside of any class’s methods. Instance variables are used more frequently than class variables. - Overloading: The assignment of many behaviors to a single function is known as function overloading. The operation is different depending on the sorts of objects or arguments used. - Instance variable: A variable defined within a method that only applies to the present instance of a class. - Inheritance: The transfer of a class’s characteristics to other classes derived from it is known as inheritance. - Instance: An instance of a class is a single object of that class. An instance of the class Circle is, for example, an object obj that belongs to the class Circle. - Instantiation: Instantiation is the process of creating a class instance. - Method: A method is a type of function defined in the definition of a class. - Object: An object is a one-of-a-kind instance of a data structure described by its class. Data members comprising of class variables and instance variables and methods make up an object. - Operator overloading: The assignment of multiple functions to a single operator is known as operator overloading. Creating a Python Class Class definitions are synonymous with beginning with the class keyword in Python, similar to function declarations starting with the def keyword. The docstring is the first string inside the class, and it contains a brief description of the class. It is strongly recommended; however, it is not required. # class definition example class CodeClass: '''This is a docstring. I have created a code class''' pass A class declares all of its attributes in a new local namespace. In addition, data or functions can be used as attributes. It also contains unique properties that start with double underscores. For example, doc returns the class’s docstring. A resultant novel class object with a similar name is produced when defining a class. In addition, we may use this class object to access the various characteristics and create new objects of that class. class Employee: "This is an Employee class." age = 32 def greet(self): print('How are you?') # Output: 32 print(Employee.age) # Output: <function Employee.greet> print(Employee.greet) # Output: "This is an Employee class." print(Employee.__doc__) Objects of a Class A class can be equated to a blueprint, whereas an instance is a class clone containing actual data. A Class’s instance is an Object. The latter is no longer a concept; it’s a living creature, like a seven-year-old Jersey cow. You can have a lot of cows to make a lot of different scenarios, but without the class to guide you, you’d be lost and have no idea what information is needed. The following elements make up an object: - state: The characteristics of an object represent the state. It also reflects an object’s attributes. - Behaviour: The behavior of an object is represented by its methods. It also represents an object’s reaction to other objects. - Identity: It gives a thing a unique name and allows it to communicate with other objects. Creating objects In Python We saw how to use the class object to retrieve various characteristics. It can also be used to create new object instances of that class. The latter is called instantiation. The process of creating an object is comparable to calling a function. laborer = Employee() It will create a new laborer object instance. Using the object name prefix, we may access the attributes of objects. In addition, data or methods can be used as attributes. An object’s methods correspond to the class’s functions. Because Employee.greet is a function object (class attribute), it will be a method object. class Employee: "This is an Employee class." age = 32 def greet(self): print('How are you?') # create a new object of Person class labourer = Employee() # Output: <function Employee.greet> print(Employee.greet) # Output: <bound method Employee.greet of <__main__.Employee object>> print(labourer.greet) # Calling object's greet() method # Output: Hello labourer.greet() You may have noticed the self parameter in the class’s function declaration, but we just called the method laborer.greet() is a function that accepts no arguments. It was still functional. It is the case because the object is supplied as the first argument whenever it calls its method. As a result, laborer.greet() becomes Employee.greet(). Calling a method with an argument list of n equals the corresponding function with an argument list generated by putting the method’s object before the first argument. As a result, the object itself must be the first argument of the class function. It is commonly referred to as “self.” It can be titled in any way you choose. However, we strongly advise you to stick to the norm. The self In the method definition, class methods must have an additional initial parameter. The self parameter refers to the current instance of the class, and it is used to access class-specific variables. We don’t specify a value for this parameter; Python does. We still need one parameter if a method doesn’t take any arguments. In C++, this is similar to this pointer, and in Java, this is similar to this reference. Python automatically converts myobject.method(arg1, arg2) into MyClass.method(myobject, arg1, arg2) when we invoke a method of this object as myobject.method(arg1, arg2) — this is what the special self is for. It doesn’t have to be called self; you can call it whatever you like, but it must be the first parameter in any class function: class Employee: def __init__(selfName, name, age): selfName.name = name selfName.age = age def myfunc(xxy): print("Hello Codeunderscored, my name is " + xxy.name) emp_one = Employee("Mark", 19) emp_one.myfunc() The statement “pass.” Class definitions by default cannot be empty, but if you have an empty class definition for some reason, add the pass statement to avoid an error. class Employe: pass Python constructors Special functions are class functions that begin with a double underscore and have a unique meaning. The init() function is of particular relevance. This particular function is invoked when a new object of that class is instantiated. Constructors are used to set the state of an object. In addition, a constructor, like methods, includes a collection of statements (i.e., instructions) that are performed when an object is created. The constructors in C++ and Java are identical to the init method. It starts running as soon as a class object is created. The method can be used to do any object initialization. Constructors are another name for this type of function in Object-Oriented Programming (OOP). We usually utilize it to set up all manner of variables. class AdvancedNumber: def __init__(self, r=0, i=0): self.real = r self.img = i def get_data(self): print(f'{self.real}+{self.img}j') # Create a new AdvancedNumber object adNum = AdvancedNumber(4, 9) # Call get_data() method # Output: 4+9j adNum.get_data() # Create another AdvancedNumber object # and create a new attribute 'attr' num _val = AdvancedNumber(8) num_val.attr = 5 # Output: (8, 0, 5) print((num_val.real, num_val.imag, num_val.attr)) # but c1 object doesn't have attribute 'attr' # AttributeError: 'AdvancedNumber' object has no attribute 'attr' print(adNum.attr) We created a new class to represent complex numbers in the preceding example. It has two functions: init() for initializing variables (defaults to zero) and get_data() for appropriately displaying the number. It’s worth noting that characteristics of an object can be created on the fly in the previous stage. For object num_val, we generated and read a new attribute called attr. However, for object adNum, this does not create that attribute. Instance and Class Variables Class variables are for properties and methods shared by all class instances, whereas instance variables are for data unique to each instance. Class variables are variables whose value is assigned in the class, but instance variables are variables whose value is set inside a constructor or method using self. Using a constructor to define an instance variable. # program showing the variables with the value assigned in the class declaration, are class variables and # variables inside methods and constructors are instance variables. # Class for Cow class Cow: # Class Variable animal = 'cow' # The init method or constructor def __init__(self, breed, color): # Instance Variable self.breed = breed self.color = color # Objects of Cow class jersey = Dog("Jersey", "black") guernsey = Dog("Guernsey", "brown") print('Jersey details:') print('Jersey is a', jersey.animal) print('Breed: ', jersey.breed) print('Color: ', jersey.color) print('\nGuernsey details:') print('Guernsey is a', guernsey.animal) print('Breed: ', guernsey.breed) print('Color: ', guernsey.color) # variables in a class accessed using the class 's name print("\nAccessing class variable using class name") print(Cow.animal) Using the standard technique to define an instance variable # program for showing that we can create instance variables inside methods # Class for Cow class Cow: # Class Variable animal = 'cow' # This is the constructor method def __init__(self, breed): # declaration of an instance variable self.breed = breed # Adds an instance variable def setColor(self, color): self.color = color # Retrieves instance variable def getColor(self): return self.color # Driver Code for Cow class jersey = Cow("Jersey") jersey.setColor("black") print(jersey.getColor()) Removing Attributes and Objects The del statement helps delete any attribute of an object at any time. To see the results, run the following command in the Python shell. num_one = ComplexNumber(2,3) del num_one.img num_one.get_data() del ComplexNumber.get_data num_one.get_data() # Using the del statement, we can even delete the object itself. c_num = ComplexNumber(1,3) del c_num c_num It’s a little more complicated. When we use c_num = ComplexNumber(1,3), we construct a new instance object in memory with the identifier c_num. The command del c_num removes this binding and deletes the name c_num from the relevant namespace. On the other hand, the object remains in memory and is immediately destroyed if no other name is assigned. Garbage collection is the process of automatically destroying unreferenced objects in Python. Conclusion A class is a blueprint or prototype that a given user first defines, and it helps build things. Essentially, classes allow you to group data and functionality. A new class introduces a new type of object, allowing for the creation of new instances of that type. Each class instance can have its attributes to keep track of its status. Class instances have methods for changing their state specified by their respective class.
https://www.codeunderscored.com/python-classes-and-objects-with-examples/
CC-MAIN-2022-21
refinedweb
2,172
58.89
View all headers Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!newsfeed.stanford.edu!newsfeed.news.ucla.edu!news-hog.berkeley.edu!ucberkeley!agate.berkeley.edu!agate!not-for-mail From: lvirden@yahoo.com (Larry W. Virden) Newsgroups: comp.lang.tcl.announce,comp.lang.tcl,comp.lang.perl.tk,comp.answers,news.answers Subject: comp.lang.tcl Frequently Asked Questions (Mar 05, 2005) (2/6) Followup-To: comp.lang.tcl Date: Tue, 12 Apr 2005 23:06:50 +0000 (UTC) Organization: University of California, Berkeley Lines: 3505 Sender: lvirden@yahoo.com Approved: tcl-announce@mitchell.org,news-answers-request@MIT.Edu Message-ID: <pgpmoose.200504121601.2988@despot.non.net> Reply-To: lvirden@yahoo.com (Larry W. Virden) NNTP-Posting-Host: alumni.eecs.berkeley.edu X-Trace: agate.berkeley.edu 1113347210 83820 128.32.47.240 (12 Apr 2005 23:06:50 GMT) X-Complaints-To: usenet@agate.berkeley.edu NNTP-Posting-Date: Tue, 12 Apr 2005 23:06:50 +0000 (UTC) Summary: A regular posting of the comp.lang.tcl Frequently Asked Questions (FAQ) and their answers. This is the second of six parts. This part covers Internet resources. Keywords: tcl, extended tcl, tk, expect, mailing lists, WWW sites Originator: lvirden@yahoo.com X-Url: X-Auth: PGPMoose V1.1 PGP comp.lang.tcl.announce iQCVAwUAQlxTcMVCYQpvzJ9ZAQFqDgQAgPF/Nsih1SaVDGtrvWVcG+mlfobHrkaQ 4UYd6YyhQsi5hXJt834t4yY2GZN3fQK1/GZE5qLSx6RAhpKYd1zsjO9iFPw6T06+ R7JgSsbNxXWBxBKFMfLMeJ1/woPh6jKdENS9BVPCXo/KWnzp+rJEnE0+AKMkCGIg Rw72PVIcaQg= =PoeX User-Agent: slrn/0.9.7.4 (Linux) Xref: senator-bedfellow.mit.edu comp.lang.tcl.announce:2760 comp.lang.tcl:256662 comp.lang.perl.tk:38898 comp.answers:60204 news.answers:288591 View main headers For more information concerning Tcl (see "part1"), (see "part3"), (see "part4"), (see "part5") or (see "part6"). Index of questions: VII. Where can I find information relating to Tcl on the Internet? VIII. Are there any mailing lists covering topics related to Tcl/Tk? IX. On what sites can I find the FAQ? X. On what sites can I find archives for comp.lang.tcl? End of FAQ Index ---------------------------------------------------------------------- From: FAQ General information Subject: -VII- Where can I find information relating to Tcl on the Internet? 000. The following newsgroups often are likely locations for Tk extension related discussions: <URL: news:comp.lang.tcl >, <URL: news:comp.lang.perl.tk >, <URL: news:comp.lang.python >, <URL: news:comp.lang.misc >. Announcements about Tcl or Tk related code releases may be seen in <URL: news:comp.lang.tcl.announce >, <URL: news:comp.archives >, <URL: news:comp.windows.x.announce >, and <URL: news:comp.lang.perl.announce > as well. Discussions concerning porting of Tcl and/or Tk into new OSes occasionally are found in newsgroups such as <URL: news:comp.os.linux.development.apps >, <URL: news:comp.sys.mac.programmer.help >, <URL: news:comp.windows.x >, <URL: news:comp.sys.next.software >, and <URL: news:comp.unix.bsd.freebsd.misc >. Discussions relating to specific applications can be found in newsgroups such as <URL: news:alt.comp.tkdesk >. Foreign language discussions concerning Tcl and Tk can be found in <URL: news:maus.os.linux >, <URL: news:maus.os.linux68k >, <URL: news:de.comp.lang.tcl >, <URL: news:fr.comp.lang.tcl >, and <URL: news:fj.lang.tcl >. 001. The introductory papers on Tcl and Tk by Dr. J. Ousterhout are available at <URL: >, <URL: >, <URL: >. (The last of these files is the contents of Figure 10 of the Tk paper). The examples from the Ousterhout book are available in one large file as <URL: >. A series of PostScript slides used in an introduction/tutorial on Tcl and Tk at several X and Usenix Conferences are available as <URL: >. Dr. Ousterhout has written an engineering style guide that describes the coding, documentation, and testing conventions that are used in Tcl and has made it available to other Tcl/Tk developers. It is located at <URL: >. Feedback is welcome, but specifics concerning actual conventions are unlikely to change. Primarily there is room for changes on the presentation itself, as well as additional conventions which should be present but are not. Notes pointing to a conflict between a stated convention and Tcl or Tk base code are of interest. Send There is also pointers to slide presentations made at the Symposium on Very High Level Languages and papers concerning intelligent agents on the Internet. Pointers to various Tcl applications (such as the Tcl Plugin, SpecTcl/SpecJava, WebTk), as well as FAQs and tutorials about these applications, can be found on the <URL: > site. A page comparing Tcl to Visual Basic, Perl and Javascript can be found at <URL: >. A series of "How To" articles are also available at TDX. See <URL: > for pointers to articles on using TclPro, using Tcl 8.1 regular expressions and internationalization features, creating tcl object commands, the option command, namespaces, tcl threading models, and more. 002. PostScript versions of published papers by <URL: mailto:libes@nist.gov > (Don Libes) relating to Expect can be found on the net. (See "bibliography/part1") for details about the published papers. <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > Some pointers to information concerning the Exploring Expect book are <URL: >, <URL: >, <URL: >. Also, see <URL: > for the WWW home of Expect, as well as other tools that Don has written. A web page for Don's CGI library can be found at <URL: >. Also, someone has taken the documentation for Expect and reformatted it so that it can be installed on a Palm Pilot. Search <URL: > for the current version. 003. A set of PostScript files collected for the Tcl 93 workshop proceedings is available as <URL: > and contains the PostScript for a number of the papers and slides presented at this workshop. 004. A second set of PostScript files consisting primarily of overhead slides is available as <URL: > 005. The Tcl Compiler (TC) Frequently Asked Questions by Adam Sah <URL: mailto:asah@cs.Berkeley.EDU > is a document describing TC, which is a work in progress. Contact Adam for details. 006. A compact yet detailed overview of Tcl, Tk and Xf is available thanks to the graciousness of <URL: mailto:theobald@fzi.de > (Dietmar Theobald) at <URL: > (compressed format) and <URL: > (gzip format). More on the entire OBST project, which is an object-oriented database interface called tclOBST, can be found at the <URL: > page. It is called Tcl/Tk in a Nutshell, was last updated in July of 1993, and is part of the STONE structured open environment. 007. Softcopy of an article about PhoneStation, a tool using Tk and Tcl presented at the 1993 Winter USENIX Conference is available as <URL: >. 008. A paper on Radar Control software which uses Tcl, by J. H. VanAndel is available in PostScript form via the experimental web server <URL: >. 009. Mark A. Harrison <URL: mailto:markh@usai.asiainfo.com > has written a Tk/Tcl information sheet, providing an introductory look at why one might want to use Tcl and Tk. Version 1.0 was posted to comp.lang.tcl as <URL: //groups.google.com/groups?selm=news:278ml0$457@news.utdallas.edu" target="new">news:278ml0$457@news.utdallas.edu >. Contact him for a copy. Mark also gave a paper <URL: > at the O'Reilly Open Source Conference on how Tcl/Tk is being used in China, and how easy Tcl/Tk 8.2 made things. 010. Cedric Beust <URL: mailto:beust@modja.inria.fr > has written a short article giving guidelines on where to start when writing a Tcl extension. You may find it at <URL: >. It is titled "Writing a Tcl extension: the Toocl example" and describes the work done on the Tooltalk extension. The paper is dated August 10, 1993. 011. Douglas Pan and Mark Linton <URL: mailto:linton@marktwain.rad.sgi.com > have written the paper ``Dish: A Dynamic Invocation Shell for Fresco''. It is available at <URL: >. The FAQ as well as some other papers are in <URL: >. Fresco is an X Consortium project - non-members interested in contributing to the effort should contact Mark Linton. 012. The World-Wide Web Virtual Library now has a page on Tcl and Tk. You can find it at <URL: >. It points off to a number of other resources, though certainly not all of them. 013. A WorldWideWeb (WWW) resource for Ada Tcl is available as <URL: >. 014. 015. A WWW resource for what appears to be a German introduction/tutorial on Tcl and Tk is at <URL: >. 016. A WWW resource describing the HTML to Tcl preprocessor is available at <URL: >. 017. See <URL: > for a WWW directory of services relating to Tcl. 018. A WWW resource discussing Tk/Tcl style issues is available at <URL: > 019. A WWW resource discussing Visual Numerics PV-Wave with Tk/Tcl is available at <URL: >. 020. Cameron Laird <URL: mailto:Cameron@Lairds.com > has a number of extremely useful WWW pages relating to Tcl. For instance, one provides assistance to users in resolving common linking problems when building Tcl. <URL: >. Others covering a wide variety of subjects, such as Tcl compilers <URL: >, server side WWW Tcl scripting, and many others, are available beginning at <URL: >. as well as others that you can find from his home page. <URL: > covers web servers with tcl embedded. For instance, see <URL: >. for pointers to various binaries. Note that Cameron has pages concerning Tcl 8.0 migration, pointers to Tcl Workshop reviews and spin offs, and many other topics - too many to list here. Cameron has also written a number of articles in SunWorld, including this <URL: > article discussing the pros and cons of the major scripting languages, or <URL: > which discusses Tk and Unicode support. He also provides <URL: > which begins an effort to provide a variety of 'good' tcl code examples. <URL: > contains pointers to a varity of tutorials. <URL: > contains information regarding Tcl on Windows. <URL: > provides a brief overview of how to get started with Jacl and TclBlend. <URL: > is an article written by Cameron about XML and web service programming in Tcl. <URL: > and <URL: > point to several articles of potential interest to Tcl-ers. 021. Nat Pryce <URL: mailto:np2@doc.ic.ac.uk > began a project to collect Tcl programming idioms or patterns. See <URL: > for the original root of this document. He has now moved the data to the more generic <URL: > which deals with various scripting languages, but continues providing Tcl specific idioms in its own sub-tree. <URL: > discusses how to set up Windows environment to launch Tcl applications. 022. A set of WWW resources discussing the Fermilab's use of Tcl within a massive data manipulation package at one time was found at <URL: > <URL: > <URL: > as well as various pages underneath this set of homes. The problem is to digitally image the entire night sky in five colors, and the entire top layer of the data reduction package is based on Tcl. 023. A soft file containing notes on Tcl and quoting philosophy can be found at <URL: >. 024. There are references to Tcl and Tk (and perhaps other Tcl based interpreters) within The Catalog of Free Compilers and Interpreters <URL: > and The Language List <URL: >. 025. The first Tcl 'home page' available via the WWW URL was at sco.com . It appears to be gone now. Thanks to Mike Hopkirk <URL: mailto:hops@sco.com > for the time, energy and resources for having made this available. Note that one of the older versions of this page is also available for those behind a firewall as <URL: >. This WWW link used to be mirrored at numerous locations. The info on this page, the last I checked, was 2-3 years out of date, but might be useful for someone looking for tips for older versions of tcl. 026. A Tcl based chat room called Felix is avail at <URL: >. 027. The PLEAC project aims to re-implement the solutions presented in the O'Reilly Perl Cookbook in other programming languages. Tcl is represented - but only a small degree. See <URL: > and contribute where you can. 028. One develper's details on building a static version of wish are outlined at <URL: > 029. Documentation on the Tcl processing of WWW's server Common Gateway Interface (known as CGI) can be found at <URL: >. 030. Mark Roseman <URL: mailto:roseman@cpsc.ucalgary.ca > prepared a brief comparison between Tcl/Tk and the Interviews C++ toolkit. It is available via email by contacting him. Mark kept a WWW page going concerning Macintosh Tcl/Tk related projects. It used to be at <URL: >, however that currently doesn't seem to be working. 031. Information about the SIMON Mosaic hotlist management tool can be found at <URL: >. 032. Information about Fritz Heinrichmeyer's experimental Schematic SPICE interface, tkSketch, is available from <URL: >. Fritz is using STk for further development of this tool. 033. Information about ical is now accessible from <URL: >. 034. Wade Holst <URL: mailto:wade@cs.ualberta.ca > at one point provided HyperTcl, a WWW page providing various views on info available to the Tcl community. Unfortunately, it has grown out of date. It can still be found at <URL: >. 035. An interesting site is <URL: >, which is a database registry for various domains of topics. Don Libes <URL: mailto:libes@nist.gov > has created a Tcl domain where one can, for instance, do a search for rand and find pointers to various implementations of random number generators for Tcl. The NICS paper Don presented at one of the Tcl conferences is <URL: >. See also the news article <URL: > for an explanation Don posted to <URL: news:comp.lang.tcl >. A domain has also been created at the NIST Identifier Collaboration Service for Tcl object types. 036. The Linux Gazette, found at WWW <URL: >, has mentioned Tcl or Tk in at least Issues 9, 10, 11. 037. A Tk reference card can be found at <URL: >. This TeX and PostScript version of a Tk 3.3 card was provided by Paul Raines <URL: mailto:raines@slac.stanford.edu >. A home page for tkmail can be found at <URL: >. 038. A good document on Xauth is available at <URL: > or <URL: >. 039. The documentation for the Xf command is available in European page format as <URL: > as well as United States page format as <URL: >. 040. Vivek Khera <URL: mailto:khera@cs.duke.edu > has written a primer on setting up your environment for xauth (by default a requirement under Tk 3.3) in the document <URL: >. 041. A list of MPEG animations, done with Tcl scripts using TSIPP can be found at <URL: >. 042. Project DA-CLOD (Distributedly Administered Categorical List of Documents) allows the Web participants to set up organizational pages. So a Tcl page has been set up. Check out <URL: > or go directly to Tcl by way of <URL: >. 044. A home page for a map marking program can be found at <URL: >. 045. The Scientific Applications on Linux (SAL) web site is a collection of information and links to software that will be of interest to scientists and engineers. The broad coverage of Linux applications will also benefit the whole Linux/Unix community. It includes a few Tcl entries - thought not many that are truly scientific in nature. <URL: >. 046. Clif Flynt's WWW page <URL: > compares a number of the static tcl code validity testers that are available. The contents of his poster session from the 1997 Tcl/Tk workshop in Boston, found at <URL: >, discuss a set of coding conventions to help reduce the pain of maintaining Tcl. 047. Documentation for the DART project can be found at <URL: >. There may be some problem with this server. 048. NeoSoft has a TclX home page - see <URL: >. They also have a home page for NeoWebScript, an extension to the Apache HTTP server to allow adding features via tcl. See <URL: >. See also the following: <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > 049. An overview page for the program currently known as tkWWW is <URL: >. A status page for tkWWW from CERN is found at <URL: > Internals information can be found at <URL: gopher://gopher.slac.stanford.edu/h0/WWW%20Documentation/TkWWWDoc/internals.html > 050. An example of the output from TreeLink can be found at <URL: >. TreeLink is a Tk/Tcl program which draws a hypergraph of links from an HTML document. 051. The documentation for the ILU software environment, which enables systems to be written which communicate between many different languages, including Tcl, can be found at <URL: >. 052. Huayong YANG <URL: mailto:yang@twain.ucs.umass.edu > in <URL: //groups.google.com/groups?selm=news:2q1iko$8cj@nic.umass.edu" target="new">news:2q1iko$8cj@nic.umass.edu > wrote a review of Tcl and the Tk Toolkit. 053. A page to locate the various versions of Wafe can be found at <URL: >. Wafe's home page can be found at <URL: >. 054. A draft paper titled "Kidnapping X Applications" is available as a part of the TkSteal tar file. It is authored by Sven Delmas and discusses the use of the TkSteal package to integrate existing X applications into a Tcl/Tk based program without having to make changes to the X application. 055. A page dedicated to the new HTML editor tkHTML used to be found at <URL: >. It is now missing. 056. A WWW section for Hdrug , an environment to develop logic grammars for natural languages, is available at <URL: >. It uses ProTcl and TkSteal. 057. The HTML slides and demo pictures for Patrick Duval's talk in New Orleans titled ``Tcl-Me, a Tcl Multimedia Extension'' can be viewed at <URL: > and are available as a tar file at <URL: >. 058. A set of HTML pages for the scotty and tkined applications have been created. They can be found at <URL: > and <URL: >. 059. An archive for the distributed processing incr tcl discussion may be found at <URL: gopher://nisp.ncl.ac.uk/11/lists-a-e/distinct/ >. 060. A copy of the dynamic loading of code strategy paper Kevin B. Kenny <URL: mailto:kennykb@acm.org > presented at the Tcl 94 workshop is accessible on WWW as <URL: >. 061. Terry Evans <URL: mailto:tevans@cs.utah.edu > is coordinating work on a tcl/tk interface to gdb. Send him email if you would like to help out. 062. The HTML home page of Jonathan Kaye <URL: mailto:kaye@linc.cis.upenn.edu >, <URL: >, contains a pointer to lisp2wish, a package that allows a Tcl/Tk process and LISP process to synchronously communicate. 063. The following are a series of references to papers relating to the Safe TCL package. <URL: > <URL: > <URL: > 064. A review of Tcl and the Tk Toolkit appeared in misc.books.technical on May 2, 1994 as Message-ID: <URL: news:2q1iko$8cj@nic.umass.edu > by <URL: mailto:yang@twain.ucs.umass.edu > (Huayong YANG) who recommended the book to X window system programmers. 065. Mark Eichin <URL: mailto:eichin@cygnus.com > has a HTML page in which he describes a Tcl random number generator. See <URL: > for details. See <URL: > for pointers to a graph editor and a dialog box set of routines. At <URL: > you will find the code to make dialog boxes. 066. The ftp address for a Quick Reference TeX guide, updated recently to Tcl 7.3 is <URL: >. Many thanks to <URL: mailto:Jeff.Tranter@software.mitel.com > (Jeff Tranter) for contributing it. 067. PostScript versions of the man pages were provided by <URL: mailto:adrianho@nii.ncb.gov.sg > (Adrian Ho). The addresses for these are <URL: > <URL: > <URL: > 068. A series of papers concerning GroupKit are available as <URL: > <URL: > and <URL: >. An html page is available at <URL: >. 069. Documentation concerning the DejaGnu Testing Framework can be found at <URL: >. 070. A very elementary introduction/tutorial to Tk 3.6 can be found at <URL: >. It is being written by <URL: mailto:David.Martland@brunel.ac.uk > (Dr. David_Martland). 071. Another new Tcl/Tk topic area is <URL: >. 072. The documentation for the Object Oriented Graphics package GOOD can be viewed at <URL: >. 073. <URL: mailto:slshen@lbl.gov > Sam Shen's WWW page has some useful Tcl related items. For instance, a demo of the NArray (numeric array) extension can be seen by pointing a forms-capable WWW browser at <URL: >. One can also get Sam's SNTL Tcl support library at <URL: >. 074. The source code from the article "A Tutorial Introduction to Tcl and Tk" by <URL: mailto:gam@lanl.gov > (Graham Mark) in Issue 11 (July, 1994) of _The X Resource_, can be found at <URL: > or on one of the ORA mirror sites. This is for Tk 3.6. 075. Brent Welch now works at Interwoven <URL: mailto:brent.welch@interwoven.com >. He has a web page at <URL: > for his book, Practical Programming in Tcl and Tk which is published by Prentice Hall. The errata for Brent's book can be found at the book's web site. Brent's home page is <URL: >. At his home page, you will find pointers to Exmh, a Tk interface to MH that Brent has written. 076. The code from the article comparing MetaCard, dtksh and Tcl/Tk from Issue 11 (July, 1994) of _The X Resource_ can be found at <URL: >. 077. A WWW home page for Collaborative Biomolecular Tools (CBMT) can be found at <URL: >. These tools consist at a minimum of a Biomolecular C++ class library, a library of filters and scripts in many languages, including Tcl, GUI components in Tk and possibly other GUI languages, as well as other data. Read the page for more details. 078. The first Internet TclRobots Challenge was held on September 30, 1994. <URL: mailto:tpoindex@nyx.net > (Tom Poindexter) was the official judge. The winner was Jack Hsu <URL: mailto:jh@cs.umd.edu > with Honorable Mention going to Lionel Mallet <URL: mailto:Lionel.Mallet@sophia.inria.fr >, Stephen O. Lidie <URL: mailto:lusol@Lehigh.EDU >, and Motonori Hirano <URL: mailto:m-hirano@sra.co.jp >. The results can be seen at <URL: >. The results from the second challenge can be found at <URL: >. 079. J.M. Ivler has provided <URL: > as a WWW based package registration tool. In this way, authors can notify the Tcl community as to relevant software. 080. The WWW NNTP page for comp.lang.tcl is found at <URL: comp.lang.tcl"> >. 081. The WWW home page for the AudioFile package, which has a number of Tcl based clients, can be found at <URL: >. 083. A technical report describing the use and implementation of tkSather is available as <URL: >. Other information concerning Sather and Tk can be found at <URL: >. 084. A home page for the Teaching Hypertools series of tools is now available at <URL: >. This series of tools is intended to be used to add new features to existing running Tk tools. An extended editor, designed to cooperate with the teacher hypertools, is described at <URL: >. 085. The home page for the Tcl question and answers FAQ can be found at <URL: >. It is maintained by <URL: mailto:jmoss@ichips.intel.com > (Joe V. Moss). 086. A paper from the 1997 Austrailian WWW Technical Conference titled "Scripting the Web With Tcl/Tk" by Steve Ball <URL: mailto:Steve.Ball@tcltk.anu.edu.au > can be found at <URL: >. 087. A ProTCL WWW page (describing the Prolog to Tcl/Tk interface) can be found by browsing <URL: >. 088. A Work In Progress report from SAGE-AU'94 concerning cpumon can be found at <URL: >. Note that at one point, there were some missing screen dumps from the paper, but it should be updated when the author replaces the images. 089. WWW documentation for the Portable Tk project can be found at <URL: >. This project's goal is to provide proof of concept to the idea of creating a version of Tk which is portable between X, Windows, MacOS, AmigaDOS, and OS/2. 090. A WWW input form for feedback on Jon Knight's TCL-DP with Multicast IP can be found at <URL: >. 091. The SCOP command is a program which drives Mosaic and rasMol. See <URL: > for details. 092. An article as to why one programmer believes that Tcl use does not scale to larger projects, see <URL: > 093. A WWW page which describes a Tcl frontend for processing WWW queries and forms can be found at <URL: >. 094. A WWW page describing an [incr tcl] widget base class can be found at <URL: >. It is by <URL: mailto:np2@doc.ic.ac.uk > (Nat Pryce). 095. <URL: mailto:dpgerdes@europa.ftc.scs.ag.gov > (David Gerdes) has made available a set of black and white slides that he used to teach a course on Tcl and Tk, with an emphasis on Tk 3.6. They can be found at <URL: >. They are packed 4 per page. If anyone wants the originals he has offered to put them there also. There are also some trivial scripts designed to get people started. 096. <URL: mailto:wayne@icemcfd.com > (Wayne A. Christopher) has begun a WWW page with pointers to usenet and other articles comparing Tcl and its extensions to other language systems. You can find this at <URL: >. At this time, there are comparisons between tcl/lisp/python, a discussion of Perl versus Tcl, articles by Stallman, Ousterhout and Throop regarding the use of Tcl in the FSF, and a critical review of stk. More articles will be added as folk make contributions. Another WWW page, maintained by <URL: mailto:glv@utdallas.edu > (Glenn Vanderburg), is at <URL: > and deals with a series of selected responses to the Stallman flame war of GNU vs Tcl which occured during 1994. Two other Tcl related pages can be found at <URL: > and <URL: >. 098. A WWW page to the tcl archives at luth.se can be found at <URL: >. 099. A WWW page describing the interface between Perl 4.x and Tk can be found at <URL: >. 100. While not directly supporting Tcl, the WWW page at <URL: > describes an X11 version of a simulation of SGI's GL under X11. You might try this with the Tcl/Tk OpenGL interfaces. 101. Most of the papers from the Tcl 94 workshop can be found at <URL: >. Also, a few papers and slides did not make it into the above file. They can be found at <URL: > <URL: > <URL: > <URL: >. 102. The PostScript version of the Master's thesis by Adam Sah <URL: mailto:asah@cs.Berkeley.EDU > can be found at <URL: >. <URL: >. 103. A PostScript version of the paper on Rush, the Tcl like language by Adam Sah <URL: mailto:asah@cs.Berkeley.EDU > and John Blow can be found at <URL: > as well as <URL: > 104. An Internet commercial company is using software based on Safe-Tcl. An index to their technical information can be found at <URL: >. 105. A home page for YART/VR can be found by looking at <URL: >. 106. A readme for the Phoenix WYSIWYG HTML editor can be found at <URL: >. It is based on tkWWW. Also see <URL: >. 107. The user guide for a multigrid galerkin hierarchical adaptive triangles solution to second order linear elliptic partial equations, which uses Tk to display graphical results, can be found at <URL: >. 108. A home page for an integration of Safe-Tcl/Tk and Mosaic's CCI API can be found <URL: >. 109. Some summary notes on the Tcl Birds of a Feather session at the January 1995 USENIX session can be found at <URL: >. 110. A page of pointers to various Tcl/Tk programs and extensions written by Dan Wallach (such as TkLayers, TkPostage and TkGLXAux) can be found at <URL: >. 111. An HTML version of the TclCommandWriting man page that comes with TclX has been made available on the WWW at <URL: >. This page explains the C API to Tcl, providing an introduction/tutorial on writing Tcl extensions. 112. A new server is available and serving up SuperTclTk. It can be found at <URL: > during GMT 17:00-9:00 . 113. Full Oracle 9i documentation about Tcl can be found at <URL: > 114. A preliminary, older draft of a thesis detailing work on the use of Tcl and Tk in intelligent agents can be found at <URL: >. More information should be forthcoming in the months ahead. The software, without a lot of good documentation, could possibly be available from the contact of Laurent Demailly <URL: mailto:dl@demailly.com >. <URL: > details a list of tools written using Tcl, written by Laurent. Note in particular the WWW related tools mentioned on this page - there is even a single process multi-tasking Tcl http server. An Anonymous Proxy HTTP server written in Tcl is accessible at <URL: >, with the source at <URL: >. Laurent also speculates about a smaller Tcl-look alike language more suitable for embedding on devices, etc. See <URL: >. 115. The documentation for OSE, a set of tools for C++ development which includes a class to provide integration of Tk with a more comprehensive C++ based poll/select event handling mechanism, can be found at <URL: >. 116. The Coral deductive database home page is <URL: >. There is a Tk client which can interact with a Coral server. There is also a Tcl shell with Coral database commands, and an explanation tool. 117. At <URL: > you will find the home page for Mobal, which is a data mining system which has a Tk GUI interface. 118. Some published papers relating to Tcl can be found at the following location <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > 119. A pointer to a paper discussing Object Tcl is <URL: >. 120. A pointer to <URL: mailto:derijkp@reks.uia.ac.be > (Peter.DeRijk)'s page on Tcl is <URL: >. 121. Pacco is a set of widgets that extend Tk for object visualization. Its home page is <URL: >. 122. A toolkit of software is available from <URL: >. Many things are on this page - a dynamic loading tcl shell, an encoded URL to Tcl array decoder, a support library for embedding tcl in HTML template files, a support library to provide support for mailto like functionalify, a simple order form generator, and a user interface support library are present. This is also the home for tkauxlib, a support library for extended Tcl/Tk capabilities <URL: >. There are also published papers on the use of Tcl/Tk in a production application, a proposal for dynamically loading libraries in Tcl and a note on what to do when Tk reports that your display is insecure, all pointed to from this page. <URL: > is the index of the manual pages for Tcl-WWW. <URL: > is the URL for information on using/debugging Tk vs X windows authorization problems. 123. A home page for Jay Sekora <URL: mailto:js@aq.org >'s jstools is at <URL: >. 124. A WWW page detailing Tcl resources can be found at <URL: >. 125. Online versions of Tcl and Tk manual pages can be found at <URL: >. 126. A WWW page pointing to various Tcl/Tk software resources can be found at <URL: >. 127. The home page for <URL: mailto:curt@sledge.mn.org > (Curtis L. Olson), <URL: >, contains pointers to a Tcl/Tk interface to a check book balance program. 128. At the 1994 WWW conference, a number of papers were presented which mentioned Tcl. These papers can be found in the proceedings located at <URL: >. Here are the papers that have been brought to my attention to date. <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > <URL: > 129. Several articles discussing WWW applications written using the Tcl extension Hush can be found. One, discussing WWW chat boards, is at <URL: >. Another, covering integrating applications and the World Wide Web is at <URL: >. 130. <URL: mailto:mmccool@cgl.UWaterloo.CA > (Michael D. McCool) used Tcl to teach a course in 3D computer graphics at the University of Waterloo. See <URL: > more information. Basically, they are using Tcl/Tk both to build UI's for projects and to build an object-oriented graphics command language that they call "Gn", for "graphics notation." 131. The page <URL: > is home for a number of Tcl/Tk related items. For instance, there is quite an interesting lunar calendar that you can view there. 132. The home page for Phantom, a new interpreted language designed for large scale interactive distirbuted applications, can be found at <URL: > and <URL: >. It includes a Tk binding. 133. A home page describing Alpha, the Macintosh text editor with the Tcl extensions interpreter, can be found at <URL: >. 134. Conversion notes for updating code to work under both Tk 3.6 and 4.0 can be found at <URL: >. 135. Notes on the sessions from the 1995 Tcl/Tk workshop can be found at <URL: >. 136. At <URL: > one will find a page describing a Kanji dictionary program. TkJdic is a combined wa-ei-wa and kanji dictionary program in Tcl/Tk. Its home page is <URL: >. 137. The SIMEX framework is a C++ class framework for building discreate event simulation models. More information can be found at <URL: >. 138. Over the years, <URL: > has had a number of articles, such as <URL: >, covering news of the Tcl community. 139. Dp in ET (DiET) is a patch to Embedded Tcl to support Tcl-DP. The home reference can be found on <URL: >. 140. The Rothamsted Experimental Station has a software archive they provide as a service to others. In <URL: > you can find a few useful Tcl scripts. 141. The home page <URL: > provides for Tako Schotanus a location for some patches to provide dashed outlines for Tk canvas items , patches to make [incr tcl] work with Tk 4, patches to make object tcl wish interpreters and patches to make tkinspect work with incr tcl. 142. The Java folk have made a small informal unsupported effort to merge Java and Tcl. See <URL: > for the details. 144. At <URL: > and <URL: > are a couple of Postscript documents detailing the work being done concerning portable Tk. 145. The Unix Review "Internet Notebook" columns of Rich Morin are now available on line. See <URL: > for one about Tcl and Tk. 146. The Plume home page <URL: > is the beginnings of a guide to writing active message content using Tk 4, Safe Tcl (stcl), and other pieces of technology. See <URL: > for more details on writing server side scripting, servlets, microscripting, and more. 147. W3CNT is a Tcl/Tk/GD based WWW access counter. You can find its WWW page at <URL: >. 147. The WWW page for GDtcl, by <URL: mailto:spencer@umich.edu > (Spencer W. Thomas), can be found at <URL: >. Note that the author has no plans on continuing support for this extension, and is seeking someone else to take over work on it. Also note that because of the legal situation with Unisys over GIF, even the GD code on which gdtcl is based is in a development limbo. 148. TkReplay is a record and replay system for Tcl/Tk. See <URL: > for details. <URL: > is the paper Charles presented at the 1995 Tcl/Tk Workshop. 149. The SunWorld online site at <URL: > has published several general articles on Tcl. Do a search there to find them all. A recent one was the one on TclBlend and Jacl <URL: >. 150. A WWW discussion board is available relating to tclwp8 topics. See <URL: >. 151. With the appearance of MacOS X, there is likely to be more articles like <URL: >, describing to people the benefits of using Tcl and Expect on this platform. Also at this site there are articles like <URL: > which discussing multicasting and Tcl, <URL: > which talks about Visual Tcl, <URL: > about Tcl on the Mac, <URL: >, an article about XStick, as well as a few other casual mentions. 152. SoftSmiths have a series of VHDL tools that use Tcl/Tk based interfaces. See <URL: > for details. 153. The translator of the tcl-faq.part0? FAQs into Japanese now has a WWW home at <URL: >. There have been reports that this URL may not be current. 154. Walnut Creek, publisher of CD-ROMs, has a WWW site where they discuss their various products. If you look at <URL: > you will see a description of the October 1995 product, along with a pointer to <URL: > where all the items from the CD-ROM can be found. Walnut Creek is now shipping a CD-ROM whose contents were obtained around the beginning of September, 1995. Contact <URL: mailto:www@wcarchive.cdrom.com > or <URL: mailto:info@cdrom.com > for more details. 155. WebReview did an article on Tcl - see <URL: >. 156. Steven Majewski's Programming Language Critque pages has a section for Tcl at <URL: >. 157. A WWW page of Internet Protocols at <URL: > contains a section pointing to libraries and applications for interfacing between SNMP and Tcl/Tk. 158. The details of <URL: mailto:throopw@sheol.org > Wayne Throop's setup for doing creating and presentations using wish can be found at <URL: >, along with a sample of slides on Tcl/Tk. Other pages of interest from Wayne are the home pages for tkdraw <URL: >, very simple cross reference viewer <URL: >, simple text editor <URL: >, and map viewer <URL: >. 159. The paper "Experience with Tcl/Tk for Scientific and Engineering Visualization" by BWK can be found at <URL: > or <URL: > (gzipped Postcript (152 kB)). At <URL: > is a paper covering performance. 160. A brave attempt at creating a master table of version compatibilities has been undertaken at <URL: >. 161. The Eolas group, holder of a pending patent on Web applets, has described in a recent Dr. Dobbs Journal and on <URL: > the idea of making a WWW browser which uses Safe Tcl/Tk as the language for applets. 162. A site called "Coop: Computer Supported Cooperative Work" has built a WWW page at <URL: > focusing on various software environments for performing one's work in concert with other users. A number of pointers to other Tcl efforts, as well as other languages, can be found on this page. 163. The TACOMA project <URL: >, which focuses on operating system support for software agents, uses Tcl and Tk for agents. One of their applications is called StormCast, which is a distributed weather prediction software, uses Tcl agents to distribute across remote sensing sites. 164. AgentTCL <URL: > is a project to create a transportable agent system. 165. Mobile Service Agents <URL: > is a project which uses Tcl/Tk for the user interface in a system for accessing up to the minute information, resources and services using the Internet. 166. MOREplus is a WWW cataloging and database tool which uses Tcl based processes in its task. See <URL: > for more details. Note that <URL: > is the Cranberry Square Software Market library of freely distributable software. They basically organize pointers using a variety of methods of searching. They have a few Tcl related packages listed, but most of the listings are old. 167. Network Cybernetics Corporation <URL: > has released a CD-ROM called Web Wrangler 1 which contains tools for those folk responsible for creation and maintenance of WWW sites. Lots of tools for CGI programming, etc. including tools for using Tcl. 168. TipTop Software <URL: > is the home for information on ObjectiveTcl. 169. Eric Johnson's WWW pages contain an HTML version of his Windows FAQ at <URL: > as well as an intro to Tcl/Tk <URL: > and a page related to his new Tcl/Tk book <URL: >. This book comes with a CD-ROM which has a number of Tcl and Tk related software items on it. Eric also has a page with a tutorial for the Tk 4.1 grid command located at <URL: >. Eric has a few examples of using Perl/Tk at <URL: > 170. A page describing a new extended Tk text widget for Tk and Perl/Tk can be found at <URL: >. 171. The AGOCG Tcl/Tk tutorial is available at <URL: >. It is a document describing the use of Tcl 7.6 and Tk 4.0 across platforms. Unfortunately, the original intention of this being a living document never was fulfilled. The source code examples files are available from <URL: >. The Cookbook is partly sponsored by the UK Advisory On Computer Graphics. It is aimed at novice window-based interactive application developers and newcomers to Tcl/Tk. 172. For a series of Tcl examples of how to do things which are not necessarily obvious, see <URL: > . 173. A very interesting resource is the People Helping One Another Know Stuff (PHOAKS) WWW site. At <URL: > is the page for <URL: news:comp.lang.tcl >. The idea is that as folks on the newsgroup refer to various web resources, they are indexed by software running at this site and added to the page. By going to the above page, one gets to look at a ranked series of favorite web pages. 174. Bruce Gingery <URL: mailto:bgingery@gtcs.com > has an article that compares Tcl/Tk, Perl/Tk, and Python/Tk to early 1980's BASIC using a simple example at <URL: >. 175. The Tcl CGI home page is located at <URL: >. It describes a small package which enables Tcl programmers to write CGI scripts which can handle the POST method. 176. The Visual Developer online archive at <URL: > discusses various tips on how to write GUI applications, including the use of Perl/Tk. 177. The PennWyndow WWW page is research being done using Tcl/Tk to supervise heterogeneous applications, coordinating different utilities. See <URL: > for details. 178. A Tcl/Tk and Expect tutorial paper by <URL: mailto:will@Starbase.NeoSoft.com > can be found at <URL: >. 179. The Inferno home page at <URL: > is a good place to read about the new Limbo programming language, which uses a Tk package for windowing. The Tk used however was written from scratch in Limbo. 180. At <URL: > an interesting paper resides regarding an interactive tool using incr tcl/incr tk to aid in proposal preparation for the Hubble Space Telescope. 181. Yet another Tcl/Tk resource site can be found at <URL: >. 182. Benchmarks of Tcl and other scripting languages by BWK and Chris Van Wyk can be found at <URL: >. 183. Over the years, <URL: > has had a number of articles, such as <URL: >, covering news of the Tcl community. 185. Text versions of articles from ;Login: regarding Tcl can be found at <URL: >. 186. The article "Using Active Server Pages with Microsoft Internet Information Server 3.0", located at <URL: >, indicates that Microsoft will be supporting Tcl plugins for their server. 187. A French tutorial on Tcl can be found at <URL: >. 188. At <URL: > is a paper titled "Reusable Procedures For Generating and Modifying Tk Widget" which describes using the standard Tcl and Tk to build reusable widget makers or fixers, along with procedures for writing one's own similar routines. You should find other useful Tcl help at this same site. 189. Notes from the Tcl 95 Workshop can be found at <URL: >. The USENIX organization, who sponsors the workshops, no longer permits the papers making up the proceedings to be made available as a group. If you are a USENIX member, you can get access to some electronic copy thru <URL: >. 190. <URL: > is a page collecting many URLs relating to the Tcl community and Object Oriented programming. 191. A paper discussing quick development languages (detailing both perl and Tcl) for Astronomy, written by <URL: mailto:kuiper@jpl.nasa.gov > and dated July 31, 1995, can be found at <URL: >. 192. softWorks has a WWW page at <URL: >. They sell several Tcl based programs for developing software. 193. Awaiting info on DarkStar 194. A WWW page for information on Tcl/Tk and GUI style guides, writtin in both English and German, can be found at <URL: >. 195. The page at <URL: > contains info learned as the author writes his Tk based IRC client. There is at least a note on how to hook into a Windows application event loop here. 196. A paper on using Tk as a remote GUI front end for fourth generation database applications, by Volker Schubert <URL: mailto:leo@bj-ig.de > can be found at <URL: >. 197. Frank Pilhofer <URL: mailto:fp@informatik.uni-frankfurt.de > has a web page at <URL: > which points to a document on building Tcl extensions from C++ code, a sample CGI script to browse RFCs, as well as pointers to various Tcl Tk projects. 198. At <URL: >, one finds a discussion of a supercomputer project. The software in this project, according to <URL: >, uses a Tcl/Tk interface for its parameter input. 199. At <URL: > you find the archives of the WWW Journal, a publication by O'Reilly's which covers the world of the Web. A number of articles have been published relating to Tcl ; use their search engine to find the currently available ones. 200. Thomas Sicheritz <URL: mailto:thomas@evolution.bmc.uu.se > has a page of Tcl references at <URL: > which cover quite a wide spectrum of interests. 201. Joe Konstan's paper on OAT from the 1997 workshop can be found at <URL: >. 202. The authority WWW site for this set of FAQs is, as mentioned at the top of these files, <URL: >. A search engine interface to all USENET FAQs is available at <URL: >. <URL: > can be found there. Other places to find USENET FAQs on the WWW include <URL: > <URL: > <URL: > <URL: >. FTP access to the FAQs can be found at <URL: > and <URL: >. 203. Stefan Hornburg <URL: mailto:racke@gundel.han.de > has written the document "Tcl and Friends" <URL: >. 204. ScriptSearch is a free index of Web related development tools. They hope to add pointers to Tcl and Tk scripting tools. See <URL: > for what they have had submitted to date. 205. Byte Magazine has had a few articles specifically about Tcl over the years, as well as references in a number of others. See for instance <URL: > <URL: > and if you search at their site, you will also find references relating to products reviewed which use Tcl. 206. A new web site about Tcl/Tk is available in Spanish. See <URL: >, which includes introductory material, examples and a forum where any question, suggestion or commentary is welcome. Contact Alejandro Sualdea <URL: mailto:asualdea@pika.net > for more details. 207. The python community <URL: > uses bindings to Tcl/Tk to obtain one of its GUI interfaces. See a variety of pages at this site for details. See <URL: > for a Python biased comparison between Python and Tcl. 208. <URL: > is an example of a WWW service provided using Expect. It is a WWW based user interface to the Virginia Tech Library System, using Expect and telnet. 209. <URL: > is an online magazine which has published several articles relating to Tcl. For instance, <URL: > and <URL: > are articles about Jacl. 210. <URL: > is the site containing information on software agents written in tcl. 211. <URL: > is an archive of a variety of Windows related patched Tcl and Tk related extensions and applications. 212. At <URL: > John Reekie <URL: mailto:johnr@kahn.eecs.berkeley.edu > did some comparisons of STERNO, Matt Newman's tcl++ 1.0 and obstcl, a small object system package John wrote. 213. At <URL: >, Donal Fellows has a number of useful Tcl routines and information regarding Tcl, including a report on his analysis of Tcl's year 2000 readiness. See <URL: > for some notes on a discussion with Paul Duffin on future Tcl needs. 214. At <URL: > the author of Tea provides a comparison between Tea and incr tcl. 215. See <URL: > for a paper on REUBEN, a reusable environment driven by benchmakring applications, by K. Kozminski, B. Duewer, H. Lavana, A. Khetawat, and F. Brglez. 216. See <URL: > for one man's view of what's needed for Tcl to help the user. 217. A short Tcl & Tk tutorial by Alex Samonte can be found at <URL: >. 218. A (biased, as most such things are) comparison of perl versus Tcl by Tom Christiansen can be found at <URL: > and another one by Aaron Sherman at <URL: >. So that you know, Tom did this type of thing for a variety of languages, including Perl. No need to flame him because the list is based on old versions of Tcl, etc. 219. Frank Stajano's paper at the 1998 Python conference had some useful insights into why he thinks Python's extensions are evolving faster and are easier to work with than Tcl's: <URL: >. 220. The Developer.com site did a profile on John Ousterhout at <URL: >. There are a couple of articles on Jacl, as well as a few other Tcl references at this web site. They have created a Tcl directory at <URL: > in yet another attempt to categorize Tcl offerings. See <URL: > for a longer article on using Tcl with Java. 221. Steve Uhler's 1996 Tcl workshop presentation slides on the search for the perfect megawidget can be found at <URL: >. 222. Linux Today <URL: > , an ezine covering Linux news, occasionally includes the Tcl-URL information, as well as other topics near and dear to Tcl fans. 223. The Tcl/Tk Consortium created a CD-ROM in 1998. It was a Tcl 7.6 based distribution, containing binaries for many different systems. The CD-ROM can be purchased by an individual via Linux Central <URL: >. 224. See <URL: > for information regarding <URL: news:comp.lang.tcl > that is maintained by <URL: mailto:andreas_kupries@users.sourceforge.net >. Also at Andreas's home page are pointers to a variety of Tcl related software packages he has developed and is in the process of developing. 225. At <URL: > is yet another attempt to make the vast tcl resources available to users. 226. Information about the use of Tcl and [incr Tcl] during prototyping of the Mars PathFinder project can be found at <URL: > . 227. OneSeek/Developer is a new search/navigation site which makes it easy for developers to find technical info on the WWW. Find it at <URL: >. A Tcl area is available on the site. 228. Stoian Jekov <URL: mailto:sto@mbox.eda.bg > has created a Tcl/Tk related site at <URL: >. Issue 1 can be found at <URL: >. 229. A Yahoo club for discussions regarding Tcl and Tk can be found at <URL: >. Another one can be found at <URL: >. 230. A PlanetAll forum has been created for Tcl/Tk - see <URL: > for details. 231. mIRC USA is a site dedicated to IRC! It offers scripts, addons, the latest information... as well as Eggdrop, compiling help, and the latest TCL files. They also offer the latest security patches to prevent nukes, and much much more! Find it at <URL: >. This site is not officially connected with the Eggdrop development team. 232. ComputingSite <URL: > is a search engine covering more than 300 different computing related 'channels', including Tcl. 233. a LUSENET web forum is available at <URL: > for trying out this technology. 234. The National Library of Singapore has recently launched the NL.Line. This is a WWW interface to its library and information services. This WWW interface uses Perl and Tcl to gateway to its McDonald Douglas mainframe. See <URL: > for the WWW interface. 235. A series of papers and slides regarding Tcl programming, written in German, can be found at <URL: >. 236. A CGI resource called <URL: > is available, however it has only a few Tcl related resources at this time. 237. A proposal for Super/Simple/Small/Safe Tcl can be found at <URL: >. 238. There are ptk (perl/Tk) web page pointers, patches, tutorial articles, and other tips at <URL: >. 239. See the OOMMF project at <URL: >. They use C++ and tcl. 240. Yet another attempt to organize internet resources: <URL: >. <URL: > 241. <URL: > is a site where you can find Adventures in Linux Programming. This includes "weekly" tips and tricks about Tcl/Tk programming. 242. An online forum to discuss XiRCON can be found at <URL: >. 243. The Brighton University Resource Kit for Students (BURKS) project is a non-profile set of 2 CD-ROMs available in the UK. It provides around 1.1 gigabyte of material including compilers, interpreters, tutorials, and reference materials for over 20 programming languages, along with a copy of the free online dictionary of computing, a linux distribution, a set of linux manuals, FAQs, tutorials, internet specfiications, and a selection of MS-DOS and Windows software. The CD-ROMs include Tcl/Tk 8.0 for Windows, Tcl 7.3 for MS-DOS, tutorials, FAQs, and the Tcl 8 manual pages. The entire collection is available online at <URL: >. Tcl/Tk-related material is at <URL: >. Ordering information (including shipping costs to various destinations) is also available online (at <URL: >). 244. A web page for coordinating Tcl Consultants available for work can be found at <URL: >. If you want to be added to this page, please send e-mail to <URL: mailto:tclconsult@hwaci.com >. 245. The bioinformatic part of GNOMICS - the small genome sequencing group - was written 99% in Tcl/Tk. See the article on <URL:: > and notice figures 1 and 2 - which are Tk canvas dumps. 246. Tcl-Wear Chronology is a link at <URL: > which attempts to detail the tee shirts, toys, and specialty items designed to advertise Tcl. 247. See <URL: > by Victor Wagner <URL: mailto:vitus@wagner.rinet.ru >, which discusses a Tcl based desktop environment. 248. Scott McCrickard <URL: mailto:mccricks@cc.gatech.edu > has the notes from a human factors class he taught on the WWW at <URL: >. He used Tcl as the programming language for the lab work. 249. Tcl/Tk is taught as a part of a X systems Admin class at the Geoscience Technology Training Center, at North Harris College <URL: >. 250. At <URL: > is a Tcl 8.0 tutorial based on John Ousterhout's original tutorials, as well as Tcl UDP and a disk usage application. The creator also has some online doc for Tcl UPD and Tcl channels at <URL: > 251. At <URL: > is the description of the API for a Laser Interferometer Gravitational Observatory Data Analysis System. 252. At <URL: > is a source code archive for Tcl applications. 253. A paper on an extended version of the MIT otcl object extension is available at <URL: >. At least two papers have been published. XOTcl (Extended OTcl, pronounced exotickle) is a value added replacement of MIT's OTcl. It is an object-oriented scripting language with several new functionalities aiming at the management of complexity, like Per-Object Mixins, Filters, Nested Classes, Dynamic Object Aggregations, Metadata, Assertions. 254. The Freshmeat web site - which is a useful site to monitor for new software releases of all sorts has a section for Tcl extensions. See <URL: >. The general appindex also lists a number of applications if you search for "tcl". Searching for Tk is a bit less useful because of matching strings like GTk. 255. The Vignette StoryServer provides a Tcl interface. See <URL: > , <URL: > or <URL: > for more information. Also, newsgroups for Vignette can be found at <URL: nntp://news.vignette.com/vignette.storyserver.template-lang > <URL: nntp://news.vignette.com/vignette.storyserver.misc >. 256. The <URL: > Jargon site has as its topic the description of numerous computer jargon/terms. While not Tcl specific, many people find it useful to explain what particular terms being used mean. 257. See an introduction to tcl at <URL: >. 258. See <URL: > and mirrored at <URL: > for a list of CAD related applications - some of which are in Tcl/Tk. 259. The AI Mind (Public Domain Artifical Intelligence) web site has a Tcl related page at <URL: > . 260. Ray Masters <URL: mailto:masters@bleriot.cac.psu.edu > pointed out to me <URL: > as a location from which one could find information about developing custom interactors for DX using the standard DXLink facilities. 261. A Tcl community collaboration effort called the Tcler's Wiki is available at <URL: >. At this site you can find pages available to ask Tcl questions, document differences between recent versions of Tcl and Tk, discuss Tcl books, document favorite Tcl tricks, tips on Tcl performance, tutorials on various tcl topics, etc. A public forum to calmly and rationally discuss the benefits of Tcl usage can be found <URL: >. Many, many other pages are available. One interesting use is the various pages full of Tcl and Tk code - code too small in and of itself to be 'packaged' up for general download, but the right size to scrall on the bulletin board and be available for use (or comment and correction!). There are too many pages at the Wiki to try to document them all. Some pages are discussion only pages. Some are documentation pages - describing how Tcl works. Some are tutorial - showing how to use Tcl to solve some kinds of problems. Some are actually code - providing working examples of solving all sorts of problems. Some are pointer pages, containing a variety of links to other resources. 262. Jeff Gosnell <URL: mailto:machtyn@earthlink.net > has announced a number of Tcl related items at <URL: >, including a Tclet, a chat room at <URL: >, etc. However, I've not been able to get thru to the site (I suspect it is very busy). 263. A discussion regarding O'Reilly's first Perl/Tk book can be found at <URL: >. 264. The Tcl/Tk Journal can be found at: <URL: > - Europe <URL: > <URL: > Contact Stoian Jekov <URL: mailto:sto@mbox.eda.bg > or <URL: mailto:stoian_j@yahoo.com > for details. 265. An experiment has begun at <URL: > to provide a place where users of Tcl applications can ask questions. 266. The Linux Journal published an interview with John Ousterhout in April of 1999. See <URL: > for details. This journal has carried other articles - do a search at the site for pointers to various articles. 267. A web page has been constructed with pointers to the papers and slides from the First European Tcl/Tk User meeting, held in June, 2000. See <URL: > for details. 268. I recently noticed that <URL: > has a relatively nice interface to RFCs. Using that, one can see a number (more than a dozen when this entry was added to my FAQ) of RFCs which contain some reference to Tcl. Most, however, are in passing references to Tcl as one of several languages which could be used for scripting. 269. <URL: > is a Web encyclopedia entry for Tcl. 270. <URL: > is an article in French, written for the French Linux magazine <URL: >. 271. Information about writing Tcl thread safe apps on Windows NT can be found at <URL: >. 272. C.K. Hung taught a Tcl/Tk course. Information on this course can be found at <URL: >. 273. <URL: > lists a number of resources for Eggdrop Tcl programmers. 274. The WebTechniques <URL: > magazine continues to publish articles on Tcl and Tk on occasion. See the 1997 article on the Tcl Plugin <URL: > the 1999 issue for Steve Ball's article on Scripting XML with Tcl, <URL: > the 2000 article on Web agents written in Tcl/Tk <URL: >, and many more - more than 45 hits on Tcl are found. 275. Delphi promotes free use of their online forum communities - there are a few that appear to focus on Tcl: <URL: > <URL: > <URL: > 276. Ioi Lam <URL: mailto:ioilam@my-deja.com > has created a WWW page covering Chinese programming in Tcl. See <URL: >. 277. The source for Perl information <URL: > has began a Perl/Tk tutorial at: <URL: > <URL: > 278. A paper on embedding Tcl, Perl or Python can be found <URL: >. 279. A page discussing how to use Turkish letters with Tcl/Tk 8.2 can be found at <URL: >. It is written in English and German. 280. The <URL: > site is filled with interesting information for the Tcl programmer. For instance, <URL: > appears to be a working draft of a book initially called "SQL for Web Nerds". It is a tutorial on SQL, using the AOLserver as a base and Tcl as the programming language. There are other items such as <URL: >, which is the web version of the book "Database Backed Web Sites". Then there is the ArsDigita Community System, a database driven web forum. 281. SuSE (a Linux distribution created by a German group - see <URL: >), uses Tcl/Tk in at least one, and possibly more, of their configuration tools. The one that has been reported using Tcl/Tk is SaX, the advanced X configuration tool, used to configure xfree86. 282. Chengye Mao <URL: mailto:chengye.geo@yahoo.com > has a web page which discusses building combined widgets (aka mega widgets) in pure Tcl at <URL: >. 283. The <URL: > web site has various drill games, all of which are written in Tcl. 284. George P. Staplin <URL: mailto:GeorgePS@XMission.com > has written some tutorials on how he uses movies, audio, images and PNG cursors with Tcl/Tk in a game he is writing. See <URL: >, <URL: > about using XLib ith Tcl/Tk from C, <URL: > about extending Tcl and Tk. 285. One ICQ Active List (ICQ is an interactive chat facility - see <URL: > for more details) that's available 24 hours/7 days a week for discussions of TCL, Tk, and C is (AL# 56087677). Contact Eric Evans <URL: mailto:ciresnave@yahoo.com > if you have questions about this list. 286. One source for perl/Tk examples is <URL: >. 287. The Linux Gazette occasionally covers Tcl related topics, such as the article <URL: > "Using SWIG to interface scripting languages with C/C++". 288. CNET's Help.com has a section for people to ask for help. See <URL: >. 289. A new web forum resource is available for Tcl/Tk programmers at <URL: >. 290. Information about the use of Tcl and [incr Tcl] during prototyping of the Mars PathFinder project can be found at <URL: > . 291. A document descripting how to embed a Tcl interpreter in a Java program has been provided at <URL: >. It mainly describes the interaction between a multi-threaded Java program and an event driven single threaded Tcl interpreter. 292. Information on building and using Tcl/Tk on IRIX 6.x can be found in the docs at <URL: >. 293. Technical report evaluating the properties of 80 different implementations of the same program in 7 different programming langauges (C, C++, Java, Perl, Python, Rexx, and Tcl). See <URL: > Erann Gat did a study of Lisp on the same problem. You can find his work at <URL: > and you can see another Lisp solution at <URL: > 294. See <URL: > for a Tcl/Tk Forum run at the Tek-Tips web site. 295. See <URL: > for a page dedicated to linking various scripting languages - include Tcl - to any freely available EDA tools. 296. The Tcl community initiated a new support mechanism called the Tcl Core Team (TCT). See <URL: > for details. Send email to <URL: mailto:tclcore@tcl.activestate.com >. See the URL just mentioned for the Tcl Improvement Proposal - a mechanism for describing new features proposed to be added to Tcl. 297. At <URL: >, the webmaster indicates that he is looking for code snippets, documentation, tutorials and articles for Tcl. 298. Not surprizingly, if you search the <URL: > site you will find a references to Tcl and the work at creating Tcl bindings for the IEEE work on CBT . 299. The eMagazine <URL: > is covering Tcl, including interviews with John Ousterhour, a series on persisting Tcl data in text files, etc. 300. <URL: > is a page pointing to a variety of useful tcl applications, extensions, etc. 301. <URL: > is a page with pointers to translations (in English, French, Nederlands, Russian and Turkish) of an introduction to Tk article. 302. ZDNet's Developer web site has a section called CGI/Perl/TCL <URL: >, where Cameron Laird has written several articles about writing CGI using Tcl. 303. Jeff Hobbs and Andreas Kupries work for ActiveState and promise to provide support for ActiveTcl. Their <URL: > plans for Tcl are available now online. They now offer ActiveTcl (see "part4") as well as enterprise maintenance support, etc. They have also added a section on Tcl mailing lists, with archives for a number of popular lists at <URL: >. At <URL: > is a great online Tcl reference section, with links to papers from the Tcl'2002 US and European conferences as well as other resources. 304. A Yahoo! WebRing for Tcl exists at <URL: >. The focus is for Eggdrop bots and scripts. 305. Linux Today <URL: > , an ezine covering Linux news, occasionally includes the Tcl-URL information, as well as other topics near and dear to Tcl fans. 306. The Church of the Swimming Elephant <URL: > is a reference site for computer professionals. It contains many pages of info on Tcl, from manual pages, to reference guides to tutorials on Expect and more. 307. Mark Harrison has provided a series of useful information regarding the use of the Tcl msgcat functionality in the form of FrameMaker and PDF files. See <URL: >. 308. Linux Guruz <URL: > has a few tutorials related to Tcl, and are open to people submitting more. 309. The Perl Montly website / ezine <URL: > has articles on perl/Tk. 310. A series of articles and sample programs covering Perl/Tk , including GUI programming can, accessing databases, etc., written by Philip Yuson <URL: mailto:pyuson@yahoo.com >, be found at <URL: > . 311. <URL: > has a variety of resources, including a search engine for a Linux FAQ, lots of links to other useful sites, Unix 'lifesaving' tips, and lots of great Perl/Tk software. 312. Doug Bagley has created a general language performance comparison web site at <URL: > which provides a look at how Tcl and a number of other languages compare. Hopefully someone in the Tcl community takes on the task of letting Doug know when new releases of Tcl appear for reappraisal. 313. A WWW site in French that covers Tcl/Tk can be found at <URL: >. There is no intent on translating the site into English - they recommend using software such as <URL: >. 314. See <URL: > for a web site where one can work with users to help them out with problems and perhaps earn a bit of money as a result. 315. ActiveState has begun offering spport of various kinds for Tcl users. See <URL: > for information about a Tcl cookbook of code and comments. 316. See <URL: > for information about cross compiling code from one platform to another. 317. Dr. Dobb's Journal is a technical monthly which has covered Tcl, Tk, and related topics for years. For instance, see: <URL: > for an article discussing the compilation of Perl/Tk scripts. 318. Notes on upvar/uplevel guidelines can be found at <URL: >. 319. See <URL: > for a FAQ like web site which uses various categories. 320. See <URL: > for a collabrative effort to advertise jobs and resources available relating to Tcl. 321. See <URL: > for a white paper dealing with Objects in Tcl and <URL: > for a white paper dealing with data file formats for Tcl scripts. 322. See <URL: > for a one page discussion of Tcl/Tk (in French). 323. <URL: > searches the web site and displays to you several Tcl related documents which can be downloaded into your Palm Pilot. There's also a couple of weird hits that come up as a result of this search as well - feel free to ignore those... 324. <URL: > is an introduction to Tcl/Tk created by <URL: mailto:davidw@dedasys.com > David N. Welton . It requires a stylesheet compliant web browser. 325. The results of the Third European Tcl/Tk user meeting can be found at <URL: > . From: FAQ General information Subject: -VIII- Are there any mailing lists covering topics related to Tcl/Tk? There are quite a number of mailing lists which cover topics relating to the Tcl community. As you begin one, if you will send me information relating to the mailing list, I will add it below. o ActiveTcl This mailing list discusses the issues of users of ActiveState's ActiveTcl product. See <URL: > for subscription information. o ActiveX for Tcl This mailing list discusses the isses in integrating Tcl and ActiveX. To subscribe, send email with the subject of "subscribe" to <URL: mailto:activex-request@tcltk.com > An archive of this mailing list appears to be available at <URL: > o Alpha-D Mailing list for the Tcl developers relating to the Macintosh text editor Alpha. To subscribe, send to <URL: mailto:listserv@listserv.syr.edu > a line of text of the format subscribe ALPHA-D your name (where you replace "your name" with your own name). To unsubscribe from this list send the text: unsubscribe ALPHA-D in the body of the message to <URL: mailto:listserv@LISTSERV.SYR.EDU > Human administrator: ALPHA-D-request AT LISTSERV.SYR.EDU Replace "AT" with @. This is to protect this list owner address from spammers. This list appears to be moving to <URL: >. o aolserver mailing lists Mailing lists relating to AOLserver, which can use Tcl as an extension language). AOLSERVER is an unmoderated open discussion list. If you want to subscribe or change your subscription settings, visit <URL: > for detailed instructions or go to <URL: > o BLT mailing list BLT is a Tk widget set with a variety of useful features. A mailing list for BLT developers has been created for the discussion of BLT development issues. It may be a useful forum for those who are currently working on BLT (developing, maintaining, bug fixing, etc). If you are interested, please subscribe. To subscribe to the blt-dev mailing list, send mail to <URL: mailto:majordomo@dscpl.com.au > with the following in the *body* of the message: subscribe blt-dev To get help on the mailing list manager, send mail to <URL: mailto:majordomo@dscpl.com.au > with the following in the *body* of the message: The mailing list is intended to be very low volume and should be used by those actively developing BLT to coordinate their activities. o Basic Object Systems (BOS) BOS is a SELF-like objects extension to Tcl. To join, send email to <URL: mailto:snl+bos-requests@cmu.edu > and then send messages to <URL: mailto:snl+box@cmu.edu > . o CAML Light Mailing list CAML Light contains a contributed interface to the Tk library. To discuss developments in this interface, subscribe to the mailing list by sending email to <URL: mailto:caml-list-request@pauillac.inra.fr >. o Canvas Visitor This is a mailing list setup up for sharing information about the visitors extension as well as any other extensions (preferably) related to the tk canvas widget. The visitors extension was made to enable users to add. Future releases may also included contributed visitors (please share your ideas) and a working C API to creating canvas items. To sign up, send email to <URL: mailto:Majordomo@pgw.on.ca > with the following command in the body of your email message: subscribe canvas-visitors {email address} o cfh German discussion group concerning cfh (call for help), a useful Tcl script for eggdrop bots on irc net. <URL: > where you provide your own email address in place of {email address}. If you have any trouble with this mailing list feel free to contact its adminstrator <URL: mailto:Matthew.Rice@pgw.on.ca > (Matthew Rice). o CODA This online data acquisition system uses Tcl to coordinate programs. To join its mailing list, send email to <URL: mailto:mailserv@cebaf.gov > using a "SUBSCRIBE CODA-L" for the body of the message. o Colossus A nickname for the TinyScript project, created by Jean-Claude Wippler <URL: mailto:jcw@equi4.com >. Discussions cover small scripting languages (Colossus) and more. Colossus mailing list - to join, send an email to <URL: mailto:solossus-add@mini.net > o CMT Users Mailing list The Berkeley Continuous Media Toolkit is a Tcl toolkit to support a portable way of developing multimedia playback against a variety of devices. To subscribe, send email to <URL: mailto:cmt-users-request@bmrc.berkeley.edu >. o comp.lang.tcl.announce mailing list By using the service available at <URL: > one can receive by email the postings of comp.lang.tcl.announce. Contact the owner at <URL: mailto:tcl_announce-owner@yahoogroups.com > o Copenhagen SGML Tool (CoST) mailing list CoST is a beta level tool designed to enhance sgmls so as to add additional flexibility in processing SGML documents. To join, send email to <URL: mailto:Klaus.Harbo@euromath.dk >. Actual messages apparently go to <URL: mailto:cost-list@math.ku.dk >. o Dart support The emails sent to the dart support can be found at <URL: > forming a sort of mailing list. o Dejagnu This set of mailing lists are *NOT* maintained by Cygnus, the developers of Dejagnu. Dejagnu is an expect 5.x based package designed to be a framework for testing other software. Test suites exist for various GNU products such as GDB and binutils. 3 mailing lists - dejagnu-bugs, dejagnu-developers, and dejagnu-questions - have been created as a part of <URL: mailto:listserv@yggdrasil.com >. To subscribe, send the line: subscribe dejagnu-bugs yourname@yoursite.com to the email address <URL: mailto:listserv@yggdrasil.com > where you put your own email address in place of yourname@yoursite.com and you put the name of the mailing list you wish to join after subscribe. o Dotfile Mailing list to discuss the Tcl based configuration tool. Send email to <URL: mailto:dotfile-request@imada.ou.dk > with the subject of 'subscribe'. o ECLiPSe ECLiPSe (ECRC Logic Programming System) is a system based on Prolog, and which uses Tk as a GUI interface. To join the mailing list, contact <URL: mailto:eclipse_request@ecrc.de >. o Effective Tcl mailing list The purpose of the list is to 1. Discuss issues, suggestions, bugs, defects, etc., in the book "Effective Tcl/Tk Programming". 2. Provide support for people using the efftcl library in various projects. 3. In the "open source" vein, to accept fixes, improvements, and additions to the efftcl library. The EffTcl mailing list is sponsored by WebNet Technologies. To subscribe: send mail to <URL: mailto:EffTcl-request@tcltk.com > with the word SUBSCRIBE as the subject. To unsubscribe: send mail to <URL: mailto:EffTcl-request@tcltk.com > with the word UNSUBSCRIBE as the subject. To send to the list, send email to <URL: mailto:EffTcl@tcltk.com > An archive for this list can be found at <URL: >. This list appears to be moving to <URL: >. o EggDrop EggDrop is an Internet Relay Chat (IRC) bot (robot) which is programmable in Tcl. To join the mailing list, visit <URL: > to subscribe. This list is not officially associated with eggdrop. o Eggdrop.ph-list This is an open, unmoderated discussion list devoted to Eggdrop "bots" (Internet Relay Chat or IRC robots). While primarily intended to be a forum where Filipino botmasters on #eggdrop.ph (the Philippine Eggdrop Bot Help channel on IRC's Undernet network) can post announcements, ask questions, swap opinions, trade scripts, and generally hang out via email, the list is open to all those interested in setting up or are already running/maintaining their own Eggdrop bots on IRC. Newbies, botmasters, and botowners are welcome. To subscribe to the list, send 2 blank emails to <URL: mailto:eggdrop.ph-list-request@eskimo.com >, putting the single word "info" (without the quotes) in the Subject: field of the first email, and the single word "subscribe" in the Subject: field of the second email. o Eggheads Official mailing list for the eggdrop software, which is an IRC bot using Tcl as the scripting language. To subscribe to this list, send email to <URL: mailto:majordomo@sodre.net > with subscribe eggdrop in the body of the message. Send email to <URL: mailto:eggdrop@sodre.net >. See <URL: > for more information. o EMIL Emil is a package for converting mail messages from one format to another. To join the mailing list, send mail to <URL: mailto:emil-info-request@uu.se >. o epics-tcl VxEpics Tcl/Tk developement list To subscribe, send email to <URL: mailto:listserv@lbl.gov > with the following line in the body of the message: subscribe epics-tcl FIRST_NAME LAST_NAME o Exmh exmh is a GUI for MH mail. It is available at <URL: > There are 3 mailing lists: To subscribe and unsubscribe to: o the release and patch notice mailing list, send email to: <URL: mailto:exmh-announce-release@parc.xerox.com > . o the release/patch notices, as well as discussions among exmh users, send mail to <URL: mailto:exmh-users-request@parc.xerox.com > o the release/patch notices, user discussion and programmer discussions, send mail to <URL: mailto:exmh-workers-request@parc.xerox.com > Be sure to include the word subscribe or unsubscribe as appropriate. Include your preferred email address if you want to be sure it is used. This mailing list appears to have moved to <URL: >, with requests going to <URL: mailto:exmh-workers-request@redhat.com >. o FastCGI FastCGI is a technique of improving cgi performance by prestarting one's application. An archive for this list is available at <URL: >. o FileRunner Mailist for announcements of new releases of FileRunner, which combines a GUI local file manager with an GUI ftp browser and HTTP downloading. To subscribe to the FileRunner mailing list, send email to Henrik Harmsen at <URL: mailto:hch@cd.chalmers.se >. o floater Mailing list which discusses the progress of the floater bridge playing program and related topics. To subscribe or unsubscribe, send mail to <URL: mailto:floater-list-request@priam.cs.berkeley.edu >. These mail messages are processed by a human and will usually not be individually acknowledged. General questions should _not_ be sent to this address. o gnntools-announce Distributes announcements about the GNN Server (which uses tcl as an extension language), such as bug fixes, updates, and important information for developers and users. This is not a discussion list. To subscribe to gnntools-announce, send email to <URL: mailto:majordomo@navisoft.com > with the following line in the body of the message: subscribe gnntools-announce o GPIB Mailing list to discuss the GPID driver interface written in Tk. Contact <URL: mailto:gpib-request@koala.chemie.fu-berlin.de > for more details. o Grail Grail is an internet browser, written in Python/Tk. To join the mailing list, send email to <URL: mailto:grail-request@python.org >. o GRASS The GRASS Users's mailing list is the location to discuss the development of the GRASS GIS widget. To subscribe, send email to <URL: mailto:grassu-request@moon.cecer.army.mil >. o Groupkit To subscribe to the Groupkit mailing list, which deals with an extension to Tcl enabling real-time groupware development, drop your email request to <URL: mailto:groupkit-users-request@cpsc.ucalgary.ca > or send bug and feedback to <URL: mailto:groupkit-bugs@cpsc.ucalgary.ca >. o GuiBuilder This low volume mailing list discusses the GuiBuilder also known as TclGui. Send email to <URL: mailto:majordomo@banffcentre.ab.ca > with a body message of "subscribe tclgui" to join the TclGUI mailing list. An archive for this list is available at <URL: > . o Guile Guile is a portable embeddable Scheme implementation written in C. It provides a machine independent execution platform. A binding between Tcl/Tk and Guile is available. To subscribe to the Guile mailing list, send mail to <URL: mailto:guile-request@cygnus.com > to subscribe, then send messages to <URL: mailto:guile@cygnus.com >. o ical Two mailing lists have been set up for ical-related information. Ical is a calendar application written using the Tk toolkit. Send mail to one of the two addresses below to be added to the mailing lists. <URL: mailto:ical-announce-request@lcs.mit.edu > <URL: mailto:ical-request@lcs.mit.edu > *** Do not forget the "-request" part!!! *** The two mailings lists are: o <URL: mailto:ical-announce@lcs.mit.edu > New source code (including beta releases), and other announcements of high interest to ical installers/users/hackers. The traffic on this list should be fairly low. o <URL: mailto:ical@lcs.mit.edu > This list will be used for general discussion about ical. Mail sent to "ical-announce" will be automatically forwarded here, so you do not have to subscribe to both lists. o incr Tcl A mailing list used to discuss [incr Tcl] and related packages. For more info, see <URL: >. To subscribe, send a message with subject "subscribe" to: <URL: mailto:itcl-request@tcltk.com > Non-administrative traffic should be sent to: <URL: mailto:itcl@tcltk.com > During late 1997 FindMail began archiving the mailing list. See <URL: > to see what is currently available. Also, Tcl Developer's Xchange has an archive as well: <URL: >. o incr tcl distributed version: Distinct This is a mailing list for discussion of a distributed processing version of incr tcl. To join send a message to <URL: mailto:mailbase@mailbase.ac.uk > where the body contains the line join distinct firstname lastname To send to the list, mail: <URL: mailto:distinct@mailbase.ac.uk > o IVS The Inria Videoconverencing System (IVS) provides a part of the interface for the MBONE support software. It uses either Motif or Tk. Contact <URL: mailto:ivs-users-request@sophia.inria.fr > to join in discussions on the system. o Jacl A discussion list relating to the Tcl written in Java tool Jacl is available. Archives as well as info on subscribing, unsubscribing, etc. of this mailing list can be found at <URL: >. This mailing list is only for discussion of the Jacl tools - discussion of Tcl/Tk, etc. should be directed to <URL: news:comp.lang.tcl >. o KIS - Kernel Information Services The KIS interpreter is a shareware package which provides access to the UNIX administrator to various kernel information. Parallelograms has setup a mailing list for discussion of KIS. To subscribe, send the message subscribe kis your-e-mail-address@your.site to <URL: mailto:majordomo@pgrams.com >. For more information, send the message "help" to <URL: mailto:majordomo@pgrams.com >. o LinuxPro A mailing list for those folk programming on Linux platforms. This list covers all aspects of programming on Linux, regardless of the language. Tcl was specifically mentioned as being an acceptible topic. To subscribe, send mail to <URL: mailto:majordomo@netsteps.com > with either subscribe linuxpro or subscribe linuxpro-digest in the body of the message. o Macintosh Tcl This Mailing List is devoted to the issues of Tcl on the Macintosh. This includes (but not limited to) such topics as ports of Tcl to the Mac (MacTcl), Tcl questions relating only to the Mac (file I/O etc.), and porting of Tk to the Mac. It is also a good forum for issues concerning Tcl based applications such as Alpha and Tickle. To join or leave the mailing list. see List-Help: <URL: mailto:tcl-mac-request@lists.sourceforge.net?subject=help > List-Post: <URL: mailto:tcl-mac@lists.sourceforge.net > List-Subscribe: <URL: >, <URL: mailto:tcl-mac-request@lists.sourceforge.net?subject=subscribe > List-Id: Tcl on the Macintosh <URL: tcl-mac.lists.sourceforge.net > List-Unsubscribe: <URL: >, <URL: mailto:tcl-mac-request@lists.sourceforge.net?subject=unsubscribe > See <URL: > for online archives of the mailing list while hosted at Sun and <URL: > for online archives of the mailing list while hosted at a few other places. However, Currently, the mailing list and archives are being hosted at <URL: >. o Microsoft Windows port of Tk Simon Kenyon <URL: mailto:simon@news.itc.icl.ie > announced in early April 1994 that the Information Technology Centre of Dublin, IRELAND was undertaking the port of Tk to MS-Windows. He has set up the mstk mailing list for those interested in discussing it. If interested, send mail to <URL: mailto:mstk-list-request@itc.icl.ie > to join the list and send comments and code to <URL: mailto:mstk@itc.icl.ie >. With the releases of Tk now coming with Windows support, I suspect if this mailing list is still going the topics have changed. o Mini SQL interface A mailing list for mSQL, a Tcl interface to the Mini SQL database server by David J. Hughes, has been formed. If interested, send a subscription request to <URL: mailto:msql-list-request@Bond.edu.au >. o Minotaur A mailing list to discuss TinyScript/2, described at <URL: >. Minotaur mailing list - to join, send an email to <URL: mailto:minotaur-add@mini.net > o Mod_dtcl Mod_dtcl is an Apache module enabling server side Tcl scripting. Mail a body line of subscribe to <URL: mailto:mod_dtcl-request@prosa.it > . o Modules Richard Elling and others have set up a mailing list for discussion of the use of the Modules tcl package, as well as related packages such as user-setup. If you would like to be added to the modules-interest mailing list, send email to <URL: mailto:majordomo@eng.auburn.edu > with the line subscribe modules-interest 0 moodss If you use moodss (Modular Object Oriented Dynamic SpreadSheet), develop modules for it, would like to hear about new features and improvements, give your input, make requests, ... you are welcome to use the new moodss mail list: - to subscribe, send mail to <URL: mailto:moodss-request@ml.free.fr?subject=subscribe > with "subscribe" as subject - to use, send mail to mailto:moodss@ml.free.fr - to unsubscribe, send mail to <URL: mailto:moodss-request@ml.free.fr?subject=unsubscribe > with "unsubscribe" as subject More information on moodss can be found at <URL: >. o MS-DOS Windows Tk Users A mailing list for the users of TkWin, the Univ. of Kentucky's port of Tcl 7.3 and Tk 3.6a to MS-DOS Windows is available at <URL: mailto:tk-win-users-request@ms.uky.edu > and msgs to <URL: mailto:tk-win-users@ms.uky.edu > o Nanny Parallelograms has setup a mailing list for discussion of Nanny. To subscribe, send the message subscribe kis your-e-mail-address@your.site to <URL: mailto:majordomo@pgrams.com > . For more information, send the message "help" to <URL: mailto:majordomo@pgrams.com >. This mailing list is also used to discuss our Kernel Information System (KIS). o Netplug Mailing list to discuss the Netplug program, a Tcl/Tk extensible client for multiple protocols, multiple connections to networks. To subscribe, send a message to <URL: mailto:listserv@hplyot.obspm.fr > with a mail body of the line subscribe netplug FirstName LastName where you supply your own first and last name. o Objective-Framework Mailing list to discuss this commercial product which provides true language independence to the Objective-C object model. The framework supports ObjectiveTcl. Send a subscription message to <URL: mailto:objsys-l-request@tiptop.com >. o ObjectiveTcl Mailing list to discuss this commercial product which is an advanced object-oriented environment for NEXTSTEP/OpenStep. It provides full access to and from Objective-C. Discussions of ObjectiveBrowser, a class browser which can be used to interact with live objects, also occur here. Send a subscription message to <URL: mailto:objtcl-l-request@tiptop.com >. o odce21 This list discusses IBM's beta program for DCE 2.1. One component of this package is the DCE Control Program (DCECP), an administration tool which uses Tcl for scripting. You can subscribe to <URL: mailto:Majordomo@austin.ibm.com >, sending an e-mail message containing the following two lines in the body of the message. subscribe ODCE21 end o OSE OSE is a collection of programming tools and class libraries for C++ development. One of the libraries provided allows integration of Tcl/Tk libraries into applications. For further details, contact <URL: mailto:ose@nms.otc.com.au >. o Oz Users Oz is a concurrent constraint programming language. An OO interface via Tcl/Tk is available. To subscribe, contact <URL: mailto:oz-users-request@dfki.uni-sb.de >. o Palmscript List to discuss scripting languages for handheld devices, such as a Tcl like language to PalmOS devices such as a PalmPilot. See <URL: > for info on how to subscribe, how to post, how to send administrative requests, etc. o Palmsupport-tcl An effort to build applications and extensions for desktop tools in support of the Palm devices. To subscribe, visit <URL: >. See <URL: > for miscellaneous details. o PIDDLE Piddle is a Python drawing API that supports a back end output of Tk. Visit the mailing list at <URL: > to subscribe. o PLPLOT This is a mailing list in support of the plotting system called PLPLOT, which has available a Tk interface. To subscribe, send a request to <URL: mailto:plplot-request@dino.ph.utexas.edu > o Plume <URL: >. o Project E.L.M.O. An effort to improve the currency and search access to the comp.lang.tcl FAQs. Visit <URL: > to subscribe. See <URL: > for miscellaneous details. o pTk This is a mailing list in support of the development of the Tk extension to Perl 5. For tutorial or beginner questions, use <URL: news:comp.lang.perl.tk > instead. To subscribe, send mail to <URL: mailto:majordomo@lists.stanford.edu > with 'subscribe ptk' in the body of the message. Please don't send subscribe requests to the list itself. An archive of the mailing list can be found at <URL: >. o Ptolemy Ptolemy is a simulation and prototyping system which uses tcl. To join the mailing list, send email to <URL: mailto:ptolemy-request@ohm.eecs.berkeley.edu > or <URL: mailto:ptolemy-hackers-request@ptolemy.eecs.berkeley.edu >. o PTUI PTUI is the Python/Tkinter User Interface - a development environment for Python and Tk. To join the mailing list, send word subscribe in the body. o Qddb Qddb is a Quick and Dirty Database package. It uses Tcl as a configuration language and has a Tk interface. To join the mailing list, send email to <URL: mailto:qddb-users-request@ms.uky.edu >. o RadTcl RadTcl is a Tcl plugin for Netscape servers. To join fill in the form at <URL: > o Ratatosk TkRat's announcement and discussion mailing lists. To subscribe, send mail either to <URL: mailto:ratatosk-announce-request@dtek.chalmers.se > or <URL: mailto:ratatosk-request@dtek.chalmers.se >. o safe-tcl Safe-tcl is an extension to Tcl which one can use to process incoming email msgs as tcl scripts. To subscribe, send a msg to <URL: mailto:safe-tcl-request@uunet.uu.net > and then further email msgs to <URL: mailto:safe-tcl@uunet.uu.net >. o SciTeXt SciTeXt is a Tcl/Tk based word processing program. To join the scitext mailing list, send email to <URL: mailto:server@uni-paderborn.de > with the line subscribe scitext in the body of the message. o Scotty Scotty is a networking extension for Tcl. Info on a mailing list for the extension can be found at <URL: >. o Scripters This list is maintained by the center for EUV Astrophsics for the purpose of discussing scripting languages of various kinds, including Tcl and Expect. To send mail to all members of the list, send your message to <URL: mailto:scripters@cea.berkeley.edu >. You will be included in the distribution of the message. Archives of the mailing list are kept at <URL: >. Administrative messages about the list should be addressed to <URL: mailto:scripters-owner@cea.berkeley.edu >. o ServiceMail Toolkit ServiceMail is a stand-alone email server written in C and Tcl. It takes incoming email requests and can perform tasks for the sender. To join the mailing list, send email to <URL: mailto:servicemail-help@eitech.com > or subscribe to servicemail-help mailing list by sending a message to the "listserv subscribe servicemail-help your-real-name" service at <URL: mailto:services@eitech.com >. The status of this mailing list is unknown. o small-tcl This is a mailing list for people interested in discussing and contributing to changes in the Tcl scripting language to make the core language itself smaller. The usual reason for wanting to do this is to make (keep) Tcl to be a good language for small systems. Please see the project home page at <URL: > for further details. To subscribe, visit <URL: >. o Sound Studio Sound Studio is a sound editing software package. To join the mailing list, send email to <URL: mailto:Majordomo@leeds.ac.uk > with the words subscribe studio-bug in the body of the message. o STk Scheme/Tk is a scheme interpreter which can access the Tk graphical package. There is a mailing list for STk. To subscribe the mailing list just contact <URL: mailto:stk-request@kaolin.unice.fr > with the Subject line of "subscribe". o SWIG Simplified Wrapper and Interface Generator (SWIG) is an interface package which makes it easier to add C code to one's Tcl environment (as well as other languages). <URL: > <URL: > is the location to use for subscription related info, or send mail to <URL: mailto:Swig-request@cs.uchicago.edu > with the line subscribe swig in the body of the message. An archive of the mailing list can be found at <URL: > o TACOMA A list discussing support for agents written in various languages, including Tcl. Fill out <URL: > to be put on the mailing list. o TASH For discussion of the Ada binding to Tcl/Tk. See <URL: > for details. To contact the owner, send mail to <URL: mailto:tash-request@calspan.com >. To contact the mailing list server, send listserv commands to <URL: mailto:listserv@calspan.com >. To send mail to the mailing list, contact <URL: mailto:tash@calspan.com >. o tcl-httpd Discussions on Brent Welch's tcl http server. Send TclHttpd-users mailing list submissions to <URL: mailto:tclhttpd-users@lists.sourceforge.net > To subscribe or unsubscribe via the World Wide Web, visit <URL: > or, via email, send a message with subject or body 'help' to <URL: mailto:tclhttpd-users-request@lists.sourceforge.net > You can reach the person managing the list at <URL: mailto:tclhttpd-users-admin@lists.sourceforge.net > o tcl-i8n Tcl/Tk internationalization issues mailing list. See the archives, subscribe, etc. see <URL: > . o Tcl-RPC Discuss implementing XML-RPC in Tcl. To subscribe to the list, send email to <URL: mailto:requests@userland.com > with the subject: subscribe Tcl-RPC To subscribe to the digest version, send email to <URL: mailto:requests@userland.com > with the subject: subscribe digest Tcl-RPC To post to the list once you've subscribed, send email to Tcl-RPC@userland.com. To unsubscribe from the regular mail or digest version, send email to <URL: mailto:requests@userland.com > with the subject: unsubscribe Tcl-RPC o tcl_cruncher tcl_cruncher is a Tcl pseudo compiler and syntax checker tool and this list discusses it. To subscribe, send email to <URL: mailto:listserv@hplyot.obspm.fr > with the following line in the body of the message. subscribe tcl_cruncher FIRST_NAME LAST_NAME o Tcl/Tk plug-in mailing list tclplug is a mailing list dedicated to discussing the new Tcl/Tk Netscape plug-in. To join, send email to <URL: mailto:listserv@hplyot.obspm.fr > with the line subscribe tclplug Firstname Lastname in the body (where your name is substituted for Firstname Lastname). o Tcl Application Users Online forum, which you can join by accessing <URL: >. Purpose is for _users_ of Tcl applications to discuss problems and provide support. o tcl binary data access mailing list tclbin is a Tcl extension to allow binary objects. Send a "subscribe tclbin Your Name" line to <URL: mailto:listserv@mail.box.eu.org > to subscribe to the tclbin mailing list. o Tcl in French Liste des personnes interressees par TCL-TK . To subscribe, send email to <URL: mailto:listserv@loria.fr > with the following line in the body of the message. subscribe tcl FIRST_NAME LAST_NAME o Tcl in Russian Discussions on Tcl related issues conducted in Russian. To subscribe, send a message to <URL: mailto:majordomo@ice.ru > with the message body subscribe tcl o Tcl Database Developers Mailing List This mailing list is for discussion announcements, and general info for Tcl programmers using database APIs. This includes Oracle, Sybase, Ingres, and other commercial DB engines as well as PG95, miniSQL, and also "micro" DBs and pseudo-DBs. Please do not send WISQL or WOSQL bug reports to this list; it is for developer rather than end-user issues. To subscribe to this list send mail to <URL: mailto:tcldb-request@ucolick.org > and in the body of the message write subscribe Follow the same procedure, but use the word unsubscribe, when you wish to leave the mailing list. Please remember to write to <URL: mailto:tcldb-owner@ucolick.org > with problems about the list itself, or to <URL: mailto:postmaster@ucolick.org > if you have difficulties getting through to the tcldb-owner address. Please do not send subscribe and unsubscribe messages to the list itself. o Tcl SNMP mailing list SNMP is the Simple Network Management Protocol. Work on a Tcl interface to SNMP v2 is being done by the SNMP Tcl mailing list. It can be contacted at <URL: mailto:majordomo@data.fls.dk >. o Tcl XML Documentation Project An effort to convert all Tcl/Tk documentation from troff into XML. To join the mailing list, contact <URL: mailto:tcldoc@hwaci.com >. <URL: > is a URL to info about the whole effort. o tcldav Mailing list discusses creating a DAV client in Tcl. This involves HTTP 1.1 and XML. To subscribe, visit <URL: >. o TclJava Mailing list to discuss TclJava and TclBlend extensions. Send tcljava-user mailing list submissions to <URL: mailto:tcljava-user@lists.sourceforge.net > To subscribe or unsubscribe via the World Wide Web, visit <URL: > or, via email, send a message with subject or body 'help' to <URL: mailto:tcljava-user-request@lists.sourceforge.net > You can reach the person managing the list at <URL: mailto:tcljava-user-admin@lists.sourceforge.net > o tcLex Since 11/17/1998, tcLex has a dedicated mailing list. The Web site for this list is: <URL: >. o tclMIDI mailing list tclMIDI is a Tcl extension to generate MIDI music information. To subscribe, send mail to <URL: mailto:tclmidi-request@boogie.com > and include the phrase subscribe tclmidi in the body of the message. The subject is ignored. o tclMotif tclMotif is an extension which provides true Motif access to a Tcl program. This mailing list is maintained by <URL: mailto:listserv@ise.canberra.edu.au >. To subscribe, send mail to this address with the request subscribe tclMotif your_name and you will receive a mail message acknowledging this. From then on, send mail to <URL: mailto:tclMotif@ise.canberra.edu.au > and it will be distributed. o tclobj tclobj is a Tcl extension for allow dynamic loading, invoking, and passing of C++ objects. The mailing list is to provide a means of information exchange, announcmenets, and making other Tcl supporting classes publically available. To subscribe, send mail to <URL: mailto:tclobj-request@belle.fpp.tm.informatik.uni-frankfurt.de > with a subject of "subscribe". o Tcl-Pubs Tcl-Pubs is a mailing list for people interested in reviewing or writing new Tcl related publications. Visit <URL: > for more details, to subscribe, etc. o TclProp Mailing list to discuss the tclprop extension. TclProp is a set of functions for declarative programming using data propagation. Send your subscription request to <URL: mailto:tclprop-request@cs.umn.edu >. o tcltk This mailing list is for all tcl'ers that want to be a part of the Tcl/Tk Journal - a free online ezine <URL: > for Tcl/Tk and all Tcl "flavours" - Expect, TclX, itcl etc. To subscribe, visit <URL: > . o TclXML Besides the effort to convert Tcl doc into XML, there is a mailing list whose topics include, but are not limited to, TclXML distribution, TclDOM specification and TclExpat. See <URL: > for info on subscriptions, archives, etc. o TclX-Win A mailing list for users of the TclX port to Windows 95 and NT. To subscribe, send a mail message to <URL: mailto:majordomo@grizzly.com > with the line subscribe tclx-win in the body (not subject) of the message. Mail is then sent to <URL: mailto:tclx-win@grizzly.com >. An archive for this list is available at <URL: >. o TeamRooms TeamRooms is an internet based groupware collaboration tool. See <URL: > for more details. To discuss the software, send e-mail to <URL: mailto:teamrooms-info-request@cpsc.ucalgary.ca > with the word "subscribe" in the body of your message. A subset of the traffic on teamrooms - just the annoucements - is also available. Send e-mail to <URL: mailto:teamrooms-announce-request@cpsc.ucalgary.ca > with the word "subscribe" in the body of your message. If you are on the teamrooms-info list, you should not subscribe to the -announce list also. o TeenyMUD TeenyMUD is a multi-user dungeon program - allows multiple users to role play and converse in 'real time'. It uses Tcl. To join the mailing list, contact <URL: mailto:teeny-list-request@fido.econlab.arizona.edu > and then send your mail to <URL: mailto:teeny-list@fido.econlab.arizona.edu >. o TEKI TEKI is a tool for creating Tcl installation applications. This mailing list discusses the tool. <URL: mailto:tcl-ext@cs.cornell.edu > o TIGER TIGER is an environment for learning how to use OpenGL. The mailing list is in support of the Tcl OpenGL extension, the tutorial for learning OpenGL, and the upcoming editor/debugger. For joining the mailing list <URL: mailto:tiger@prakinf.tu-ilmenau.de > send a "subscribe TIGER mailing list" to <URL: mailto:ekki@prakinf.tu-ilmenau.de >. o Tix A mailing list for announcements regarding the Tix widget set is available. Info on this mailing list is available at <URL: >. A second list is available for discussions relating to Tix. See <URL: > . o TkDE Discussion of creating a consistent Tk desktop environment (TkDE ?). Send a message to <URL: mailto:tkde-discuss-request@winehq.com > to subscribe and then send your discussions to <URL: mailto:tkde-discuss@winehq.com >. Here is a web page for the TkDE mailing list <URL: >. o TkDesk TkDesk is a rather sophisticated desktop and file manager for Unix and X. To unsubscribe from the mailing list, send the message unsubscribe tkdesk to <URL: mailto:majordomo@mrj.com >. To send an email to the mailing list, use <URL: mailto:tkdesk@majordomo@shaknet.clark.net >. Archives are available at <URL: >. o tkdiff tkdiff is a graphical 2-way diff/merge file program which works with RCS, SCCS, PVCS, and Perforce. One can buy support from Ede Development as a part of their AccuRev tool set. To subscribe to the tkdiff mailing list, email <URL: mailto:majordomo@ede.com > and put the string subscribe tkdiff end in the body of the message. o tkdvi There are two mailing lists for TkDVI: <URL: mailto:tkdvi-announce@tm.informatik.uni-frankfurt.de > This is a low-traffic moderated mailing list for TkDVI-related announcements such as the publication of new versions. <URL: mailto:tkdvi-users@tm.informatik.uni-frankfurt.de > This is a forum for general exchange between TkDVI users (such as there will be, hopefully). All the traffic from tkdvi-announce shows up here as well, so if you're interested in both lists you only need to read this one. To subscribe to either of these lists, send a message containing a Subject: header of subscribe to <URL: mailto:tkdvi-announce-request@tm.informatik.uni-frankfurt.de > and <URL: mailto:tkdvi-users-request@tm.informatik.uni-frankfurt.de >, respectively. o tkgdb A mailing list to discuss a graphical interface to gdb can be joined by sending a subscription request to <URL: mailto:tkgdb-request@busco.lanl.gov >. However, this email address does not seem to be working at this time. o tkGS A mailing list to discuss the creation of a new graphics subsystem for Tk, with device independence in mind. See <URL: >. o TkHtml A mailing list for discussing D. Richard Hipp's Tk widget for rendering HTML. <URL: > o tkined tkined is a Tk based network editor with a programming interface. To join the tkined mailing list, contact <URL: mailto:tkined-request@ibr.cs.tu-bs.de > . This list appears to be moving to <URL: >. o tkmail Two mailing lists exist in support of the TkMail program. The first list, tkmail-l, is a general purpose list while the second, tkmail-dev, is for detailed development issues. To join either mailing list, send a message to <URL: mailto:listserv@mailbox.slac.stanford.edu > in which the first line of the BODY is subscribe tkmail-l [your_address] or subscribe tkmail-dev [your_address] Obviously, [your_address] should be replaced with your address and is optional (defaults to address in From header). Archives from both lists are accessible on the web at <URL: > <URL: > o tknews tknews is a Usenet news reader, capable of either direct or NNTP news reading. To be added to the general discussion mailing list (tknews) or the bug reports list (tknews-bugs) contact <URL: mailto:mdm@cis.ohio-state.edu > and ask to be added. o tkoct-design This list is for discussions of issues related to the user interface and database for Ptolemy. Discussions include replacing and/or augmenting the current user interface with a new one based on Tcl/Tk. Discussions also include replacing the oct database currently used by Ptolemy. To subscribe, send email to <URL: mailto:majordomo@dewitt.eecs.berkeley.edu > with the following line in the body of the message: subscribe tkoct-design Contact Christopher Hylands <URL: mailto:cxh@eecs.berkeley.edu > for further information. This list appears to be moving to <URL: >. o TkVP TkVP is a video poker application, built using TclProp. To be added to the TkVP mailing list, contact <URL: mailto:tkvp-request@cs.umn.edu >. o Tkwm Tkwm is an X11 window manager written using the Tk tool kit. To subscribe to the mailing list, send a message with the word help to <URL: mailto:MajorDomo@comp.vuw.ac.nz >. Messages are set to <URL: mailto:tkwm@comp.vuw.ac.nz >. o tkWWW tkWWW is a tk-based WorldWideWeb client. Contact <URL: mailto:tk-www-request@athena.mit.edu > to join the mailing list and send your messages to <URL: mailto:tk-www@athena.mit.edu >. Also see <URL: > for more information about tkWWW. o tmk tmk <URL: > is a freely available tool that combines the functionality of a traditional make utility with Tcl. The tmk mailing list can be reached at <URL: > o Tribeirc Tribe mirc scripts, bugs, updates, london(UK) phreaking, mirc addons, and group userfiles. To subscribe, visit <URL: > o VMS Tcl/Tk Folks interested in Tcl on VMS in general can sign up to the <URL: mailto:vms-tcl@src.honeywell.com > mailing list for more details. An archive for the mailing list is available at: <URL: > o VSTCL A Virtual Reality Markup Language Tcl extension. Send mail to <URL: mailto:vstcl-request@sme.co.jp > to subscribe. o vtcl This list is for any discussions relevant to the use of or development of a graphically oriented Tcl development environment currently known as Visual Tcl. See <URL: > for subscription and archive info. o WAFE WAFE is a Athena Widget front end which uses Tcl. To join the wafe mailing list, contact <URL: mailto:wafe@wu-wien.ac.at >. o wintcl This mailing list is devoted to issues relating to Tcl on the Microsoft Windows platform (including Windows 3.1, '95 or NT). An archive for this list is available at <URL: >. o WOBBLE WOBBLE - Web of Binary Building and Linking Engines - is an idea of creating a mechanism for generating binary versions of extensions from a variety of machines. See <URL: > for some introductory remarks. Contact Jean-Claude Wippler <URL: mailto:jcw@equi4.com > to get on this mailing list. o X Directory A mailing list to discuss the Tcl/Tk based directory and file manager. Contact <URL: mailto:majordomo@vespa.uni-siegen.de > by sending "subscribe ml-xdirector" in body. o xbatcheck A mailing list to discuss this simple battery ife application. See <URL: > for subscription information. o XF-L XF is a Graphical User Interface builder which generates Tk and Tcl code. To subscribe to the xf mailing list, send a "subscribe XF-L Your Name" line to <URL: mailto:listserv@listserv.gmd.de >. To unsubscribe from this list send the text: unsubscribe XF-L in the body of the message to: <URL: mailto:listserv@LISTSERV.GMD.DE > Human administrator: XF-L-request AT LISTSERV.GMD.DE Replace "AT" with @. This is to protect this list owner address from spammers. This list appears to be moving to <URL: >. o X Protocol Engine Library (XPEL) To join, send email to <URL: mailto:xpel-request@cs.unc.edu >. XPEL uses Tcl for an embedded interpretor as well as uses safe-tcl in external monitor programs. o xtem-list Discussion mailing list for the xtem_texmenu project. Subscribe by sending email to <URL: mailto:majordomo@iwd.uni-bremen.de > with a message body of subscribe xtem-list end o YART YART is a imaging software package based on Tk, OpenGL, etc. To join, send mail with subject "subscribe YART mailing list" to <URL: mailto:ekki@prakinf.tu-ilmenau.de > . Then send mail to <URL: mailto:yart@prakinf.tu-ilmenau.de >. GENERIC is a 3D graphics kernel related to YART. To subscribe to its mailing list: send mail with subject "subscribe GENERIC mailing list" to <URL: mailto:ekki@prakinf.tu-ilmenau.de > . Then send mail to <URL: mailto:generic@prakinf.tu-ilmenau.de >. o Zircon Zircon is a Tk interface to IRC. To subscribe, send email to <URL: mailto:zircon-request@catless.newcastle.ac.uk >. From: FAQ General information Subject: -IX- Where can I find the FAQ and who do I contact for more information about it? I ]
http://www.faqs.org/faqs/tcl-faq/part2/
CC-MAIN-2016-07
refinedweb
18,355
66.74
.datatype;17 18 import java.util.Vector ;19 20 /**21 * Represents a postal address. Essentially holds a simple set of AddressLines,22 * but can be adorned with an optional useType attribute and sortcode. The23 * useType attribute is used to describe the type of the address in24 * freeform text. Examples are "headquarters", "billing department", etc.25 * The sortCode values are not significant, but can be used by user-interfaces26 * that present contact information in some ordered fashion, thereby using the27 * sortCode values.28 *29 * @author Steve Viens (sviens@apache.org)30 */31 public class Address implements RegistryObject32 {33 String useType;34 String sortCode;35 String tModelKey;36 Vector addressLineVector;37 38 /**39 * Constructs a new Address with no address-lines and no useType or sortCode40 * attribute.41 */42 public Address()43 {44 }45 46 /**47 * Constructs a new Address with no address-lines, but with the given useType48 * and sortCode attributes.49 *50 * @param type The usetype of the new address, or null if the address51 * doesn't have a usetype.52 * @param sort The sortcode of the new address, or null if the address53 * doesn't have a sortcode.54 */55 public Address(String type,String sort)56 {57 this.useType = type;58 this.sortCode = sort;59 }60 61 /**62 * Sets the usetype of this address to the given usetype. If the new usetype63 * is null, this address doesn't have a usetype anymore.64 *65 * @param type The new usetype of this address, or null if the address66 * doesn't have an usetype anymore.67 */68 public void setUseType(String type)69 {70 this.useType = type;71 }72 73 /**74 * Returns the usetype of this address.75 *76 * @return The usetype of this address, or null if this address doesn't have77 * an usetype.78 */79 public String getUseType()80 {81 return this.useType;82 }83 84 /**85 * Sets the sortcode of this address to the given sortcode. If the new86 * sortcode is null, this address doesn't have a sortcode anymore.87 *88 * @param sort The new sortcode of this address, or null if the address89 * doesn't have a sortcode anymore.90 */91 public void setSortCode(String sort)92 {93 this.sortCode = sort;94 }95 96 /**97 * Returns the sortcode of this address.98 *99 * @return The sortcode of this address, or null if the address doesn't100 * have a sortcode.101 */102 public String getSortCode()103 {104 return this.sortCode;105 }106 107 /**108 * Sets the key of this tModel to the given key.109 *110 * @param key The new key of this tModel.111 */112 public void setTModelKey(String key)113 {114 this.tModelKey = key;115 }116 117 /**118 * Returns the String of this Address.119 *120 * @return The key of this tModel.121 */122 public String getTModelKey()123 {124 return this.tModelKey;125 }126 127 /**128 * Add a new addressline to this address. The addressline is added at the129 * end of the already existing set of addresslines.130 *131 * @param line The addressline to be added to this address.132 */133 public void addAddressLine(AddressLine line)134 {135 if (this.addressLineVector == null)136 this.addressLineVector = new Vector ();137 this.addressLineVector.add(line);138 }139 140 /**141 * Add a collection of new addresslines to this address. The new142 * addresslines are added at the end of the set of the already existing143 * addresslines.144 *145 * @param lines The collection of addresslines to add.146 */147 public void setAddressLineVector(Vector lines)148 {149 if (this.addressLineVector == null)150 this.addressLineVector = new Vector ();151 this.addressLineVector = lines;152 }153 154 /**155 * Returns the addresslines of this address.156 *157 * @return The addresslines of this address. If this address doesn't have158 * any addresslines, an empty enumeration of addresslines is returned.159 */160 public Vector getAddressLineVector()161 {162 return this.addressLineVector;163 }164 } Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/apache/juddi/datatype/Address.java.htm
CC-MAIN-2017-30
refinedweb
649
68.87
Rock Hound Write a subclass of the Actor class called RockHound. The RockHound loves to to move toward any Rock in the grid. You will need to write two methods, getRockLocation and act. Part (a): Write the method getRockLocation. It returns either a valid Location in the grid gr that has a Rock in it, or else null if there are no Rocks in the grid. Part (b): Complete the method act. If there is a Rock in the grid, it turns toward the Rock. If the the adjacent location toward the Rock is valid and empty, it moves there. If there is no Rock in the grid, it behaves like an Actor. You may presume the method getRockLocation works properly, regardless of your answer to part (a). RockHound.gif RockHoundTester.java import info.gridworld.actor.*; import info.gridworld.grid.*; import java.awt.Color; public class RockHoundTester { public static void main(String[] args) { ActorWorld world = new ActorWorld(); world.add(new Location(7, 8), new Rock()); world.add(new Location(3, 3), new Rock()); world.add( new RockHound()); world.add(new Location(8, 0), new Bug()); world.show(); } } RockHound.java import java.util.ArrayList; import info.gridworld.actor.*; import info.gridworld.grid.*; public class RockHound extends Actor { public Location getRockLocation(){ //part (a) } public void act(){ //part (b) } }
https://mathorama.com/apcs/pmwiki.php?n=Main.RockHound
CC-MAIN-2021-04
refinedweb
216
69.89
I have video 450mb. I would like to upload it to xvideos.com I use in my script xvideos_log_data = {'login': xv_login, 'password': password, 'referer': '', 'log': 'Login to your account'} def xvideos(f_path): _print('xvideos started uploading...') try: s = requests.Session() s.post('', data=xvideos_log_data, headers=headers) rp = s.get('') apc = re.search(r'onclick="launch_upload_basic\(\'(.*?)\'\)', rp.text).group(1) payload = {'APC_UPLOAD_PROGRESS': apc, 'message': ''} r = s.post('', data=payload, files={'upload_file': open(f_path, 'rb')}, headers=headers) edt = re.search(r'<a href="(.*?)" target="_top"', r.text) if edt is None: _print(re.search(r'inlineError.*>(.*?)<', r.text).group(1)) return payload = {'title': make_title(), 'keywords': ' '.join(make_tags()), 'description': choice(description), 'hide': 0, 'update_video_information': 'Update information'} r = s.post('' + edt.group(1), data=payload, headers=headers) _print('xvideos finished uploading') except Exception as error: _print(error) finally: return The problem is very probably the Python httplib code beneath the requests library. It was horrible for chunked encoding streaming in older Python versions (2.2), now it is just pretty bad. By replacing it with a custom built http layer directly on the socket and handling buffers better, i could get an application to stream with 2% CPU and like full link utilization on a fast network link. Httplib could only achieve like 1 MB/s with 50% or more CPU usage due to very inefficient buffering. httplib is fine for short requests, but not so good for huge uploads (without tweaking/hacking). You can try a few things to make things better, depending on your network and OS setup: Tune your socket buffers via setsockoption SO_SNDBUF, if you don't need many connections and have a fast network, something like 4 MB or more is possible, to reduce problems with always empty buffers on fast pipes (10GE and more) Use a different http library (pycurl or Twisted with some patches for example) and use larger buffers for transfers, e.g. make every socket.send() call move a few MB of data and not some tiny 4kB buffers. Python can nearly fully utilize a 10 GE link, if done right.
https://codedump.io/share/0C2zNV8G10Nx/1/upload-large-file-is-too-slow
CC-MAIN-2017-13
refinedweb
346
57.06
Red Hat Bugzilla – Bug 151960 gnome-volume-manager uses 100% cpu Last modified: 2013-03-13 00:47:38 EDT From Bugzilla Helper: User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050322 Epiphany/1.5.8 Description of problem: gnome-volume-manager is using 100% cpu. An strace shows no activity. A signal 15 won't kill it, a nine was needed. How it probably happened: Plugged in usb device, copied things off of it. turned off usb device, then removed cable. The icon was still on the destkop. Right-clicked icon, choose Unmount. Warning showed saying it wasn't mounted, icon disappeared. Version-Release number of selected component (if applicable): How reproducible: Didn't try Steps to Reproduce: x Additional info: Created attachment 112380 [details] output of "strace -o /var/tmp/log.txt gnome-volume-manager" I started gnome-volume-manager before inserting my SM card into the card reader. After it was started with strace, I inserted my card and noted the following messages spewed to the terminal: [sean@localhost ~]$ strace -o /var/tmp/log.txt /usr/bin/gnome-volume-manager manager.c/794: New Device: /org/freedesktop/Hal/devices/volume_part1_size_131047936 manager.c/834: Changed: /dev/sda1 manager.c/771: Added: /dev/sda1 manager.c/919: Mounted: /org/freedesktop/Hal/devices/volume_part1_size_131047936manager.c/312: Photos detected: /media/usbdisk/dcim At this point, I unmounted the drive and then <ctrl-c> my strace. This is still occuring as of today. I just tested this out on my USB card reader. As soon as the card is inserted, gnome-volume-manager spikes to 100% CPU useage. I can unmount the device, but I must kill -9 gnome-volume-manager to bring my system back to normal. Can we escalate this one a bit? did you try the latest version 1.3.1? Also provide a copy of the output of dmesg after you plug the card in. Some card readers have problem with the kernel driver. Grabbed this version from rawhide today. No effect could be noted. I am going to reboot my machine and re-run the tests with more "stracing" and such. More interesting, if not expected results from this issue. If you do not kill gnome-volume-manager, and umount ur media, the second insert of any media fails to mount the device. So, you will have to kill the gnome-volume-manager to get this functionality back. At this point, am I the only one experiencing this issue? Is this only happening with "wierd" USB hardware? I attempted to run gnome-volume-manager with GDB to try to get some useful information about it. Here is what I got when I started it under GDB and inserted my media: manager.c/798: New Device: /org/freedesktop/Hal/devices/volume_part1_size_131047936 manager.c/838: Changed: /dev/sda1 manager.c/775: Added: /dev/sda1 Detaching after fork from child process 16764. manager.c/923: Mounted: /org/freedesktop/Hal/devices/volume_part1_size_131047936 manager.c/313: Photos detected: /media/usbdisk/dcim (no debugging symbols found) ---Type <return> to continue, or q <return> to quit--- Program received signal SIGINT, Interrupt. [Switching to Thread -1208396096 (LWP 16743)] 0x068dc88f in dbus_watch_handle () from /usr/lib/libdbus-1.so.1 (gdb) where #0 0x068dc88f in dbus_watch_handle () from /usr/lib/libdbus-1.so.1 #1 0x068b117a in dbus_connection_open () from /usr/lib/libdbus-1.so.1 #2 0x068b1cba in dbus_connection_dispatch () from /usr/lib/libdbus-1.so.1 #3 0x00c5c057 in dbus_g_pending_call_cancel () from /usr/lib/libdbus-glib-1.so.1 #4 0x00d6a46e in g_main_context_dispatch () from /usr/lib/libglib-2.0.so.0 #5 0x00d6d476 in g_main_context_check () from /usr/lib/libglib-2.0.so.0 #6 0x00d6d763 in g_main_loop_run () from /usr/lib/libglib-2.0.so.0 #7 0x0045c39a in gtk_dialog_run () from /usr/lib/libgtk-x11-2.0.so.0 #8 0x0804b8fa in _start () #9 0x002bc963 in libhal_psi_get_strlist () from /usr/lib/libhal.so.1 #10 0x068b215a in dbus_connection_dispatch () from /usr/lib/libdbus-1.so.1 #11 0x00c5c21e in dbus_g_pending_call_cancel () from /usr/lib/libdbus-glib-1.so.1 #12 0x00d8fd4c in g_vasprintf () from /usr/lib/libglib-2.0.so.0 #13 0x00d6a46e in g_main_context_dispatch () from /usr/lib/libglib-2.0.so.0 #14 0x00d6d476 in g_main_context_check () from /usr/lib/libglib-2.0.so.0 #15 0x00d6d763 in g_main_loop_run () from /usr/lib/libglib-2.0.so.0 #16 0x004cacd5 in gtk_main () from /usr/lib/libgtk-x11-2.0.so.0 #17 0x0804c0c7 in main () (gdb) f 0 #0 0x068dc88f in dbus_watch_handle () from /usr/lib/libdbus-1.so.1 I couldn't really debug the program without recompiling as all symbols have been stripped out... Update today. Still an issue. If you can get a hold of an Epson Stylus CS4600 printer, maybe that will assist u in reproducing the issue. This printer has an integrated card reader and that is what I am using to access my mem card. *** Bug 153984 has been marked as a duplicate of this bug. *** This seems to be a problem when attaching storage with a /dcim directory on it (i.e. it has photos on it and g-v-m is trying to launch gthumb). That narrows it down a bit. Just for the record: I don't use gthumb for importing my images, but a program I made myself for the purpose (which I call fujitrans). Any more useful information I could provide? The issue is a deadlock within D-Bus when using model dialogs (gtk_dialog_run) and dispatching messages as the same time. Going to try and debug the D-Bus issue and failing that just switch to using a non-model dialog for the photo import popup. A bit more help for you. I can confirm that the SM card being placed in my card reader has the "/dcim" dir. Same here. New behaviour this AM after updates. Now I get no notification from the system that there is any activity on the USB card reader. There was a kernel update, so I will attempt to reboot and test to see if that has anything to do with it. At this point, I don't even think I can manually mount the card reader as there is nothing in /var/log/messages about the card being inserted. Nor can I test this bug as g-v-m doesn't get triggered to mount anything. The deadlock has been fixed though I am working on getting d-bus make check to work. If I can't get real packages out to rawhide I will build some test packages for you guys just to make sure it fixes the problem. new dbus packages which should fix this issue are in rawhide and should show up in tomorrows compose. Please update to the new packages and check to see if they fix your issues and report back here on the results. Yep. Did the trick for me. The effort is much appreciated! Nicely done. I installed FC4T2, and updated to rawhide. My computer picked up the card reader when I inserted the card and fired off the picture viewer. No issues noted, I believe we can call this ticket closed. WFM. Thanks!
https://bugzilla.redhat.com/show_bug.cgi?id=151960
CC-MAIN-2017-34
refinedweb
1,192
60.31
In python, you can make http request to API using requests module or native urllib3 module. However requests and urllib3 are synchronous. It means that only one HTTP call can be made at the time in a single thread. Sometimes you have to make multiples HTTP call and synchronous code will perform baldy. To avoid this, you can use multi threading or since python 3.4 asyncio module. Test case In order to show the difference of time between sync and async code, i made a script that read a file with 500 cities names and perform HTTP call to an API to retrieve information about location,population and so on from the city name. Sync code performance Here is the sync code version with requests module @timeit def fetch_all(cities): responses = [] with requests.session() as session: for city in cities: resp = session.get(f"{city}&fields=nom,region&format=json&geometry=centr") responses.append(resp.json()) return responses Finished 'fetch_all' in 38.7053 secs Async code performance I used aiohttp module to make the async code as requests module doesn't support asyncio for now. async def fetch(session, url): """Execute an http call async Args: session: contexte for making the http call url: URL to call Return: responses: A dict like object containing http response """ async with session.get(url) as response: resp = await response.json() return resp async def fetch_all(cities): """ Gather many HTTP call made async Args: cities: a list of string Return: responses: A list of dict like object containing http response """ async with aiohttp.ClientSession() as session: tasks = [] for city in cities: tasks.append( fetch( session, f"{city}&fields=nom,region&format=json&geometry=centr", ) ) responses = await asyncio.gather(*tasks, return_exceptions=True) return responses @timeit def run(cities): responses = asyncio.run(fetch_all(cities)) return responses Finished 'run' in 3.0706 secs Conclusion As you can see, the async version is lot faster than the sync version so if you run into a situation where your code is performing multiple I/O calls then you should consider concurrency to improve performance. However asynchronous version require more work as you can see. I recommend reading python asyncio to learn more about asyncio. Thanks for reading Discussion
https://practicaldev-herokuapp-com.global.ssl.fastly.net/matteo/async-request-with-python-1hpo
CC-MAIN-2020-50
refinedweb
370
56.35