text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
I am going to create an rail application to import a csv file and showing its content in webpage. Everything is working fine except one thing. If the csv file contains quoted strings such as "", ",'' then the program is not working. My app/models/user.rb file is :- class User < ActiveRecord::Base require 'csv' def self.import(file) CSV.foreach(file.path, headers:true) do |row| User.create! row.to_hash end end end you can create a rescue for this error use code like this - may be it works for you! def self.import(file) quote_chars = %w(" | ~ ^ & *) begin CSV.foreach(csv_file, headers: :first_row, quote_char: quote_chars.shift) do |row| User.create! row.to_hash end rescue CSV::MalformedCSVError quote_chars.empty? ? raise : retry end end
https://codedump.io/share/e9MVwUP4uGI5/1/struggling-while-trying-to-import-a-csv-file-in-a-rail-application
CC-MAIN-2016-44
refinedweb
122
62.14
ILocalCache Interface [namespace: Serenity.Abstrations] - [assembly: Serenity.Core] Defines a basic interface to work with the local cache. public interface ILocalCache { void Add(string key, object value, TimeSpan expiration); TItem Get<TItem>(string key); object Remove(string key); void RemoveAll(); } A default implementation of ILocalCache ( Serenity.Caching.HttpRuntimeCache) that uses System.Web.Cacheexists in Serenity.Webassembly. ILocalCache.Add Method Adds a value to cache with the specified key. If the key already exists in cache, its value is updated. Items are hold in cache for expiration duration. You can specify TimeSpan.Zero for items that shouldn't expire automatically. Values are added to cache with absolute expiration (thus they expire at a certain time, not sliding expiration). Dependency.Resolve<ILocalCache>.Add("someKey", "someValue", TimeSpan.FromMinutes(5)); This method, in its default implementation, uses HttpRuntime.Cache.Insert method. Avoid HttpRuntime.Cache.Add method, as it doesn't update value if there is already a key with same key in the cache, and it doesn't even raise an error so you won't notice anything. A mere engineering gem from ASP.NET) ILocalCache.Get <TItem> Method Gets the value corresponding to the specified key in local cache. If there is no such key in cache, an error may be raised only if TItem is of value type. For reference types returned value is null. If value is not of type TItem, an exception is thrown. You may use object as TItem parameter to prevent errors in case a value doesn't exist, or not of requested type. ILocalCache.Remove Method Removes the item with specified key from local cache and returns its value. No errors thrown if there is no value in cache with the specified key, simply null is returned. Dependency.Resolve<ILocalCache>.Remove("someKey"); ILocalCache.RemoveAll Method Removes all items from local cache. Avoid using this except for special situations like unit tests, otherwise performance might suffer.
https://volkanceylan.gitbooks.io/serenity-guide/caching/ilocalcache_interface.html
CC-MAIN-2019-18
refinedweb
318
51.55
Filesystem Magic with Python I recently added a number of examples on working with files and directories with Python and PyFilesystem. Counting Bytes of Python The first example, is count_py.py which recursively sums up the number of bytes stored in a directory, and renders it in a "friendly" format. import sys from fs import open_fs from fs.filesize import traditional fs_url = sys.argv[1] count = 0 with open_fs(fs_url) as fs: for _path, info in fs.walk.info(filter=["*.py"], namespaces=["details"]): count += info.size print(f'There is {traditional(count)} of Python in "{fs_url}"') This script takes a path or a URL. For instance python3 count_py.py ~/projects will sum up the bytes of Python in your projects folder. For me, this gives the following output: There is 227.1 MB of Python in "/Users/will/projects/" This script accepts a path, but it will also work with any supported filesystem. So you could sum the bytes of Python in an archive or cloud server. Finding Duplicates Next up, is find_dups.py which will recursively find duplicate files (even if the filenames are different). It does this by calculating the md5 hash of all the files, and looking for files with matching hashes. It is possible that two different files have the same hash, but the chances are remote. As always, this script works with local files, archives, or network filesystems like S3 or Google Cloud Storage. from collections import defaultdict import hashlib import sys from fs import open_fs def get_hash(bin_file): """Get the md5 hash of a file.""" file_hash = hashlib.md5() while True: chunk = bin_file.read(1024 * 1024) if not chunk: break file_hash.update(chunk) return file_hash.hexdigest() hashes = defaultdict(list) with open_fs(sys.argv[1]) as fs: for path in fs.walk.files(): with fs.open(path, "rb") as bin_file: file_hash = get_hash(bin_file) hashes[file_hash].append(path) for paths in hashes.values(): if len(paths) > 1: for path in paths: print(f" {path}") print() This could be made a little smarter. Rather than calculating hashes for every file (which is comparatively slow), it could first compare filesizes. I've left that as an 'exercise for the reader'! Notice the get_hash function. This will work with a file opened on your local drive, in an archive, or streamed over the network. PyFilesystem hides the gory details from you, so you can write generic code. Uploading files from your local drive This next script is upload.py which opens a local file and uploads it to a server. import os import sys from fs import open_fs _, file_path, fs_url = sys.argv filename = os.path.basename(file_path) with open_fs(fs_url) as fs: if fs.exists(filename): print("destination exists! aborting.") else: with open(file_path, "rb") as bin_file: fs.upload(filename, bin_file) print("upload successful!") Here's how you might upload a file to an FTP server: python3 upload.py starwars.mov Or to Amazon S3 python3 upload.py starwars.mov s3://mybucket/movies/ Deleting your .pyc files Finally, rm_pyc.py is a super simple script that recursively deletes .pyc files. import sys from fs import open_fs with open_fs(sys.argv[1]) as fs: count = fs.glob("**/*.pyc").remove() print(f"{count} .pyc files removes") More examples I'll be adding more scripts to the "examples/" directory in the future. Let me know if you have any ideas for those, or requests... what is the best way to read HDFS files with 2 million records in python3.
https://www.willmcgugan.com/blog/tech/post/filesystem-magic-with-python/
CC-MAIN-2022-27
refinedweb
577
69.89
UPDATE: After receiving a request to modify the code to ignore .lock files, I have an updated to this post. One of the tasks I’ve been automating is publishing a weekly data update to a website. The update consists of shapefile. The trouble with shapefiles is they consist of 3 or more files with the same basename but different extensions in the same directory. Not an overly complicated situation but a common one that ArcGIS does not have a solution out-of-the-box. Below is a bare-bones code snippet to do it. It has both the input shapefile and output zip file hard-coded. The call to the subroutine that does the work is: zipShapefile(wellsShapeFile,wellsZipFile) import zipfile import sys import os import glob wellsShapeFile = "C:/cwi5_bk/WELLS/wells.SHP" wellsZipFile = "C:/cwi5_bk/WELLS/test5.zip" def zipShapefile(inShapefile, newZipFN): print 'Starting to Zip '+inShapefile+' to '+newZipFN if not (os.path.exists(inShapefile)): print inShapefile + ' Does Not Exist' return False if (os.path.exists(newZipFN)): print 'Deleting '+newZipFN os.remove(newZipFN) if (os.path.exists(newZipFN)): print 'Unable to Delete'+newZipFN return False zipobj = zipfile.ZipFile(newZipFN,'w') for infile in glob.glob( inShapefile.lower().replace(".shp",".*")): print infile zipobj.write(infile,os.path.basename(infile),zipfile.ZIP_DEFLATED) zipobj.close() return True zipShapefile(wellsShapeFile,wellsZipFile) print "done!" 2 thoughts on “Zipping a shapefile using python” import zipfile import os import glob #os.getcwd() def zipShapefile(inShapefile): newZipFN = “zipped_”+inShapefile[:-3] + ‘zip’ print ‘Starting to Zip ‘+inShapefile+’ to ‘+newZipFN print (os.path) if not (os.path.exists(inShapefile)): print inShapefile + ‘ Does Not Exist’ return False if (os.path.exists(newZipFN)): print ‘Deleting ‘+newZipFN os.remove(newZipFN) if (os.path.exists(newZipFN)): print ‘Unable to Delete’+newZipFN return False zipobj = zipfile.ZipFile(newZipFN,’w’) for infile in glob.glob(inShapefile.replace(“.shp”,”.*”)): print infile zipobj.write(infile,os.path.basename(infile),zipfile.ZIP_DEFLATED) zipobj.close() return True print “done!” wellsShapeFile = “Clip_vilaine.shp” a = zipShapefile(wellsShapeFile) if a: print “Zipping done!” else: print “An error occurred during zipping.”
http://milesgis.com/2010/12/10/zipping-a-shapefile-using-python/
CC-MAIN-2017-51
refinedweb
339
54.29
sem_trywait, sem_wait - lock a semaphore #include <semaphore.h> int sem_trywait(sem_t *sem); int sem_wait(sem_t *sem); The sem_trywait() function shall lock the semaphore referenced by sem only if the semaphore is currently not locked; that is, if the semaphore value is currently positive. Otherwise, it shall not lock the semaphore. The sem_wait() function shall lock the semaphore referenced by sem by performing a semaphore lock operation on that semaphore. If the semaphore value is currently zero, then the calling thread shall not return from the call to sem_wait() until it either locks the semaphore or the call is interrupted by a signal. Upon successful return, the state of the semaphore shall be locked and shall remain locked until the sem_post() function is executed and returns successfully. The sem_wait() function is interruptible by the delivery of a signal. The sem_trywait() and sem_wait() functions shall return zero if the calling process successfully performed the semaphore lock operation on the semaphore designated by sem. If the call was unsuccessful, the state of the semaphore shall be unchanged, and the function shall return a value of -1 and set errno to indicate the error. The sem_trywait() function shall fail if: - [EAGAIN] - The semaphore was already locked, so it cannot be immediately locked by the sem_trywait() operation. The sem_trywait() and sem_wait() functions may fail if: - [EDEADLK] - A deadlock condition was detected. - [EINTR] - A signal interrupted this function. - [EINVAL] - The sem argument does not refer to a valid semaphore. None. Applications using these functions may be subject to priority inversion, as discussed in XBD Priority Inversion . The sem_trywait() and sem_wait() functions are part of the Semaphores option and need not be provided on all implementations. None. None. semctl , semget , semop , sem_post , sem_timedwait XBD Priority Inversion , Memory Synchronization , <semaphore.h> First released in Issue 5. Included for alignment with the POSIX Realtime Extension. The sem_trywait() and sem_wait() functions/121 is applied, updating the ERRORS section so that the [EINVAL] error becomes optional. SD5-XSH-ERN-54 is applied, removing the sem_wait() function from the ``shall fail'' error cases. The sem_trywait() and sem_wait() functions are moved from the Semaphores option to the Base. return to top of pagereturn to top of page
https://pubs.opengroup.org/onlinepubs/9699919799.2008edition/functions/sem_wait.html
CC-MAIN-2021-39
refinedweb
364
55.03
How to post on Ask-pages editThis page is not intended for new questions.Please post your question on the latest version of Ask, and it shall be given.Please do not edit this part, it is meant as a guide! - Starting on: 23 April 2005 - Ending on:: 8 April 2006 - Previous : Ask, and it shall be given # 2 - Next page : Ask, and it shall be given # 4 Page contents Questions edit automate a windows application[ashish] (8 April 2006): i want to automate a windows application i.e.i want to minimise user involvement in certain procedures and i want windows to perform certain steps automatically can u suggest me any thing related to this using tcl/tkA: See dde, COM, Inventory of IPC methods, Techniques for 'driving' Windows applications, ... example code snippetsLB 5/3/06I am searching for simple example code snippets for a technique in Tk. I wish to display widgets (picklists, messages, etc) and assemblies of widgets in a separate window that overlays my main window without distorting the main window. Using frames I can embed my widgets, but depending on their content, the window they're inserted into may distort ( I use grid).This is such a fundamental operation that I'm sure it must be supported and I've just not found an example of it. I suspect it entails using a frame or toplevel as a container, but have struck out on my experimentation.I have most of the Tcl/Tk books, so pointing to an example therein would be a quick way to help (although I've been searching them).TIA,~Lan BarnesLB Answering my own question: #!/usr/bin/wish proc close_tl {} { destroy .topl } proc call_tl {} { toplevel .topl button .topl.quitb -text Quit -command close_tl pack .topl.quitb -in .topl } button .callb -text Call -command call_tl pack .callbThis little stub does what I was looking for. Adding grab to make it modal and wm to simplify the top level frame are left out for simplicity.Thanks to Clif Flynt for the hints that led me to this. GUIMG 05/04/2006I am facing a problem with my GUI. In my GUI a window gets opened and that window has a browser button for selecting file. If user has clicked on the browse button and the browse window has been opened and user closes the parent window(window having browse burron) by clicking the cross. Both the windows disappear, but after that when I try to do something I get errors which are related to the same code used to open the browser. So I feel that the windows are destroyed but the flow has not returned from the function which was executing the browsing of file. So How can I make sure that the flow too returns back from there.MG (not the one who asked the question, though, the one who uses the MG wiki page;) Which OS are you using? On Windows, tk_getOpenFile uses the native file selector. I assume you're using a Linux system (or MacOS?) which uses the pure-Tcl alternative?MG Yes, I am using the Linux environment, Redhat 3 version.MG Looking at the code which powers those dialogs briefly, it looks like you shouldn't be able to close the other window while the dialog is still open - it sets a grab. But I don't think your browser window should disappear too, though - unless the window with the button was '.', the main window, and by closing it they closed Tk? If not, could you show us what the actual errors you're getting are? (I'm a Windows user myself, so I'm not greatly familiar with the Linux dialogs - anyone who uses them seen an issue like this?)MG -I am providing a simple code which might show the problem after opening the wish, issue following commands - button .a pack .a toplevel .b button .b.a pack .b.a tk_getOpenFile -parent .bNow this will open up the browser window. If you click on cancel of browser, the flow immediately comes back to the shell, while if you click on the cross of "b", then the flow does not come back while b as well as browser window has gone. Tcl shell[MK] I want to create a shell in Tcl/Tk which will allow user to type Tcl Commands and see the result. Is there any enhanced text widget, or any package which can provide this feature. - RS Check the console - built-in for Windows and Mac, easily added on other platforms (see console for Unix). For more bells and whistles, see tkcon. Kanotixwdb (Feb 18, 2006) Question about Tk command raise on Linux distribution Kanotix. The Tk command raise has no effect -- solved, article moved to Problems with raising/lowering windows SOAPsnichols I need help with generating the correct SOAP envelope (at least the SOAP request the web service understands). Please see this link: SOAP Complex Data. Thanks in Advance. Find largest (and smallest) entry in a numerical arrayWas wondering if there's a quick way to pick out the largest (and smallest) entry in a numberical array? For instance, if myArray = [-2 3 6 7] , the largest element is 7, the minimum is -2 . I know I can set up a for-loop to go through each element of the array, but I was just wondering if TCL provides a more sophisticated way of doing this. Thanks! --Arnie - RS: % set try {3 -2 7 6} 3 -2 7 6 % lindex [lsort -real $try] 0 -2 % lindex [lsort -real $try] end 7Lars H: That's a rather unTclish syntax and terminology, so I suspect you're a beginner, aren't you? Given a list of numbers set my_list {-2 3 6 7}then you may indeed, as you observe, find the smallest using a loop, e.g. as follows (making use of the infinity trick): set min infinity foreach num $my_list { if {$num < $min} then {set min $num} }A more compact alternative is however to sort the list and pick out the smallest or largest number using lindex: lindex [lsort -integer $my_list] 0 ; # Smallest element lindex [lsort -integer $my_list] end ; # Largest element(This is an O(n log n) operation and thus asymptotically slower than the time-linear foreach loop, but in practice you'll probably need to have very large lists for this to make a difference.)ECS Or, without infinity: set min [lindex $my_list 0] set max $min foreach num $my_list { if {$num < $min} then {set min $num} if {$num > $max} then {set max $num} } wheel-mouseMG Feb 12 2006 - I'm on Windows XP, and use a wheel-mouse. The drivers/software which came with the mouse include a feature where you can click the mouse wheel, and then move the mouse in any direction to scroll (clicking the button again turns this feature off). It works in the vast majority of applications on Windows - I can think of very few where it doesn't - but none of my Tk text widgets can be scrolled with it (or any other Tk widgets, I don't believe). Where it works, the feature knows whether the application in question can scroll horizontally/vertically/both, and displays a different cursor accordingly. Does anyone know why this doesn't work in Tk apps - is it that Tk isn't "registering" the fact that the window can be scrolled (a wild guess, but the most logical thing I can think of)? Anyone know how hard it might be to fix this? (I've seen this feature with many different (brands of) mice, with different software providing the feature, and it's never worked in Tcl/Tk apps.) Thanks for your help :)Peter Newman 12 Feb 2006: Check out these two pages on MSDN Mike (especially the second one):- you an idea of how Windows apps. handle the MouseWheel. Presumably, Tk doesn't. But you could probably add that support by looking for WinMain in the Tk sources, and adding support for the WM_MOUSEWHEEL message (or modifying the existing support so that it does the required). But, how the application knows that it's the window to be scrolled, rather than the mouse to be moved, I've no idea. The answer will be in those MSDN docs. But, you're probably in for a lot of reading and thinking. Good luck...MG Hi Peter, thanks for the response. Tk does scroll when you roll the wheel, it's just the extra functionality provided by the mouse's software which doesn't work. I'll try and dig through the links you gave and their related pages later today and see if I can find anything that explains it/shows how it could be changed.Peter Newman Yeah, I just read about it in the bind manpage. If by extra functionality, you mean changing the cursor, that would be easy enough to implement (I think). Just bind to the <MouseWheel> event. And, whenever you get one, switch the cursor accordingly. And bind to mouse movement events too. These should restore the default cursor. I think that would work (though I haven't tried it).MG It's not actually something I'm trying to implement in Tcl/Tk, per se. In many other apps (Internet Explorer, for example), if I click (not scroll) the mousewheel, it changes the cursor, and I can then move the mouse in any direction and the window scrolls in that direction. Clicking the mousewheel again (or scrolling it/pressing another button) turns this feature off. It's not a part of Internet Explorer, though - it's a feature provided by my mouse driver, which works in more or less every application with a scrollable window. But not in Tk apps - when I press my mousewheel, it simply fires the Tk app's <Button-2> event. My best guess is that Tk isn't registering the fact that the window can be scrolled, in some way, and so the OS/mouse driver isn't intercepting the <Button-2> click and doing its own thing, but is simply sending the click through to Tk to handle (which is what seems to happen in apps where this feature does work, but the window in question can't be scrolled at the time).Peter Newman 13 February 2006: As I read it, Tk/wish does support the MouseWheel event the way you want it too. In that its WinMain listens for the WM_MOUSEWHEEL message, and then raises a <MouseWheel> event via the bind mechanism when it receives it. But it's up to the individual Tcl app. to handle that message/event. If it doesn't, then MouseWheel scrolling is ignored. It seems to me that a Windows supported MoseWheel must work in two modes; 'Mouse' mode, where it emulates a mouse, and 'MouseWheel' mode, where it acts as a MouseWheel. Clicking the mousewheel obviously switches it into 'MouseWheel' mode. In 'Mouse' mode, Windows moves the mouse pointer automatically for the app, and sends the standard mouse messages (excluding WM_MOUSEWHEEL) to the focused app. And in 'MouseWheel' mode, it sends WM_MOUSEWHEEL. Obviously, the app. concerned has to handle WM_MOUSEWHEEL, and do the necessary scrolling and cursor changing, etc, as required. So, you can make a Tk app. handle the mousewheel the same as any other Windows app. that supports the mousewheel. But, you'll have to manually add a <MouseWheel> event handler to every (scrollable) widget that you want this MouseWheel support for. Ie; You have to add:- bind .someScrollableWidget <MouseWheel> ScrollTheWidget_AndSwitchMouseWheelCursorOn_AndSetMouseWheelModeFlagTrue bind .someScrollableWidget <Button-1> IfMouseWheelModeFlagTrue_SetItFalse_AndRestoreNormalCursor bind .someScrollableWidget <Button-2> ditto(or something like that,) to every widget you want to support the MouseWheel. See description of the <MouseWheel> event, in the bind manpage. console2006-02-08 [CSW] I don't have the console command. I did get spawn -console to get control of the console, however I don't know where the information is going. It's not on the console or the terminal. How do I grab that info?2006-02-02 [CSW] I have written a terminal that runs on SunOS. I need to redirect control of the console to the terminal. I tried the -console from Expect but the OS doesn't support this command. Any suggestions?RJ 2006/02/05 SunOS (at least mine) has a console command - try spawning that - spawn console -s <server name> create wikit2006-02-03 LB -- Again I am convinced I have seen the answer somewhere but cannot find it now.I want to create a wikit wiki instance with a different name than "My Wiki" which seems to default no matter what I do. There must be either a command line flag or a way to edit the title once the .tkd is formed.TIA,- Yep - the text entry field at the top of the Home page will do that. wikit2006-02-02 LB I am replacing an internal wiki (inside the company firewall) with Wikit. The formatting page and Help page are enough for the basic operation, but the hint about URLs that end in .jpg and .png/.gif hasn't come clear in my experimentation. I want to display photos and graphics. Is there a more detailed instruction document or tutorial for Wikit?MG I believe that, if you type a link in directly (without enclosing in square brackets), the link is displayed normally. If you enclose in square brackets, the picture itself is shown. For instance (first is not in square brackets, second is; pictures stolen from the Graffiti page) string match2006-17-10 Hi! Does anybody know why the following code prints 0, but not 1 ? set s \[test\] puts [string match \[*\] $s]Thanks. Anton.MG As well as being special to the Tcl parser, the [ ] characters also have special meaning to string match. You can use a range of characters in brackets to match. For instance: string match \[a-z\] cmatches, because 'c' is in the range 'a-z'. To make your match work how you intend, you need to escape the brackets twice: once from the Tcl parser, and once from string match's little language: % set s \[test\] [test] % puts [string match \\\[*\\\] $s] 1 % puts [string match {\[*\]} $s] 1 encryption and decryption2006-01-25 Hello! I have a question about safe encryption and decryption. Assume we have the following: 1) encrypted data; 2) a TCL program that is able to decrypt this data using TCL libraries.Question: is it possible to make this data nondecryptable by any program except of that specific TCL program?Thanks. Anton.ECS: No. One could write another program in another language to decrypt the data.Security of data should the a function of the algorithm to encrypt it (known to attacker) and a secret key. color of a pixelHJG 2006-01-24: I have some problems to Get the color of the pixel under the pointer. OO / ParentClass01-09-06 I was wondering what would be the advantages/disadvantages of option 1 Vs option 2. Option 1 inherits the ParentClass and adds custom functionality to the sMethod. Option 2 has an option called "command" in the ParentClass that an allows simply to set the "command" option by the derived MyObject with the custom lines of code. Both yield the same effect. I would appreciate the input. ThanksSarnold : Please tell us what OO system you are using ; I cannot see whether it is [Incr Tcl] or XOTcl. Thanks.I am using Incr Tcl......OPTION 1: class ParentClass { public { method sMethod {} } } body ParentClass::sMethod {} { some lines...... some lines...... some lines...... } class MyClass { inherit ParentClass public { method sMethod {} } } body MyClass::sMethod {} { ParentClass::sMethod some custom lines....... some custom lines....... some custom lines....... }OPTION 2: class ParentClass { public { variable command method sMethod {} } } body ParentClass::sMethod {} { some lines...... some lines...... some lines...... uplevel #0 command } ParentClass MyObject Myobject configure -command {some custom lines.......; some custom lines.......; some custom lines.......}Sarnold Well, when working with buttons you really need a callback (the -command parameter). But best practices are, often expressed, to keep a callback simple so that it fits in one or two lines.At that point, it seems to me that using inheritance - with all its drawbacks - is better in this case. mail / sybase.log12-29-05 I want to mail a message to me if the size of sybase.log = 0. This script does not finish and I have to logout from the server and then log in again. I would appreciate any help. This is the script: if {[string match [file size /home/oracle/dba/logs/sybase.log] "0"]} { exec mailx -s "Sybase log is 0 bytes" [email protected]} } else { puts <oramessage>NO</oramessage> puts <oraresult>2</oraresult> }escargo - What happens when you do your mailx command from a comand line? (What's your platform, what's your Tcl version, etc.?)The script do nothing and do not exit. The Platform is Sun Sparc Solaris version 5.8 and the TCL that I'am using is Oacle TCL.ECS: mailx reads from standard input. Try to redirect stdin to /dev/null.escargo - I think that probably the right answer. The mailx command is trying to get command line input for the body of the message, which it isn't getting. (I didn't ask what the script did; I asked what mailx did if you ran it outside the script.)[LCO] I tried also redirecting to dev null but also it takes forever. The script does not finish. Maybe is the syntax that I'am using: oratclsh[1]- if {[string match [file size /home/oracle/dba/logs/sybase.log] "0"]} { exec mailx -s >/dev/null 2>&1 "Sybase log is 0 bytes" [email protected]} } else { puts <oramessage>NO</oramessage> puts <oraresult>2</oraresult> }escargo 11 Jan 2006 - Note that the advice was to redirect stdin to /dev/null. You redirected stdout to /dev/null. Also note that as long as you are in Tcl to start with, why not use what's in tcllib? See smtp for examples and other possible solutions.[LCO] Thank you very much escargo, the script below, using the stdin to /dev/null was the answer. As you can see it is obvious I know the basics of Unix only. Thank you again for your help. The smpt suggestion told me that the package of smtp was missing. if {[string match [file size /home/oracle/dba/logs/sybase_tables.log] "0"]} { exec mailx -s </dev/null 2>&1 "Sybase log is 0 bytes" [email protected] } else { puts <oramessage>NO</oramessage> puts <oraresult>2</oraresult>}escargo - You could do this instead: if {[file size /home/oracle/dba/logs/sybase_tables.log] == 0} { ... } else { ... }That will do a more direct comparison.You could even take advantage of the fact that 0 is false, and do this: if {[file size /home/oracle/dba/logs/sybase_tables.log]} { puts <oramessage>NO</oramessage> puts <oraresult>2</oraresult> } else { exec mailx -s </dev/null 2>&1 "Sybase log is 0 bytes" [email protected] } Unix "script" commandHP 28 Nov 2005 Is there a script which immitates the Unix "script" command in Tcl. I need to record an interactive Tcl session on Windows, and need exactly what the "script" command does on Unix.LES Tkcon. File > Save...HP This works, but I need this functionality in a real shell as well, such as when using tclsh. (This is what we're actually using in the meantime)RJ OR - Expect for Windows. package require Expect spawn -noecho <command to get to DOS shell> ;#start a session with shell log_file filename interact ;#give session to user #..<interaction with shell - everything scripted to "filename"> log_file #..<terminates scripted session to "filename" and saves the fileRemember to thank Don Libes in your prayers.HP RJ - "interact" is not available on the windows version of expect. Supposedly it is difficult to implement in Windows.RJ Clearly, I am Windows-challenged. I stand corrected. TCL on Solaris[Ron] 8 NOV 2005 I just installed TCL on Solaris system. When I type tclsh the message "ld.so.1: tclsh: fatal: libgcc_s.so.1: open failed: No such file or directory c/r Killed"It looks like it compiled, but something else is wrong. Any ideas?RJ Try checking setenv for LD_LIBRARY_PATH - if it isn't there or doesn't contain the path to your tcl libraries this is what you'll see. build tkimgEscaladix:2005/11/04Does somebody know where is described the good procedure, for a beginner like me, to build correctly "tkimg" on windows with cygwin?When I use the following procedure:configuremake -mno-cygwin allin the top build directory andmake install (or make -mno-cygwin install)in the top build directory or in the sub directories of the build directory, errors are produced and any format specific directories and dll libraries aren't built.If you have any knowledge of the subject, please, help me.Thank you in advance. compile TCL code into bytecode2005/10/20Is it possible to compile a TCL code into bytecode (or binary exe)? The goal is to speed up a TCL application.aricb The short answer is no.The long answer is: the Tcl interpreter bytecode-compiles procs by default; there are some things you can do to make that compilation more efficient, notably putting braces around [expr] expressions (e.g. [expr {$a * $b}] rather than [expr $a * $b]). Code that is not inside procs is not bytecode compiled.It's possible to make an executable out of a Tcl program. People do this for convenience of deployment (starpack and freewrap) or to protect closed-source intellectual property (Tcl Dev Kit); the end result is bytecode-compiled, but it's no faster than the original Tcl script (which is also bytecode-compiled by the interpreter).KJN 2005/11/05: Would bytecode compilation into .tbc files at least speed up loading, which would no longer need a compilation step? Python seems to use this trick for its libraries. Daylight Saving Time2005/10/20jpt When Windows adjusts the DST "Daylight Saving Time" back to normal (Normal Eastern Standard Time or whatever), all after commands that are pending are delayed by one hour. In my script, all the loops that are scheduled to run after a few seconds won't run until an hour! Do someone know a way to circumvent that problem? Is this happening also under Unix/Linux or is it just another Windows bug? column in file2005/10/12I would appreciate some help with the following:I have a file (from a simulation) containing lots of data. The first column is the frame number. The seventh column contains data the data of interest (z coordinate). So i would like to bin the z coordinate for each frame so i would end up with a 3d data set. column 1 would be frame, column 2 would be z coordinate and column 3 would be occurrences of that z coordinate within the frame.Is this possible with tcl and if so, please can someone help me get started?Thank you in advance.Syma KhalidUniversity of OxfordPeter Newman 13 October 2005: Are you wanting to graph the data? Or are you wanting to enter the data into a program, and do further computation/analysis of it? Or both?[Syma] 13 Oct 2005: I would like to graph the data using Xfarbe- thank you!Peter Newman 13 October 2005: So, what is it that you want Tcl to do? I assume, from looking at the Xfarbe site, it would be to convert the data you have, to the Xfarbe format (and then possibly, to run Xfarbe). Tcl can do that quite easily. But I'm not sure if that's what you wanted.[Syma] 13 Oct 2005: I'd like to create the input file for Xfarbe with my data. So i have a file containing data for a number of frames, where the first column is the frame no and the seventh column is the z coordinate. I want to end up with a file with 3 columns, the first the frame number, the second being z coordinate and the third being the number of occurrences of that z coordinate in that frame. So the script will go through and bin the z coordinate values for the first frame, then start over for the second frame etc etc.So something like this:Frame no: Z coordinate Occurrence1 10-20 21 21-30 01 31-40 41 41-50 12 10-20 02 21-30 12 31-40 42 41-50 3I hope this is clearer!MG offers this (untested) suggestion: proc parseData {originalFile {outputFile "./data.txt"}} { set allFrames [list] set allZs [list] set highest 1 set fin [open $originalFile r] while {[gets $fin line] >= 0} { set data [split $line " "] set frame [lindex $data 0] set z [lindex $data 6] if { [catch {zRange $z 10 highest} z] } {continue; #some error occurred, so ignore this line} if { [lsearch -exact $allFrames $frame] < 0 } { lappend allFrames $frame } #if { [lsearch -exact $allZs $z] < 0 } { # lappend allZs $z # } if { ![info exists count($frame,$z)] } { set count($frame,$z) 1 } else { incr count($frame,$z) } };# while close $fin for {set i 1} {$i <= $highest} {incr i 10} { if { [lsearch -exact $allZs [set range [zRange $i 10]]] } { lappend allZs $range } } set fout [open $outputFile w+] foreach frame [lsort $allFrames] { foreach z [lsort $allZs] { set howMany [expr {[info exists count($frame,$z)]?$count($frame,$z):0}] puts $fout "$frame $z $howMany" };# foreach z };# foreach frame close $fout };# parseData proc zRange {num {steps 10} {var ""}} { set base [expr {floor($num / $steps)}] if { $base < 1 } { set base 0 ; set num 1 } set start [expr {int(($base * $steps)+1)}] if { $num < $start } { incr start -$steps } set end [expr { int($start + $steps - 1) }] if { $var != "" } { upvar 1 $var high if { $high < $num } { set high $num } } return "$start-$end"; };# zRangeWhich should take a file like this: 1 some other data not used 14.6 1 some other data not used 18.2 2 some other data not used 25.7And output one that looks like this: 1 10-20 2 1 21-30 0 2 10-20 0 2 21-30 1This works on the assumption that all columns are separated by a single space (and all single spaces separate columns). If that's incorrect, it'd need some altering.[Syma] 14 October 2005: Hi- thanks for this MG. This is working so far, but teh probelm is the data of interest is not already in groups. So i (inadvertently) misled you in teh info i gave. So the data of interest is in real number format ie 54.35627 rather than 50-60. So i would like to build in something that would allow the user to define teh bin widths and then assign data to it. Please can you help. Thank you for your patience.MG Modified the above so that it should put it into ranges for you. The only "problem" is that numbers such as 20.001 don't fit into either 11-20 or 21-30. (Currently it puts them into the lower range, so 20.001 up to 20.999 will go into 11-20, and so on.)[Syma] When attempting to run the above script i get the error message: invalid command name "zRange"- any help would be appreciated.MG Added in a missing bracket, which I very stupidly missed out. I've now lightly tested this (using the test data above) and it seems to work fine, outputing exactly what it says it will above. I didn't get the error about missing 'zRange' at all, Syma - the zRange command is also provided above (I added it in when I made the previous modification). Make sure you have all of the code above saved, and try running it again?[Syma] before testing again, i'd like to ask an embarrassingly simple question:to run this do i only have to change the originalFile and outputFile bits then run this from tclsh? again thanks for your patience.MG You'll need to run the code above (which defines two new commands). Then, you'll need to run this line of code, too (which runs the new commands): parseData "c:/orignal/file.txt" "c:/results/of/code.txt"It's that line where you'll need to edit the paths, to reflect where your original file is, and where you'd like the file with the results in to end up. (If you have any other questions about running it, please put which operating system you're using, as the best/exact way to run the code differs between Windows and Linux. Thanks.)[Syma] Ok so I'm running on linux (fedora core)This is exactly what i did:tclshsource ask.tclparseData "./data.dat" "./out.dat"where data.dat was just copied and pasted from the example above, ie 1 some other data not used 14.6 etcThe message i get is: can't use non-numeric string as operand of "/"Trying my original data file gave me:can't use empty string as operand of "/"Sorry again.MG I imagine that with your original data file, the problem is that there are "extra" spaces - if the colums are separated by anything but a single space, the code above won't work. If you want to email me it ([email protected]) I can tailor the code a little to work with the exact layout. As for it not working with the test data above - I altered the test data earlier today (it shoed 10-20 before) to reflect the fact that your real data has floating-point numbers, and not ranges (10-20). Did you use the updated one for your test? If so, it should have worked correctly (or at least did for me). Using the older one, with the ranges, produces the error you mentioned.MG Updated the code above to work as required, after talking w/Syma via email and getting it working as needed. The last "can't use non-numeric string as operand of /" error was because some lines didn't have 7 'columns', so the lindex returned an empty string - it now catches the error, and ignores any lines where that happens. If someone wants to move all of this to a more appropriate page, if there is one somewhere, please feel free to do so now. Tk_Canvas in a Tcl-Extension2005/10/10Does someone know how I do create and show a canvas-object (Tk_Canvas) in a Tcl-Extension or where I can get DETAILED information about this? (Unfortunately, manpage of tk-library-functions only said that some functions exists, but not really how to use...)aricb The easiest way to do this would be to call Tcl_Eval with a little script that creates and displays the canvas. close windowABU 2005-10-07There are a lot of advices in this wiki about how intercept/handle window manager closing my tcl ; all these advices are based on the wm protocol command. Something like: wm protocol . WM_DELETE_WINDOW { ...do something before closing .. exit }I always used this technique for saving the application status, so that when user restart the application, he can magically resume his working.Unfortunately, at least on Windows, there are cases this technique does not work: When user does a shut-down, or simply log-off the current session, all applications are closed (of course), but this is not done by the window-manager; this is done by the O.S. - In this latter case, the application does not receive the WM_DELETE_WINDOW, then the 'status' is not saved ! - How can a simple application (notepad) be informed that it is being to be killed ? - How could I implement a similar behaviour in Tcl (for Windows, and maybe for *unix and Mac) ? wm protocol . WM_DELETE_WINDOW chk_exit bind . <Destroy> {savePrefs . %W} proc chk_exit {} { set ans [tk_messageBox -message "Really quit?" -type yesno if { $ans != "no" } { exit; } } proc savePrefs {top this} { if { $top != [winfo toplevel $this] } { return; # stop us saving prefs every time a widget under $top is destroyed } # do stuff to save prefs }That still wouldn't get the user prompted, on shutdown, but it should still save the prefs, at least.ABU Thanks, but half solution is not enough. Does anybody know how a simple Windows application like notepad.exe can intercept the kill/shutdown messages (?) for saving the current document ?Do you think it could be enough to provide a library (dll) or does it require a tcl-core extension ?Peter Newman Like I said above, it's all handled by the Windows message handling system. You've no choice but to spend time at the link I gave above, understanding it. Consider this quote (from there):- Since Windows is a message-oriented operating system, a large portion of programming for the Windows environment involves message handling. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event.In other words, Windows messages are much the same as Tk events. When someone clicks "Quit" or "File Save" (or whatever,) in Notepad, Windows sends a message to Notepad, telling it about this. Notepad then invokes its "File Save" or whatever handling code. A Windows app. like 'wish' or 'tclsh' can intercept another Windows app. (like Notepad)'s messages. Which is what you want to do.Then, I think you'll find you can create the necessary code (to call the necessary Windows API functions,) with ffidl or Yet another DLL caller.Cheers (and good luck). window sizeEvgeny Sep 29 2005:is there a way to determine how much space in pixels a Tk widget wants to take "naturally"? (below i explain why i want it, but i'd like to know the answer regardles of possible workaraund)i want several widgets of different size be placed in a lined-up fashion - i.e. have extra space appear padded so that i could add a second lined up column on the right etc. i understand i can use grid, but what if i want to have several instances of such table (with different content) each enclosed into its own label frame (just want to design a nice looking entry form) Thanks!Peter Newman 30 September 2005: I can't see that it's a problem; just a case of using pack and/or grid appropriately. But I'm not 100% sure exactly what you're after. Perhaps if you start a new page, with some ASCII (or whatever,) pictures of what you're after. Then, we can make some suggestions...aricb If your goal is to create nice-looking forms, you might have a look at Adrian Davis' GRIDPLUS package.TR You cannot tell how much space a widget will take naturally until it is managed/displayed using pack, grid or place. After that, use winfo height and winfo width to see how much space in pixels they really took.aricb [winfo reqwidth] and [winfo reqheight] will tell you how much space a widget "wants" to take, before they are geometry-managed.Peter Newman winfo height and winfo width are kinda buggy. In that it typically takes 10 to 100 milliseconds (sometimes longer,) till they return the correct values.Evgeny 30 Sep 2005: Thanks guys! GRIDPLUS looks nice, and winfo reqwidth works in Tcl and solves the problem. winfo width only works after something is packed which serves a different purpose of course.P.S. I am actually doing that in Python/Tkinter and there winfo_width is of no use at all - always returns 1 however winfo_reqwidth works well. ogg stream player/icecast[Navin] Hi, I am new to TCL, I wanted to make a very light, small ogg stream player, which can play icecast2 stream. I need to develop something very simillar to escargo 26 Sep 2005I have added to my personal page (escargo), a problem I am currently having trying to develop something like source that does logging.It seems to handle single-line Tcl correctly, but falls down with commands spanning multiple lines.I've tried to keep the example input and the sample code small, but I didn't want to clutter up this page too much, so I request your attention there. chr(), ord()LES: Does Tcl have something like PHP's chr() [2] and ord() [3] functions? I can make my own if it doesn't. I just want to know if Tcl already has them.MG The scan and format commands do that: % set num [scan A %c] 65 % format %c $num ALES Yes, your method works, but some results don't match the ASCII table I have here. I will check that later.MG I have no idea whether this actually is the problem, but it's something that may be worth trying. Do encoding system asciibefore you run the scan/format.Lars H: No, encoding system shouldn't make a difference for format or scan (things would actually get rather hairy if they did). More likely causes are: - If the differences are for chars with codes >127, then it's not an ASCII table you've got, because ASCII is a 7 bit encoding. Rather, you probably have an "extended ASCII" table. Use encoding convertfrom to convert foreign chars to Tcl's native unicode before you scan them, or fconfigure the channel you're reading them from with the proper encoding. - If the differences are for chars with codes <= 127, then you may have encountered some of the chars where people tend to divert from strict ASCII. Most notable is the "backquote" `, which according to strict ASCII is really a grave accent (why that was considered a useful character is however beyond me). foreach i [exec seq -s " " 300] { rw a c:/windows/desktop/ascii2.txt "$i: [format %c $i] : [scan [format %c $i] %c]\n" }rw is a file reading/writing/appending proc.The only problem I still seem to have is that neither Tkcon nor pure Tcl in Cygwin can display any chars from 0127 to 0159. Although my text editor can display most of them. It fails on 0129, 0141, 0142, 0143, 0144, 0157 and 0158. MS Word and Wordpad display a few more chars, like 0142 and 0158. I am on Windows 98 right now and will run more tests on Linux later.Neither Tkcon nor pure Tcl in Cygwin can display some characters, but the test above proves that they are still intact internally. MG Sep 21 2005 - I'm trying to compile a Tcl app on Windows which uses Iwidgets, with freewrap. I basically just wrapped the contents of the itcl3.3, itk3.3 and iwidgets4.0.2 folders from my /tcl/lib folder into the .exe, then copied them all into a folder (all files in the same folder - I combined the 3 pkgIndex.tcl files into one single pkgIndex.tcl) when the app runs. It loads Iwidgets fine, but when the app runs an iwidgets::panedwindow it throws this error: cannot inherit from "itk::Widget" (class "itk::Widget" not found in context "::iwidgets")Anyone have any idea what the problem might be? Any help would be greatly appreciated. Thanks! ping[Ashish] on 2005-09-19 @ 1204 PM ESTI am trying to ping a ip address in tcl, can some one please give me some pointers ?Thank you [Ashish]RJ See solution to the question below. Same way. Or see Expect extension doc. Just spawn a ping command and expect on the ping response. GUI-wrapper to a console applicationMRS on 2005-09-14I am trying to make a graphical wrapper to a console application. This application has many parameters that can be set in the command line, so the idea is to make a GUI for this and then invoke the command. I want to have the output (also text) of this command in a text widget. I know that set out [exec program]will store in out the output. The problem in this case is that the software being wrapped takes a long time to finish and from time to time it will output some progress.My question is, there is a way to update the text widget during the run of the console-based program to be wrapped? - [I think not. exec has only the eof callback. Would you be able to set prghandle [open "|program" r+] and use fileevent to update your text widget?] RJMRS Yes, it works. Thanks! ns08 Sept, 2005. Gurpreet SinghI am running a tcl file in ns2. I wish to call a tk window from that file, but seem to be getting too many errors. Basically, I cant run the tcl script using the standard "ns" command, because the tk commands such as canvas are not recognized. And i cant use "wish" to run the tcl script because some variables are being read in using the "source" command, and these cause errors to tk.Someone, help pls!Peter Newman 9 September 2005: I think we need some more info. 1) What is "ns2"? 2) What is "the standard "ns" command"? 3) I don't think we could answer the question without seeing the script. Is it available on the Net somewhere?RJ same day: This should be interesting. Answer to 1) ns2 appears to be a network simulator written in (at least partially) Tcl/Tk. See [4] for a start on that. Gurpreet, you're in the right place now - go ahead and supply info on 2) and 3) above. But please create a new page to move this to once your problem is resolved. It may become a valuable source of information. incr tclskm 2005/07/28I am interested in mapping incr tcl objects to a relational database. I am just beginning to learn about O/R mapping, and I've gathered some essays to read about it in general. There's a tcl conference paper from 2003 about this [5], and I was wondering if there is yet a standard O/R object mapping solution for incr tcl or for any of the other OO packages for tcl? If I end up writing my own, it won't be elegant enough to release into the wild right away (assuming I get permission to do so). Seems like it would be a nice thing to have. Iwidgets::scrolledtext[MK] I am using Iwidgets::scrolledtext for writing and editing text. Is there any "real" text editor in TCL with different colors for comments, keywords,.. such as a gvim or emacs .MG The ctext package in tklib provides a syntax-highlighting-enabled text-widget. It's a relatively simple matter, then, to add scrollbars and save/open file functionality to it. Any other features you might deem necessary for a '"real" text editor' can probably handled, too, depending on what you want.The Tcl Editors lists some programs, too, but I haven't studied the list in detail. It points out though that many are for editing Tcl in, and aren't actually written in Tcl. So I'm not sure how much use they might be... downloadAngel Sosa 2005.06.29 Is there a way to down load this website? From [email protected]escargo - See the bottom item on About this site. configure networkrdt 2005.06.27 Here is the problem. A tcl script is running on a system with network down. The script configures the network and brings it up. If the script attempts to open a socket to an outside machine using the IP address it succeeds. If it attempts to open a socket to that machine name, it fails. If it spawns a separate process to open the socket by name, it succeeds. So it appears as if the socket code in the running script, does not get correctly configured for dns when the network "comes up", whereas when it starts up on a configured network, it does. What command needs to be given to the socket code to "configure" it after bringing up the network?rdt 2005.09.29 No response for this. Guess no-one has an answer or just doesn't care.KJN 2005-11-05: I've reproduced your problem (on a Linux system). If I switch off networking, and then start a tcl process that restarts networking, I get the problem that you describe: exec /sbin/service network start package require http 2.5 http::geturl with the error message "couldn't open socket: host is unreachable". However, I only get the problem if both (a) I delete /etc/resolv.conf, which contains the IP addresses of the nameservers, when I stop networking - it is rewritten by DHCP when networking is restarted; and (b) I attempt a DNS lookup before switching networking back on. In fact, it is not necessary to stop and start networking - simply move /etc/resolv.conf before launching Tcl, and move it back after doing the first lookup. The Tcl process remembers that it doesn't know where to find nameservers, and doesn't try again. It is very likely that this is not a bug in Tcl but in the resolver library: man resolv.conf says "The config file is read the first time the DNS client is invoked by a process" - which is why a new process launched by exec has no trouble. If your network uses DHCP, you need to make sure that /etc/resolv.conf does not get deleted when networking is stopped. If you are using DHCP on Windows, try setting the DNS server IP addresses in the TCP/IP properties, instead of obtaining them from DHCP. If all else fails, call an external process (e.g. dig) to do your name resolution - or at least to check that name resolution is working before using it directly from your Tcl process.rdt 2005.11.05: Thanks, for your work. I believe that you are absolutely correct in your analysis. podcastLV 2005-June-27Anyone written any Podcast related software in Tcl? Right now, I'm looking at some crudely written bash code, but would have preferred to find some neat Tcl software that would work cross platform, from command line (for cron type executions) and perhaps with a tk gui for interactive use.I understand that it's not that hard to write; I'd just as soon not go through the life cycle of the effort if not necessary.[Henry Flower] 2009-08-24Googling for "tcl podcast" gives [6]. wish-reaper crashes tclkitSarnold 2005-06-26The following code taken from wish-reaper crashes tclkit (8.4.9 and 8.5a2) but not ActiveTcl : wm title . "Wish Reaper" set font {Helvetica 14} frame .reaper pack .reaper -expand 1 -fill both -side left tk_messageBox -icon info -message "Reaping complete." -type ok\ -parent .reaperThe operating system tested is Windows ME.escargo 27 Jun 2005 - I copied this code out and ran it on my Windows XP Pro system with ActiveState ActiveTcl 8.4.9.0 and with tclkit 8.4.9. Both crashed immediately. (The message box never came up.) The failure on Windows XP Pro is accompanied by a message box of a kind that asks if you want to send an error report. One of the controls on the box is "To see what data this error report contains, click here." If you click, you get a more detailed box (including an "Error signature") and another control that says, "To view technical information about the error report, click here." If you click, a window labeled "Error Report COntents" appears with "Exception Information", "System Information", a module list, a thread list, and a stack.This error appears to be highly repeatable; perhaps knowledgeable people could use the provided information to determine the underlying cause. I'll have to check to see where else this info should go.Peter Newman 28 June 2005: I've come across what looks like a similar thing, at 2 or 3 places in my own app. It happens (in my app.,) when I pop-up a message box whose parent is a toplevel that's just been destroyed. Doing this generates a Windows page fault error, and wish exits. I call it the "half-disappeared toplevel" problem. In your case, it looks like wish-reaper is just starting. So maybe it can happen when the toplevel's half-open too. Put a few seconds delay between the pack and the tk_messageBox, and see if that solves the problem.Generally speaking, if you ask Tk to do something on a nonexistent window, it will complain that the window doesn't exist. But quite obviously, there's definitely a bug in wish, in that it doesn't always catch the situation where the window is in a transitory state.In my case, I solve the problem by making the tk_messageBox's -parent the main window (.). But whether that will work in this case, I don't know. BLTjpt 2005-06-24What should I do to get BLT load in tclkit under Windows (tk_version=8.4; tcl_patchLevel=8.4.9) ?I always get: couldn't load library "BLT24.dll": this library or a dependent library could not be found in library path 1) I've downloaded BLT v2.4z for tcl8.4 and installed it in my "lib" dir ''(I used a directory tree like the one presented at [ that other binary extensions (like dll10.dll) load normally without error.Peter Newman 25 June 2005: I've also got ActiveState 8.4, and in this BLT24.dll is in Tcl/bin; not Tcl/lib. There's also a BLTlite24.dll in Tcl/bin - and a few other dll's which may or may not be part of BLT. Try putting BLT24.dll in Tcl/bin. And if that doesn't fix it, let me know and I'll list the other dlls for you (and email them to you if you want). Also, there are PE (Portable Executable) Viewer type programs downloadable from the Web that tell you what a given dll's dependencies are. So, inspecting BLT24.dll with one of those should tell you what's missing.However, whether those solutions will work with BLT in a TclKit, I don't know (isn't Tcl/bin in the kit?). I think you have to get a TclKit with BLT burnt into it. Two such kits are; bikit.exe and; dqkit-win32-i386-all.exe. You can Google for them.jpt Thanks Peter. Bikit solved my problem for now. However, i've tried a "dependency walker" software, and it seems that there is something wrong with blt84.dll. The software reports this error: "Error: At least one module has an unresolved import due to a missing export function in an implicitly dependent module."" I may investigate this later. ]'' 2) I opened tclkit and used "lappend auto_path" to add the "lib" dir where BLT is installed 3) then I type "package require BLT"]'' 2) I opened tclkit and used "lappend auto_path" to add the "lib" dir where BLT is installed 3) then I type "package require BLT" icursorJune 18, 2005 [J on Linux} I'm having difficulity getting icursor to work in the chosen field. I can use delete, insert, get for a specific field but icursor either won't work or after rebuilding the field the cursor will end up in the wrong field. Any suggestion will help. fmod[Muthu] June 15th 2005: I see weird result from fmod function in tcl.For below example, i expect the result to be 0.0 but it returns 6.44. % expr fmod(19.32,6.44) 6.44 However, in below example expression, i get 0.0. % expr {fmod(25.76,6.44)} 0.0 Any help in deciphering this conundrum is appreciated.Peter Newman 16 June 2005: I get the same results as you. And can't explain it. Looks like fmod is buggy and unreliable to me.ABU 16 Jun 2005 : I'm not an expert of the "fmod" semantic, so my reasoning is by analogy with the "modulus" operator semantic. Following this analogy, your strange results are not errors, but simply an approximation due to floating-point number imprecision.The fmod(x,6.44) function should always return a value within the interval \[0 ..6.44) . Be careful that in a modulus-6.44 arithmetic (!) the distance between 0.0 and 6.44 is ZERO, i.e. 0.0 and 6.44 are equal !Maybe the result was "6.44-epsilon" and this was printed as "6.44".For the modulus-6.44 arithmetic the difference between "6.44-epsilon" and "0.0" is just "epsilon" ! Therefore your result was not an error, but simply a floating-point negligible approximation.Lars H: Quite right. Subjecting the result of fmod to some more arithmetic verifies this suspicion: % expr fmod(19.32,6.44) 6.44 % expr fmod(19.32,6.44)<6.44 1 % expr 6.44-fmod(19.32,6.44) 8.881784197e-16See also a Real problem.If you want serious results, you should forget floating-point numbers and use integer arithmetic.If your operands are simply decimal numbers (with limited decimals), you could multiply both operands for 10^N ( so that they become integer numbers) and then use the integer-modulus operator fmod(x,6.44) is equivalent to (int(x*100) % 644) / 100.0 [Muthu] June 17th 2005 - Thanks a lot for all who clarified floating point calculation. MG June 14th 2005 - Does anyone know of a way on MS Windows to find out exactly what version you're using? I know you can use $tcl_platform(osVersion) to get some info, but that's the same (5.1) across all versions of XP, Home and Professional, SP 1 and 2, etc. Searching through the registry, I managed to find a couple of keys in My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersionProductName and CSDVersion, which are (on my XP Home SP2 machine) Microsoft Windows XP and Service Pack 2, respectively - couldn't find anything to differentiate between Home and Pro versions, though. I don't know if those can be relied upon, either (to exist on all NT machines, or to be correct). Anyone know the best way to get a "clean" textual representation of the Windows OS that works for all versions? I usually just check for $tcl_platform(platform) == "windows" and then work off $tcl_platform(osVersion), but it can come up a little short at times. Thanks in advance for your help.AET download psInfo.exe free from Sysinternals [7].Sample output: . . . [ SNIP ] . . . Kernel version: Microsoft Windows XP, Multiprocessor Free Product type: Professional Product version: 5.1 Service pack: 2 Kernel build number: 2600 . . . [ SNIP ] . . . Processors: 2 Processor speed: 2.7 GHz Processor type: x86 Family 15 Model 3 Stepping 4, GenuineIntel Physical memory: 1016 MB HotFixes: KB834707: Windows XP Hotfix - KB834707 KB867282: Windows XP Hotfix - KB867282 . . . [ SNIP ] . . .Peter Newman 16 June 2005: The official Microsoft solution is on the "Operating System Version" and "Getting the System Version" pages on MSDN; [8] and [9] respectively. They're in C, so you'll need Yet another DLL caller or something.I think AutoIt can do it too, perhaps writing the info. to a text file (of your own design,) that you can parse; like "psInfo.exe", above.APN On NT 4.0 and up, you can also use TWAPI. See get_os_version [10], get_os_info[11], and get_os_description [12].MG will look into all of those later tonight. Thanks for your help, guys! bug in the Text widgetMG June 8th 2005 - A friend of mine thinks he's found a bug in the Text widget. There are a couple of large screenshots with it, so I've put it up at Text Widget Bug. Any help/ideas would be greatly appreciated. Thanks :) sockspyLars H, 7 June 2005: I'm experimenting with the proxy functionality in sockspy, using this wiki at experiment subject, but it seems to be a bit ... shaky. I have managed to view normal pages, but get errors for e.g. references pages. Here's an excerpt showing what I mean:Sockspy: 16:58:06 connect from 127.0.0.1 localhost 8091 54200 16:58:06 fowarding to wiki.tcl.tk:80Client: 16:58:06 GET: !: 16:58:08 HTTP/1.0 400 Bad request 16:58:08 Content-type: text/plain 16:58:08 16:58:08 This is not a valid URL for this site 16:58:08Sockspy: 16:58:08 ----- closed connection ----- 16:58:08 waiting for new connection...The strange thing is that the exact same URL -- issued from the same browser after changing the proxy settings there, or copied from the GET line and entered into a browser that ignores proxy settings -- does work when not going through sockspy. So what is going wrong?Peter Newman 9 June 2005: I don't know if this is relevant or not - but for the last month or so - and just on the Wiki - my browser sometimes (maybe 1 out of every 10 times,) pops up its "Open or Save" dialog, when I click on a link??? I just click "Open" of course. I've never experienced this before, on any other web site, in many years of browsing. So there seems to be something strange going on with the Wiki.Lars H, 10 August 2005: For some reason, LES in between versions 141 and 142 of this page changed the above URLs from having server wiki.tcl.tk to mini.net. Why did you do that, LES? Or is has the wiki suddenly got magic link-rewriting built in?In any case, I have since used sockspy as a proxy when communicating with several other servers, and it has worked fine. (Very handy when you're away from campus and need to browse some subscriber-IP-only web sites.) Why there should be something in this wiki which it chokes on is still a mystery, however. LAME / pipedzach 2005-6-3I am looking for a way to use the LAME mp3 encoder in tcl. Running on a win98 laptop, I get errors using a pipe with the LAME executable. So, now, I'm trying to use the lame_enc.dll instead. The problem is described in LAME. Any help please? format-date / xsltskm 2005/06/02I am having trouble using format-date ( <xsl:value-ofThe xml being processed has this node: <note datetime="2005-06-02T17:32:17">is this thing on?</note>Here is the result % $datedoc xslt $formatdoc formathtml Unknown XPath function: "format-date"!skm 2005/06/03 -- it turns out that format-date is new in XSLT 2, and tDOM only supports XSLT 1 for now. [unperson] Some mods have been made to my homemade editor in order to run it with the new TCL Kit, the beta version (9,0?). Unfortunately I get all sorts of error messages when I run it with the new TCL Kit. What is wrong? Is it because I still run Windows 98? Anyone has a clue? join 2 pointsGurpreet -- 2005/05/31I'm using tk to allow a user to join two points using a line created by moving the mouse. After drawing the line, however, unless the user clicks the mouse somewhere in the canvas, the line is not fixed to the point it was made. It floats to another point marked on the canvas if th emouse happens to hover over it. I have used bind to allow me to create lines with a starting point inside specified points, but cant seem to bind them to lock in place at the specified end point. Help, pls!MG See A minimal doodler explained for some help on how to do it. But you can either bind to ButtonPress and ButtonRelease (to start and stop the line, respectively, with a Motion that configures the line to follow the mouse), or you can bind to ButtonPress so that it records the coordinates of the click, then changes the ButtonPress binding so that the next one just draws the line from the coordinates you recorded to the coordinates of the second click. Hopefully that makes some sense ;) many menubuttonsDK -- 2005/05/24I'm trying to create a large number of menubuttons using loops, and I'm having trouble using -command {} with the dynamic variables. Shortened example: for {set i 0} {$i < [llength $i_count]} {incr i} { # length of i_count = 3 # some code # problem code: for {set m 0} {$m < [llength $m_count]} {incr m} { # lenght of m_count = 4 set a [menubutton $sf1.b${i}${m} -text "choose one" -menu $sf1.b${i}${m}.menu] set foo [menu $sf1.b${i}${m}.menu] } grid $a } }The error I'm seeing is a 'no such variable' on ${m}, and I think it is because it's a dynamic variable that is called in a -command {}. Is there a way to use such an assignment? - RS: The -commands are executed in global scope, so the uplevel in the first is not necessary. Also, you have redundant braces around variable names - not needed if a non-varname character follows. But most of all, braces around the -command scripts prevent variable substitution at definition time. Try "DK: a great many thanks for your help -- the substituting " for { and } solved my problem (i left the uplevel in the above on accident; i was just playing with the code trying to figure it out) IWidgets::scrolledtext[MK] I am using IWidgets::scrolledtext. I want to bind "MouseWheel" sequence to this widget. All other bindings seem to work except this. I am trying the following code: set scrolltext [iwidgets::scrolledtext .a] bind [$scrolltext component text] <MouseWheel> {puts "called"}I have tried this binding to various children of scrolledtext. But none works. Please tell me the correct way to do so.KJN There is some discussion of problems with binding to MouseWheel at Text Widget Bug. bugs in tcllib smtpd's gmtoffset[FEB] on 2005-05-17: I'm new to Tcl. I believe I've found a couple of bugs in tcllib smtpd's gmtoffset function. A tclsh session follows. (I added the unindented debugging lines to the function.) gmtoffset should always return -0500 for CDT, my local time zone. The result of the first call is +0500 and the result of the second call is -1900. In other words, as far as I can tell, the function will return either +0500 or -1900 for CDT, neither of which is correct. C:\>tclsh % proc gmtoffset-test {} { puts [gmtoffset 1116355370] ;# A little after 2005-05-17T1340, 1:40 p.m., CDT, my local time zone puts [gmtoffset 1116389544] ;# A little after 2005-05-17T2300, 11:00 p.m., CDT, my local time zone } % % proc gmtoffset {time_} { set now [clock seconds] set now $time_ set lh [string trimleft [clock format $now -format "%H" -gmt false] 0] puts "lh = $lh" set zh [string trimleft [clock format $now -format "%H" -gmt true] 0] puts "zh = $zh" if {$lh == "" || $zh == ""} { set off 0 } else { set off [expr {$zh - $lh}] } if {$off > 0} { set off [format "+%02d00" $off] } else { set off [format "-%02d00" [expr {abs($off)}]] } return $off } % gmtoffset-test lh = 13 zh = 18 +0500 lh = 23 zh = 4 -1900 %Lars H, 19 May 2005: If you think you've found a bug in some tcllib module, then you should report it. The tcllib bug database is at [13]. date arithmetic[FEB]: I also have a question about Tcl. Are date arithmetic functions available for Tcl?Peter Newman 18 May 2005: Search for date on this Wiki and you'll get a whole load of stuff. Then there's the nstcl nstcl-time module. scrolledframe[MK] I am making a scrolledframe. Inside this I am adding items row by row. Each row will contains a label , then three checkbuttons. Every time I add a row , I make these widgets and pack them. Now suppose I need to add 2000 or more of such rows at one go. My display then hangs. I am not able to create so many widgets and pack them . Is there any way to do this efficiently ?? Can I find any package which allow me to add rows containg a label and checkbuttons efficiently ???Peter Newman Yes, I've experienced that with scrolledframe and similar widgets. But I think with text, canvas or tablelist, for example, you should be OK. But 2000 rows? Hmmm... My gut feeling is that canvas would be your best shot.Chris L - Would it be appropriate to fake the scrolling? By that I mean that you could have a small number of real rows (maybe even just 1) displaying a sub-set of the full set, and moving the scrollbar would change the starting offset. Obviously you've got slightly more work to do when responding to button presses, taking into account the current starting offset, and moving the scrollbar will have to apply the correct state/data to the visible widgets, but it might be a better solution than scrolling around a canvas whose area is measured in acres!Peter Newman 18 May 2005: Chris L, your idea sounds a bit like jcw's Virtual grid widget.Chris L - Along the same lines, yes, but Virtual grid widget (which I'm glad you've brought to my attention!) appears to be a lot smarter about scroll-induced upates. SQLite vs MetakitLES on May 03 2005: I am having a hard time trying to find information on comparison/benchmarking between SQLite and Metakit. Can anyone point me to a good source?BTW: Maybe it's about time to start an "Ask, and it shall be given # 3" page... LES on May 02 2005 $ set foo {Quoting "one" or "two words" is {tough}.} $ set foo Quoting "one" or "two words" is {tough}.Great. However... $ proc p> {args} {puts "<p>$args</p>"} $ p> Quoting "one" or "two words" is {tough} <p>Quoting one or {two words} is tough</p> $ p> Quoting "one" or "two words" is {tough}. extra characters after close-braceOuch! Using the proc, one is not quoted, tough is not braced and the quotes became braces in two words. And if the phrase ends in a period, it generates an error. Why does it only happen when attempted with a proc and how can I clean ALL that mess?RS: Arguments to a command are early parsed as a list. That will remove grouping markup, i.e. quotes and braces around grouped words. The quotesw around "one" disappear as they're redundant in Tcl syntax. "two words" are grouped, but at Tcl's discretion with braces, not quotes. And in this syntax, the period after the close-brace is considered an error. If you don't want the parsing to occur, add another layer of braces around strings you don't want to be parsed further: % p> {Quoting "one" or "two words" is {tough}.} <p>{Quoting "one" or "two words" is {tough}.}</p>LES But that does not produce the desired effect. Those braces should not be there. I suppose you left that as an exercise for me? OK, this proc seems to work: proc p> {args} {puts <p>[lindex $args 0]</p>}GWM I suggest using JOIN as it uses less arguments. proc p> {args} {puts <p>[join $args]</p>}What I want to do hwoever is construct a set of arguments for a button and use the list: pack [button .btn -text fred -command "puts {Dont do that}"]creates a button which works. destroy .btn lappend args -text fred -command "puts {Dont do that}" button .btn $argsreturns: unknown option "-text fred -command {puts {Dont do that}}". I have tried some 'clever' tricks such as: button .btn [eval concat $args] button .btn [join $args]but no joy.How do I use the args which I have built up other than to get RSI from: button .btn [lindex $args 0] [lindex $args 1] [lindex $args 2] [lindex $args 3]Thanks! Any suggestion of a wikit page where this topic should be moved to? Shall we try Argument to a Command? background processesStephen Tjemkes: 2005-04-29 Hi can somebody help me with background processes? I want to spawn off a limited number (say 30) of parallel background processes within the expect modules but do not understand how this can work. I've seen a brief description in the expect book using fork but this allowed me to fork off only one process. At least i didnot see that there were more than one. Is there somebody who can share his experience on thisThanks Stephen Iwidgets::combobox[MK] I have made a Iwidgets::combobox. In order to test it , I am creating it through a *.do file in my application.On creating it the mouse is grabbed to this combobox. I want to select different entry from the list of combobox. How can I perform this behaviour of mouse from a *.do file ?? console for UNIXDerek Peschel 2005-04-23 I'm new to Tcl and Tk and the console for UNIX script is still not clear to me. I have Mac OS X. I've tested the console under X a little with A minimal editor, but I want to use the console as a part of TkOutline [14] under Aqua. Note my terms "loader script" (what's on console for UNIX) and "library script". Also see my comments on the console page.If someone can answer these questions about the loader, I'll be ready to send in some changes from TkOutline: - Are the two blocks that call tk::unsupported::ExposePrivateCommand in the most logical place? Obviously they have to come after $consoleInterp is created. But a binding that uses tkConsoleExit comes before the code that makes tkConsoleExit available. - Should the "work around bug in first draft..." block logically go closer to the reading of the library file? regexp *[MK] 1. When I am using the command "regexp" and supppose my pattern is "*". This gives a Tcl error . I am not able to catch this error using the catch command. How can I do this ?2. Where can I find the new features added for tcl commands (for example in case of list commands many new options have been added) for new versions ??LV 1. Here's what I see: $ tclsh % catch { regexp {*} abc a b c} 1Seems like I can catch it. Can you show us specifically what you believe is a failure to catch? P.S. See regexp for an explanation of why your pattern is wrong. P.P.S. be certain to actually check the results of the catch, because ignoring the error is just begging for trouble.[MK] Its working .. Thanks.[GV] Don't you want:% regexp {.*} abc a b c. means any single character, * means 0+ occurrences (of . in this case)2. New features to Tcl commands are supposedly only added after proposal, discussion, and approval of an appropriate TIP. If you check out Changes in Tcl/Tk, there are attempts to summarize the changes there. There are also short notes in the ChangeLog files that are a part of the source distribution. Simple Launch Pad[HJH] May 18, 2005; I posted two questions on the page Simple Launch Pad. This are really beginners questions and I would be please if somebody could spend 5 minutes on it.Some hours later .... Thank you! The answer is fine. CPU utilizationi need to find system CPU utilization from tcl/tk. if system CPU utilization is low means,i should display a warning message. please help me to find this.DKF: On Linux: set f [open /proc/loadavg] set loadinfo [split [gets $f]] close $f parent/child[EK]: 2005-05-25 Hi, I have been getting the errorparent: sync byte read: bad file number child: sync byte write: bad file numberafter 1015 loops on the code below: set counter 1 while {1} { echo $counter spawn ftp -n close wait incr counter }I read on the Expect FAQ that it is due to calling 'spawn' in a loop and neglecting to call close and wait. I have done both of that in the above code, so what can the problem be? Thanks in advance for your help...[EK]: I found out what's the problem. I'm using Tclx and Expect together, thus the 'wait' command is actually a Tclx command instead of the Expect command. To use Expect commands, prepend them with 'exp_'. install tkZinc3.3.0 on winXPDoes anyone know how to install tkZinc3.3.0 on winXP?? I already have tcl/tk8.4.9 but am still basically lost on installing tkZinc on my desktop. I'm very new to tcl/tk though. Hope anyone can help me. Thank ye all.AB balbuena (25.5.2005)MG I've never used it, personally, but it looks like if you download the "Starkit for Windows/Linux" from the downloads page on the TkZinc website [15], then "source $fileYouDownloaded" in your code, that should work. BLT for MacI used to use BLT in the last century, and was happy to see it was available in the Batteries Included 8.4 distribution for Mac OS-X 10.3.9 However, there's some disconnect when I try to actually use it in the wish shell: (() 1 % package require BLT 3.0 () 2 % blt::graph .g -title "xxx" invalid command name "blt::graph" () 3 %I've tried to make sense of the problem using info commands, etc. but no luck.Apologies in advance if this is common knowledge, because I've never used a Wiki before...RBN (11.6.2005)TR (2005-09-19) - The BI distribution of Tcl for MacOS X does not include the complete BLT. Although it may seen so, the pkgIndex.tcl file tells us, that only BLTlite is loaded (this version 3.0 was never officially released yet by the author of BLT) which has some commands of the complete BLT but not any from the graphing engine.But there is a way out. If you can content yourself with using X11 on the Mac, try the port by Fink [16]. It has BLT for MacOS X in the current version 2.4z which runs fine with the X11 version of wish provided by Fink (that's version 8.4.1 and 8.4.7). Be aware, that this BLT will not run with the BI wish ... iwidgets::scrolledhtml[aviad] I'm trying to use iwidgets::scrolledhtml in my aplication for viewing html documents, the problem is when i try following links my links are totaly internal in th document but yet I get exception when I click on the link. How to solve this?package require Iwidgets 4.0 option add *textBackground white iwidgets::scrolledhtml .sh -linkcommand ".sh import -link" pack .sh -fill both -expand yes puts [.sh configure] .sh import [lindex $argv 0] TCL / VB6There was an written TCL procedure. Now I want to run that existing TCL procedure from VB6 and display the result of that TCL procedure in VB6. How can i do this.Please Guide me.Thankyou.EKB It depends on the kind of output from the Tcl procedure. Is it plain text? If it is (and maybe even if it isn't), you can run the Tcl or Tcl/Tk program (tclsh or wish) as an external process. The VB6 API function to call is called CreateProcess.If you want to run, then wait for the output from tclsh (especially if it's plain text), also call WaitForSingleObject to make sure tclsh is done running. See the following URL for more info on the VB6 code: toplevelI'm trying to write a Tcl/Tk app that places my toplevel window on the display and then does not allow the user to resize or move the window. I've managed the fixed size part, but does anyone know how to "lock" a window in place?EKB The wm overrideredirect will prevent the user from moving the window (there's no frame for the window for them to grab, for example). (But are you sure you don't want the user to have that control?)Thank you, EKB. That should work. Perhaps a little more background on my situation is in order. I have a system that is polling a server via socket twice a second and showing results on one of four displays attached to the client PC. Each display is assigned a Tk form and should constantly show that form and only that form for ever (or as long as Windows will let it run). I will probably have to add another label to the top of each form to simulate the title bar, but that's fine with me. Your help is most appreciated.EKB - Makes sense. And you're welcome! exit statusI'm trying to access the exit status variable in the separate TCL script file. Here bgexec is not supported so i want to know how to get exit status variable using exec command.EKB Take a look at exec and error information. Euro symbolctasada I'm working in a project that needs to work with the Euro symbol (EUR). Tcl seems to handle that correctly in cp1252, but working in utf-8 I cannot type the euro symbol in any entry widget, not even in a wish console (bin) 5 % encoding system cp1252 (bin) 6 % EUR invalid command name "EUR" (bin) 7 % encoding system utf-8 (bin) 8 % ?Any help is welcome. Thank you very much in advance.WJP You should be able to enter it using a \u escape. Try \u20AC.BR 2005-10-01: Tcl/Tk only uses one representation (Unicode) internally. It converts to that encoding on input and from that encoding on output to whatever it thinks that the outside world wants.So "working in utf-8": You always "work" in Unicode inside Tcl."% encoding system cp1252": You have proven that everything works if Tcl treats the outside world (input and output) as CP1252."% encoding system utf-8": You tell Tcl that the world has changed to UTF-8. That's not true, so communication doesn't work anymore. LJF 20octoberI am only learning TCL, to understand some drivers on our M&C, who uses TCL to implement the comunication to the hardware, mostly modems and satelite equipments. My knowledge is basic, I am asking if anyone nows how to "create" a channel to an ethernet card to send a ping to another one in the network. I have read on a manual that a channel could be created to a file, a pipe or a device. Does this device could mean ports or eth cards? How to do that? tcl manuals are poor on sutch area tks luismy mail addres is [email protected]EKB I think you're looking for the socket command. From the man page:." sockets[DIRLIK Thibaut] Hello (this my first post in this fabulous wiki), i'm a french TCL Coder and i'd don't understand how I can use sockets in a Tclet (Using Tcl plugin) ! I'd like to make a IRC TCL Applet (in order to tchat from the web) ! Can you help me please ? TML / putsRuffy How come my TML's simple code:[Doc_Dynamic] puts "The time now is: [clock format [clock seconds]]"...shows up as: puts "The time now is: Tue Nov 29 12:09:31 PM Eastern Standard Time 2005"...Why is the tcl command "puts" ignored?Grateful.aa - TclHttpd's template support doesn't [source] the .tml files as scripts, so you can't expect them to work that way. The content of a .tml file is essentially run through [subst]. Even if you enclosed the [puts] in brackets to get it to be evaluated as a command, you'd end up with its output appearing on the TclHttpd console instead of the page. If you need full scripting with stdout going to the page, you should use TclHttpd's [Direct_Url] support instead of templates. SSH[SJK] 11 December 2005I've just started using ActiveTcl 8.4.11.2. I have written an Expect script to automate an SSH session and this works successfully on XP Pro when run with tclsh. However, when I run it on Windows Server 2003 then the first expect command after the exp_spawn exits with eof. The command used in the exp_spawn works fine when entered at the command line. Can anyone help?Thanks.SJK 12 December 2005Oops, sorry to have bothered you - solution is just to disable Data Execution Prevention for tclsh.exe via Control Panel->System->(Advanced Tab)Performance Settings. vwaitKen: I am wondering whether how to transfer control back to a procedure using 'vwait' concept? Let say, I have a proc A below. It transfer control to another procedure B which is running a while loop executing all sorts of commands. But inside proc B , there are commands that require transfer back to the proc A. And after executing proc A, it continues where it lefts off in proc B? Is there a way using vwait command to implement this or is there other ways? Really need help! Thanks in advanceproc A {} { while {1} { #commands to execute call proc B #continue }}proc B {} { while {1} { #process certain things #sleep #vwait (need to transfer control to b) #when call proc b from proc a resumes here #continuye to process things }}EKB Ken, what problem are you trying to solve? This looks like a complicated solution, and I'm wondering if the logic can be simplified.Ken EKB, what do u mean by "logic can be simplified"? The problem i'm trying to solve is transfering of control from one procedure to the next. Like i have a main proc that calls proc a which inside has a vwait command to suspend operation until been activated and continue from where it left off and transfer control back to the main program which continue processing till it calls proc a again and runs where it was suspend previously.EKB Ken, I actually meant, what's the larger problem you're trying to solve? (What does the program do?) At any rate, from my understanding of the code, it doesn't seem to matter that there's a vwait. Here is my understanding: A calls B B returns (after a vwait, but that's incidental - right?) A calls B again, but control starts where B last returnedIs that right?Ken EKB, oh i get what you meant? The above code is what i wanted to express earlier. That's is the problem i trying to resolve. But the larger problem i was trying to solve was that i am suppose to create a Wireless sensor nodes simulator. I use the discrete events simulator concept to program my simulator. Thus for example my event queue contains node N1 which is suppose to be awake, and then execute a set of code but then goes to sleep so the simulator should just 'suspend' the node N1 and grap the next event which may be node N2 is to be processed and afte r it is processed grap node N1 which is suppose to be awake now, and then continue to process where it left off. I thought of using after and vwait to suspend the node N1 but i just don't know how to transfer the control back to the simulator to grap the next event. I did consider to use return but it may prove cumbersome as it would have to reexecute all the previous code which node 1 has already processed? Do you get what i meant? Thanks in advanceEKB Ken, I think the page Keep a GUI alive during a long calculation is about solving a similar problem. Looking at that page may help. (The basic idea is to schedule an event using after, and keep track of state using namespace variables.) But people more knowledgable than me might have other ideas...EKB, Can you kindly state a simple algorithm cause i can't seem to link that site with the case i stated?EKB Ken, what I have in mind is something like this (and if this isn't what you're looking for, then I apologize, but I'll need some further clarification - or maybe someone else has a better solution?): proc A {} { while {1} { #commands to execute events::B #more commands } } namespace eval events { variable state "start" proc B {} { variable state switch -exact -- $state { start { #process certain things set state "1" after ... ::A } 1 { #process certain things set state "2" after ... ::A } 2 { #process certain things set state "3" after ... ::A } # ... default { # This is an error } } #continue to process things return } }Ken: EKB I really appreciate your effort in helping a newbie like me really thanks, but just to wonder what is the "after...::A" does it just rerun proc A again. Cause my idea was like using vwait or tkwait and then transfer control back to proc B and back to proc A, can it be done since vwait just suspend that till it is updated.EKB Ken, I haven't forgotten about you. But I haven't had time to sit down and think this through yet.Ken EKB, for the past few days, I been rethinking of the problem I think i am nearly there with this approach listed below. I probably nearly there with this approach. I manage to get the 2 procs to wait on each other. But the problem i don't understand, i am encountering is that once proc ::SuspendAndUnSuspendTest::ProcBSimulateAlgoProc has set UnSuspendFlagA before it suspends and wait for the variable UnSuspendFlagB to be set it suspends in proc ::SuspendAndUnSuspendTest::ProcBSimulateAlgoProc even though it sets variable UnSuspendFlagA which should gets ::::SuspendAndUnSuspendTest::ProcASimulateMainProc to contine running. Is it cause there must a return statement to get ::SuspendAndUnSuspendTest::ProcBSimulateAlgoProc to return control to ::SuspendAndUnSuspendTest::ProcASimulateMainProc before it can continue. If not how i can get it to move control back to ::SuspendAndUnSuspendTest::ProcASimulateMainProc before it continue to process ::SuspendAndUnSuspendTest::ProcBSimulateAlgoProcLars H: Well, you can't. A tkwait or vwait doesn't suspend a proc and gives control back to some global event loop, but starts a new event loop. Quoting the vwait page: - - Multiple vwaits nest, they do not happen in parallel. The outermost vwait cannot complete until all others return. namespace export -clear ProcASimulateMainProc, ProcBSimulateAlgoProc,ToggleUnSuspendProcA,Debugger,UnSuspendProcB variable ProcASuspendVar 0 ProcBSuspendVar 0 UnSuspendFlagB 0 UnSuspendFlagA 0}proc ::SuspendAndUnSuspendTest::CheckB {} { variable ProcBSuspendVar variable UnSuspendFlagB if {$UnSuspendFlagB} { puts "UnSuspendFlag is $UnSuspendFlagB and Proc is Run" set ProcBSuspendVar 1 } puts "CheckB fail" #puts "UnSuspendFlag is $UnSuspendFlag in UnSuspendProcB" after 5000 [list ::SuspendAndUnSuspendTest::CheckB]}proc ::SuspendAndUnSuspendTest::ProcASimulateMainProc {} { variable ProcASuspendVar variable ProcBSuspendVar variable UnSuspendFlagA variable UnSuspendFlagBss puts "Execute Command 1" puts "Execute Command 2" puts "Execute Command 3"## ::SuspendAndUnSuspendTest::Debugger #here need to unset to continue to Run Proc B #here need to unset to continue to Run Proc B #check whether UnSuspendFlagA for Proc A has been toggled to unsuspend the below function after 10000 { set ProcASuspendVar [::SuspendAndUnSuspendTest::CheckA]; puts "MainProc $ProcASuspendVar"} after 1000 [list ::SuspendAndUnSuspendTest::ProcBSimulateAlgoProc] #after 10000 { set UnSuspendFlagB 1 } tkwait variable ProcASuspendVar #tkwait variable ProcASuspendVar puts "Execute Command 4" puts "Execute Command 5" puts "Execute Command 6" set UnSuspendFlag 0}proc ::SuspendAndUnSuspendTest::Debugger {} { variable ProcBSuspendVar variable UnSuspendFlag variable ProcASuspendVar puts "ProcBSuspendVar is $ProcBSuspendVar" puts "ProcASuspendVar is $ProcASuspendVar" puts "UnSuspendFlag is $UnSuspendFlag" after 5000 [list ::SuspendAndUnSuspendTest::Debugger]}proc ::SuspendAndUnSuspendTest::CheckA {} { variable UnSuspendFlagA variable ProcASuspendVar if {$UnSuspendFlagA } { set ProcASuspendVar 1 puts "Value of ProcASuspendVar in UnSuspendProcA is $UnSuspendFlagA" } after 1000 [list ::SuspendAndUnSuspendTest::CheckA] return $ProcASuspendVar return $ProcASuspendVar}proc ::SuspendAndUnSuspendTest::ProcBSimulateAlgoProc {} { variable UnSuspendFlagA puts "Execute Command - ProcB 1" puts "Execute Command - ProcB 2" puts "Execute Command - ProcB 3" puts "Suspend" set UnSuspendFlagA 1 after 1000 { set ProcBSuspendVar [::SuspendAndUnSuspendTest::CheckB] } tkwait variable ProcBSuspendVar puts "Execute Command - ProcB 4" puts "Execute Command - ProcB 5" puts "Execute Command - ProcB 6" puts "Execute Command - ProcB 6"} ::SuspendAndUnSuspendTest::ProcASimulateMainProc} string is digithuck. According to the man page, string is digit string will return 1 if string is composed of "Any Unicode digit character." Then it goes on to say that "this includes characters outside of the [0-9] range." What other characters, aside from [0-9], are members of the digit character class? Thanks!(Answer moved to string is) extracting elements from listken: I am wondering is there any efficient and fast way of extracting [a fixed number of elements] from a list variable instead of using the normal of using lsearch and then lrange and lreplace?ken: Is there any way to edit the flow of events that are about to execute in the after info results. For example, i would like to edit the event lists in the results obtained from after info like delay the execution fo the events or resume the continuation of some events?MG March 25 2006 - I believe the only way is to cancel the event with [after cancel], and then either run it immediately or use another after call to have it execute later at a different time.ken: I have a problem with after cancel cause i have an event that reschedules itself periodically but even i use an after cancel, and when i check the event loop again it stills there. Is there a way to cancel all this event? array to listken: Just a question, is there any efficient way to transfer information from a array set variables to a list besides using a foreach loop and [array names (array variable name)]?Sarnold: It seems like you need array get, like this: % set myarray(0) a % set myarray(1) b % puts [array get myarray] 0 a 1 b Tk canvas 'closest'Ken: How do i use the options for 'closest' in the Tk canvas widget?Ken: Just a question again? how come when i set an array set variable using this notation below . I can't seem to be able to add a varible in place of a value, it always prompt me an error? set FullStrength 100 array set myarray { Power $FullStrength D1 $FullStrength }NEM: Because braces prevent substitution, as explained in the main Tcl manual page [17]. You want to use either double quotes: array set myarray "Power $FullStrength D1 $FullStrength"or else construct a list: array set myarray [list Power $FullStrength D1 $FullStrength] Query objects on canvasKen: I have another query. I have an object in a canvas. And everytime i need to click on the object to access its information. Is there a way of letting the canvas know that i am going to click on the object, so that it shows the information whenever i am near it ? Earlier i read up on the tag 'closest' can it be used?MiHa Maybe have a look at Enter and Leave Event Bindings
http://wiki.tcl.tk/12730
CC-MAIN-2017-26
refinedweb
15,135
72.66
“Do you pine for the nice days of Minix-1.1, when men were men and wrote their own device drivers ?” – Linus Torvalds What is a Kernel Module ? Modules are pieces of code that can be loaded and unloaded into the Kernel upon demand. Now, we get to the real action, where a single wild pointer can wipe out your file system. One type of module is the device driver, which allows the Kernel to access to access hardware connected to the system. Basic Terminologies - Char Device : Is the one with which the driver communicates by sending and receiving single characters. We will be mostly covering Char devices. Example – Serial, Parallel Ports, Sound Cards. - Block Device : Is the one with which the driver communicates by sending entire blocks of data. - Header Files : In order to have definitions of common structures and declarations be consistent across source files, it is easiest if these be in some sort of a central file that are included via ‘ # include’. You must have noticed Header files with the extension ‘.h’ in Arduino libraries. You may point out that you even noticed a few ‘.cpp’ files. A header ‘.h’ file is where you declare your functions, classes, variables whereas a ‘.cpp’ file is where you define those previously declared elements. - Object File : A ‘.o’ file which is created by the compiler for every source file, before lining them together, into executable file. ‘.ko ‘ file is your object file linked with some kernel automatically generated structures that are needed by the kernel. - Makefiles : Assume you have a huge codebase that has hundreds of files with lots of dependencies. Following are the steps you will need to perform : Hundreds of Files | Compile each of them | Generate an Object File | Link all .o files to generate executable code | If you do a small change in a file | Then you need to recompile and link all of them again Makefiles ensure that only the files that have been modified since the last build and those which are dependent are changed. It contains a file containing a set of rules to compile specific programs. How do Modules get into the Kernel ? - Insmod : Insmod is a user space utility to load a module into Linux Kernel. It is a small program to intimate the Kernel that a module is attempted to be loaded and transfers the control to the Kerenl. - lsmod : To check whether the module is installed correctly. Type this command to see a list of modules installed on your system. - rmmod : To remove the module. There are various other terms associated like depmod, modprobe which will be covered as we proceed further. _init and _exit - Module_init : It indicates when the particular function is used. - Module_exit : Exits and all the address space ( text, symbol ) used can be reclaimed. Printk() It is a function that prints a message. It is very similar to the wel know printf apart from the fact that it onlt works inside the kernel. You won’t see the message in user space, but to do that we use the ‘dmesg’ which prints the message buffer of the kernel. Module License MODULE_LICENSE(” Dual BSD/GPL “); It allows loadable kernel modules to declare their licences to the world. The purpose is to let the kernel developer know when a non free module has been into a given kernel. Modeversioning A module compiled for one kernel won’t load if you boot a different kernel unless you enable CONFIG_MODEVERSIONS. Writing you first Hello World Hello World – Part 1 ( hello-1.c) # include <linux/module.h> /* Needed by all modules */ # include <linux/kernel.h> /* Needed for kernel info */ int init_module(void) { printk(KERN_INFO " Hello World\n "); return 0; /* A non zero return means init_module failed; can't be loaded */ } void cleanup_module(void) { printk(KERN_INFO " Goodbye World\n "); } Compiling Kernel Modules obj -m += hello.o ( Generating the makefile ) All : make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules You need to compile the module using the same kernel that you’re going to load and use the module with. Discussion Kernel modules must have at least two functions : a “start” (initialization) function called init_module () which is called when the module is insmoded into the kernel , and an “end” (cleanup) function cleanup_module() which is called just before it is rmmoded. You can use any start or end function name which we will see in the coming tutorials. What is KERN_INFO ? There are eight possible loglevel strings, defiend in the header file : - KERN_EMRG : Used for emergency messages, usually those that precede a crash. - KERN_ALERT : A situation requiring immediate action. - KERN_CRIT : Critical conditions, for serious hardware or software problems. - KERN_ERR : Used to report error conditions. - KERN_WARNING : Warnings about problematic situations that do not create serious problems witht the system. - KERN_NOTICE : Situations that are normal but worthy to note. - KERN_INFO : Informational messages. - KERN_DEBUG : Used for debugging messages. I hope you found this tutorial useful. If you have any doubt, feel free to ask.
https://saumitra.co/embedded-4/
CC-MAIN-2019-30
refinedweb
829
65.32
Andreas Oman wrote: > For a system that does not have llrint() libavutil provides one. > However, the necessary header file is not included from the c-files > where llrint() is used. I believe this statement is incorrect. > This patch fixes that. > > I'm not sure it's the best way, but it should be fixed somehow. e.g. --- libavcodec/mpegaudiodec.c (revision 16251) +++ libavcodec/mpegaudiodec.c (working copy) @@ -27,6 +27,7 @@ #include "avcodec.h" #include "bitstream.h" #include "dsputil.h" +#include "libavutil/common.h" mpegaudiodec.c includes avcodec.h avcodec.h includes libavutil/avutil.h avutil.h includes common.h (in libavutil) common.h includes internal.h internal.h conditionally defines llrint #ifndef HAVE_LLRINT static av_always_inline av_const long long llrint(double x) { return rint(x); } #endif /* HAVE_LLRINT */ Same thing for opt.c -- Regards.
http://ffmpeg.org/pipermail/ffmpeg-devel/2008-December/044682.html
CC-MAIN-2016-30
refinedweb
133
56.32
While many government agencies have made strides toward going paperless, most still depend on one of the great paper producers of all times the as long as the fax is still king of the office, it seems the paperless goal will remain a chimera. But now several products have been introduced that suggest that the government's dependency on the fax machine can be reduced, if not eliminated. HP's Digital Sender, for example, offers an alternative to the fax machine by converting paper documents into digital form and then sending them via e-mail. Adobe Systems Inc. has a similar software product, Acrobat Messenger, which requires a dedicated Microsoft Corp. Windows NT machine and scanner. But while Acrobat Messenger offers other capabilities, such as optical character recognition, it comes at a price significantly higher than the HP Digital Sender's. The Digital Sender looks like a cross between a traditional fax machine and a copier. A top-loading document feeder takes up to 25 single- or double-sided pages. For double-sided documents, you must feed the pages through twice, once for each side. The system then collates the digital pages before sending them. The document feeder accommodates paper up to legal size, but pages that are placed directly on the glass for scanning must be less than 11.7 inches in length. Setting Up Configuring the network options presents about the only challenge to setting up the system. An RJ-45 jack on the rear of the machine supports a standard 10Base-T connection to any TCP/IP network. The first thing you must do after connecting the system to the network is configure the IP address as either static or dynamic. The Digital Sender supports both BOOTP and Dynamic Host Configuration Protocol for dynamic IP addressing. Next, Digital Sender will need your mail server address and a default e-mail account to use when sending documents. I tested the Digital Sender on a small network with a Cobalt Qube Linux-based appliance box as our e-mail server. I used Microsoft's Outlook Express as my e-mail client to retrieve messages sent from the Digital Sender. The Digital Sender uses e-mail messages that are compliant with Multipurpose Internet Mail Extensions to transmit its information. Users choose either Adobe's Portable Document Format or TIFF for the attachments. The size of the attachment will depend on the resolution the user selects and whether it is in color or black and white. The worst-case scenario for a fairly complex single-page, black-and-white document was around 400K. Color documents are typically larger, although in several instances a color document was actually smaller than the same page in black and white. The default operating mode for the Digital Sender is guest mode anyone can walk up to the machine and send a document, much like a typical fax machine. Two additional modes self-registering user and registered user provide an added level of security. In self-registering mode, new users must register the first time they use the machine and then log in each subsequent time. In the registered user mode, only users selected by an administrator can have access to the machine. Sending Documents Sending a document consists of entering a destination address and then scanning the document. The Digital Sender supports Lightweight Directory Access Protocol address look-up if your network provides that service. You can also create individual e-mail address books with single and multiple entries. While the keyboard on the Digital Sender is not one you'd use to type a lengthy e-mail message, it's adequate for the job at hand. One feature I did not like was the arrangement of the keys on the numeric keypad, with the "1" at the top instead of the bottom. The system also does not give much feedback on the status of a message. With a traditional fax machine, you get immediate feedback on the success or failure of a transmission. With e-mail, you're typically notified if your message was not deliverable. The Digital Sender is a send-only machine, so there's no immediate feedback to let you know whether your message made it. There is an option for registered users to receive an e-mail notification of delivery, but the server must support Extended Simple Mail Transfer Protocol for this feature to work. HP provides several utilities to help administer the Digital Sender. The Address Book Import Tool, available on the HP World Wide Web site, will import addresses from Microsoft Outlook or Exchange for individual users or for a global public address book. HP's Web JetAdmin program provides a browser-based administration utility for configuring and monitoring the health of HP network-enabled devices such as printers or the Digital Sender. There's also a utility for updating the Digital Sender's firmware over the network. The HP Digital Sender can be a real cost saver if your organization has a lot of outbound fax traffic. It will also help with the paperless office effort by quickly transforming paper documents into digital images that can then be routed to anyone with an e-mail address. Ferrill, based at Edwards Air Force Base, Calif., is a principal engineer with Avionics Test & Analysis Corp. He can be reached pferrill@fwb.gulf.net. HP Digital Sender 8100C Score: A+ Hewlett-Packard Co. (613) 728-8200 Price and Availability: Available for $1,299 on the open market. Remarks: The HP Digital Sender offers hope for government agencies drowning ina sea of paper and looking for an electronic way out. Using Adobe SystemsInc.'s Portable Document Format or TIFF files as attachments to e-mail providesa way to convert paper documents into digital form and then transmit themto one or many recipients. User address books and Lightweight DirectoryAccess Protocol support make the addressing chore much easier. Download page for the Address Book Import.
https://fcw.com/articles/2000/07/17/hps-weapon-in-the-paperless-wars.aspx
CC-MAIN-2019-43
refinedweb
992
54.02
Summary Combines multiple input datasets feature classes must be of the same geometry type. For example, several point feature classes can be merged, but a line feature class cannot be merged with a polygon feature class. Tables and feature classes can be combined in a single output dataset. The output type is determined by the first input. If the first input is a feature class, the output will be a feature class,; if the first input is a table, the output will be a table. If a table is merged into a feature class, the rows from the input table will have null geometry. To manage the fields in the output dataset and the contents of those fields, use the Field Map parameter. - To change the field order, select a field name and drag it to the new position. - The default data type of an output field is the same as the data type of the first input field (of that name) it encounters. You can manually change the data type at any time to any other valid data type. - The available merge rules are first, last, join, sum, mean, median, mode, minimum, maximum, standard deviation, and count. - When using the Join merge rule, you can specify a delimiter such as a space, comma, period, dash, and so on. To use a space, ensure that This tool will not split or alter the geometries combine multiple rasters into a new output raster. Parameters arcpy.management.Merge(inputs, output, {field_mappings}, {add_source}) Code sample The following Python window script demonstrates how to use the Merge function. import arcpy arcpy.env.workspace = "C:/data" arcpy.management.Merge(["majorrds.shp", "Habitat_Analysis.gdb/futrds"], "C:/output/Output.gdb/allroads", "", "ADD_SOURCE_INFO") Use the Merge function to move features from two street feature classes into a single dataset. # Name: Merge.py # Description: Use Merge to move features from two street # feature classes into a single dataset with field mapping # import system modules import arcpy # Set environment settings arcpy.env.workspace = "C:/data" # Street feature classes to be merged oldStreets = "majorrds.shp" newStreets = "Habitat_Analysis.gdb/futrds" addSourceInfo = "ADD_SOURCE_INFO" #.management.Merge([oldStreets, newStreets], uptodateStreets, fieldMappings, addSourceInfo) Environments Licensing information - Basic: Yes - Standard: Yes - Advanced: Yes
https://pro.arcgis.com/en/pro-app/latest/tool-reference/data-management/merge.htm
CC-MAIN-2022-27
refinedweb
366
55.74
Microsoft .NET Remoting: A Technical Overview Piet Obermeyer and Jonathan Hawkins Microsoft Corporation Summary: This article provides a technical overview of the Microsoft .NET remoting framework. It includes examples using a TCP channel or an HTTP channel. (15 printed pages) Note This article includes updated Beta 2 code. Contents Introduction Remote Objects Proxy Objects Channels Activation Object Lifetime with Leasing Conclusion Appendix A: Remoting Sample Using a TCP Channel Introduction Microsoft® they are transported by the channel.. Managing the lifetime of remote objects without support from the underlying framework is often cumbersome. .NET remoting provides a number of activation models to choose from. These models fall into two categories: - Client-activated objects - Server-activated objects Client-activated objects are under the control of a lease-based lifetime manager that ensures that the object is garbage collected when its lease expires. In the case of server-activated objects, developers have a choice of selecting either a "single call" or "singleton" model. The lifetime of singletons are also controlled by lease-based lifetime. Remote Objects One of the main objectives of any remoting framework is to provide the necessary infrastructure that hides the complexities of calling methods on remote objects and returning results. Any object outside the application domain of the caller should be considered remote, even if the objects are executing on the same machine. Inside the application domain, all objects are passed by reference while primitive data types are passed by value. Since local object references are only valid inside the application domain where they are created, they cannot be passed to or returned from remote method calls in that form. All local objects that have to cross the application domain boundary have to be passed by value and should be marked with the [serializable] custom attribute, or they have to implement the ISerializable interface... This indirection does have some impact on performance, but the JIT compiler and execution engine (EE) have been optimized to prevent unnecessary performance penalties when the proxy and remote object reside in the same application domain... In order to gain a better understanding of these proxy objects, we need to take a detour and briefly mention ObjRef. A detailed description of ObjRef is provided in the Activation section. The following scenario describes briefly how ObjRef and the two proxy classes are related. It is important to note that this is a very broad description of the process; some variations exist, depending on whether objects are client or server activated, and if they are singleton or single-call objects. - A remote object is registered in an application domain on a remote machine. The object is marshaled to produce an ObjRef. The ObjRef contains all the information required to locate and access the remote object from anywhere on the network. This information includes the strong name of the class, the class's hierarchy (its parents), the names of all the interfaces the class implements, the object URI, and details of all available channels that have been registered. The remoting framework uses the object URI to retrieve the ObjRef instance created for the remote object when it receives a request for that object. - A client activates a remote object by calling new or one of the Activator functions like CreateInstance. In the case of server-activated objects, the TransparentProxy for the remote object is produced in the client application domain and returned to the client, no remote calls are made at all. The remote object is only activated when the client calls a method on the remote object. This scenario will obviously not work for client-activated objects, since the client expects the framework to activate the object when asked to do so. When a client calls one of the activation methods, an activation proxy is created on the client and a remote call is initiated to a remote activator on the server using the URL and object URI as the endpoint. The remote activator activates the object, and an ObjRef is streamed to the client, where it is unmarshaled to produce a TransparentProxy that is returned to the client. - During unmarshaling, the ObjRef is parsed to extract the method information of the remote object and both the TransparentProxy and RealProxy objects are created. The content of the parsed ObjRef is added to the internal tables of the TransparentProxy before the latter is registered with the CLR. The TransparentProxy is an internal class that cannot be replaced or extended. On the other hand, the RealProxy and ObjRef classes are public and can be extended and customized when necessary. The RealProxy class is an ideal candidate for performing load balancing for example, since it handles all function calls on a remote object. When Invoke is called, a class derived from RealProxy can obtain load information about servers on the network and route the call to an appropriate server. Simply request a MessageSink for the required ObjectURI from the Channel and call SyncProcessMessage or AsyncProcessMessage to forward the call to the required remote object. When the call returns, the RealProxy automatically handles the return parameter. Here's a code snippet that shows how to use a derived RealProxy class. MyRealProxy proxy = new MyRealProxy(typeof(Foo)); Foo obj = (Foo)proxy.GetTransparentProxy(); int result = obj.CallSomeMethod(); The TransparentProxy obtained above can be forwarded to another application domain. When the second client attempts to call a method on the proxy, the remoting framework will attempt to create an instance of MyRealProxy, and if the assembly is available, all calls will be routed through this instance. If the assembly is not available, calls will be routed through the default remoting RealProxy. An ObjRef can easily be customized by providing replacements for default ObjRef properties TypeInfo, EnvoyInfo, and ChannelInfo. The following code shows how this can be done. public class ObjRef { public virtual IRemotingTypeInfo TypeInfo { get { return typeInfo;} set { typeInfo = value;} } public virtual IEnvoyInfo EnvoyInfo { get { return envoyInfo;} set { envoyInfo = value;} } public virtual IChannelInfo ChannelInfo { get { return channelInfo;} set { channelInfo = value;} } } Channels different communication protocols. Channel selection is subject to the following rules: - At least one channel must be registered with the remoting framework before a remote object can be called. Channels must be registered before objects are registered. - Channels are registered per application domain. There can be multiple application domains in a single process. When a process dies, all channels that it registers are automatically destroyed. - It is illegal to register the same channel that listens on the same port more than once. Even though channels are registered per application domain, different application domains on the same machine cannot register the same channel listening on the same port. You can register the same channel listening on two different ports. - Clients can communicate with a remote object using any registered channel. The remoting framework ensures that the remote object is connected to the right channel when a client attempts to connect to it. The client is responsible for calling RegisterChannel on the ChannelService class before attempting to communicate with a remote object. All channels derive from IChannel and implement either IChannelReceiver or IchannelSender, depending on the purpose of the channel. Most channels implement both the receiver and sender interfaces to enable them to communicate in either direction. When a client calls a method on a proxy, the call is intercepted by the remoting framework and changed into a message that is forwarded to the RealProxy class (or rather, an instance of a class that implements RealProxy). The RealProxy forwards the message to the channel sink chain for processing. This first sink in the chain is normally a formatter sink that serializes the message into a stream of bytes. The message is then passed from one channel sink to the next until it reaches the transport sink at the end of the chain. The transport sink is responsible for establishing a connection with the transport sink on the server side and sending the byte stream to the server. The transport sink on the server then forwards the byte stream through the sink chain on the server side until it reaches the formatter sink, at which point the message is deserialized from its point of dispatch to the remote object itself. One confusing aspect of the remoting framework is the relationship between remote objects and channels. For example, how does a SingleCall remote object manage to listen for clients to connect to if the object is only activated when a call arrives? Part of the magic relies on the fact that remote objects share channels. A remote object does not own a channel. Server applications that host remote objects have to register the channels they require as well as the objects they wish to expose with the remoting framework. When a channel is registered, it automatically starts listening for client requests at the specified port. When a remote object is registered, an ObjRef is created for the object and stored in a table. When a request comes in on a channel, the remoting framework examines the message to determine the target object and checks the table of object references to locate the reference in the table. If the object reference is found, the framework target object is retrieved from the table or activated when necessary, and then the framework forwards the call to the object. In the case of synchronous calls, the connection from the client is maintained for the duration of the message call. Since each client connection is handled in its own thread, a single channel can service multiple clients simultaneously. Security is an important consideration when building business applications, and developers must be able to add security features like authorization or encryption to remote method calls in order to meet business requirements. To accommodate this need, channels can be customized to provide developers with control over the actual transport mechanism of messages both to and from the remote object. HTTP Channel The HTTP channel transports messages to and from remote objects using the SOAP protocol. All messages are passed through the SOAP formatter, where the message is changed into XML and serialized, and the required SOAP headers are added to the stream. It is also possible to configure the HTTP Channel to use the binary formatter. The resulting data stream is then transported to the target URI using the HTTP protocol. TCP Channel The TCP channel uses a binary formatter to serialize all messages to a binary stream and transport the stream to the target URI using the TCP protocol. It is also possible to configure the TCP channel to the SOAP formatter. Activation The remoting framework supports server and client activation of remote objects. Server activation is normally used when remote objects are not required to maintain any state between method calls. It is also used in cases where multiple clients call methods on the same object instance and the object maintains state between function calls. On the other hand, client-activated objects are instantiated from the client, and the client manages the lifetime of the remote object by using a lease-based system provided for that purpose. All remote objects have to be registered with the remoting framework before clients can access them. Object registration is normally done by a hosting application that starts up, registers one or more channels with ChannelServices, registers one or more remote objects with RemotingConfiguration, and then waits until it is terminated. It is important to note that the registered channels and objects are only available while the process that registered them is alive. When the process quits, all channels and objects registered by this process are automatically removed from the remoting services where they were registered. The following four pieces of information are required when registering a remote object with the framework: - The assembly name in which the class is contained. - The Type name of the remote object. - The object URI that clients will use to locate the object. - The object mode required for server activation. This can be SingleCall or Singleton. A remote object can be registered by calling RegisterWellKnownServiceType, passing the information above as parameters, or by storing the above information in a configuration file and then calling Configure, thus passing the name of the configuration file as a parameter. Either of these two functions can be used to register remote objects as they perform exactly the same function. The latter is more convenient to use since the contents of the configuration file can be altered without recompiling the host application. The following code snippet shows how to register the HelloService class as a SingleCall remote object. RemotingConfiguration.RegisterWellKnownServiceType( Type.GetType("RemotingSamples.HelloServer,object"), "SayHello", WellKnownObjectMode.SingleCall); Where RemotingSamples is the namespace, HelloServer is the name of the class and Object.dll is the name of the assembly. SayHello is the Object URI where our service will be exposed. The Object URI can be any text string for direct hosting, but requires a .rem or .soap extension if the service will be hosted in IIS. It is therefore advisable to these extensions for all remoting endpoints (URI's). When the object is registered, the framework creates an object reference for this remote object and then extracts the required metadata about the object from the assembly. This information, together with the URI and assembly name, is then stored in the object reference that is filed in a remoting framework table used for tracking registered remote objects. It is important to note that the remote object itself is not instantiated by the registration process. This only happens when a client attempts to call a method on the object or activates the object from the client side. Any client that knows the URI of this object can now obtain a proxy for this object by registering the channel it prefers with ChannelServices and activating the object by calling new, GetObject, or CreateInstance. The following code snippet shows an example of how this is done. "" ChannelServices.RegisterChannel(new TcpChannel()); HelloServer obj = (HelloServer)Activator.GetObject( typeof(RemotingSamples.HelloServer), "tcp://localhost:8085/SayHello"); Here "tcp://localhost:8085/SayHello" specifies that we wish to connect to the remote object at the SayHello endpoint using TCP on port 8085. The compiler obviously requires type information about the HelloServer class when this client code is compiled. This information can be provided in one of the following ways: - Provide a reference to the assembly where the HelloService class is stored. - Split the remote object into an implementation and interface class and use the interface as a reference when compiling the client. - Use the SOAPSUDS tool to extract the required metadata directly from the endpoint. This tool connects to the endpoint provided, extracts the metadata, and generates an assembly or source code that can then be used to compile the client. GetObject or new can be used for server activation. It is important to note that the remote object is not instantiated when either of these calls is made. As a matter of fact, no network calls are generated at all. The framework obtains enough information from the metadata to create the proxy without connecting to the remote object at all. A network connection is only established when the client calls a method on the proxy. When the call arrives at the server, the framework extracts the URI from the message, examines the remoting framework tables to locate the reference for the object that matches the URI, and then instantiates the object if necessary, forwarding the method call to the object. If the object is registered as SingleCall, it is destroyed after the method call is completed. A new instance of the object is created for each method called. The only difference between GetObject and new is that the former allows you to specify a URL as a parameter, where the latter obtains the URL from the configuration. CreateInstance or new can be used for client-activated objects. Both allow instantiating an object using constructors with parameters. An activation request is sent to the server when a client attempts to activate a client-activated object. The lifetime of client-activated objects is controlled by the leasing service provided by the remoting framework. Object leasing is described in the following section. Object Lifetime with Leasing Each application domain contains a lease manager that is responsible for administrating leases in its domain. All leases are examined periodically for expired lease times. If a lease has expired, one or more of the lease's sponsors are invoked where they are given the opportunity to renew the lease. If none of the sponsors decides to renew the lease, the lease manager removes the lease and the object is garbage collected. The lease manager maintains a lease list with leases sorted by remaining lease time. The leases with the shortest remaining time are stored at the top of the list. Leases implement the ILease interface and store a collection of properties that determine which policies and methods to renew. Leases can be renewed on call. Each time a method is called on the remote object, the lease time is set to the maximum of the current LeaseTime plus the RenewOnCallTime. When the LeaseTime elapses, the sponsor is asked to renew the lease. Since we have to deal with unreliable networks from time to time, the situation might arise where the lease sponsor is unavailable, and to ensure that we don't leave zombie objects on a server each lease has a SponsorshipTimeout. This value specifies the amount of time to wait for a sponsor to reply before the lease is terminated. If the SponsorshipTimeout is null, the CurrentLeaseTime will be used to determine when the lease should expire. If the CurrentLeaseTime has a value of zero, the lease will not expire. Configuration or APIs can be used to the override the default values for InitialLeaseTime, SponsorshipTimeout, and RenewOnCallTime. The lease manager maintains a list of the sponsors (they implement the ISponsor interface) stored in order of decreasing sponsorship time. When a sponsor is needed for renewing the lease's time, one or more sponsors from the top of the list is asked to renew the time. The top of the list represents the sponsor that previously requested the largest lease renewal time. If a sponsor doesn't respond in the SponsorshipTimeOut time span, it will be removed from the list. An object's lease can be obtained by calling GetLifetimeService, passing the object for which the lease is required as a parameter. This call is a static method of the RemotingServices class. If the object is local to the application domain, the parameter to this call is a local reference to the object, and the lease returned is a local reference to the lease. If the object is remote, the proxy is passed as a parameter, and a transparent proxy for the lease is returned to the caller. Objects can provide their own leases and thereby control their own lifetime. They do this by overriding the InitializeLifetimeService method on MarshalByRefObject as follows:; } } The lease properties can only be changed when a lease is in the initial state. The implementation of InitializeLifetimeService normally calls the corresponding method of the base class to retrieve the existing lease for the remote object. If the object has never been marshaled before, the lease returned will be in its initial state and the lease properties can be set. Once the object has been marshaled, the lease goes from the initial to the active state and any attempt to initialize the lease properties will be ignored (an exception is thrown). InitializeLifetimeService is called when the remote object is activated. A list of sponsors for the lease can be supplied with the activation call and additional sponsors can be added at any time while the lease is active. Lease times can be extended as follows: - A client can invoke the Renew method on the Lease class. - The lease can request a Renewal from a sponsor. - When a client invokes a method on the object, the lease is automatically renewed by the RenewOnCall value. Once a lease has expired, its internal state changes from Active to Expired, no further calls to the sponsors are made, and the object will be garbage collected. Since it is often difficult for remote objects to perform a callback on a sponsor if the sponsor is deployed on the Web or behind a firewall, the sponsor does not have to be at the same location as the client. It can be on any part of the network that is reachable by the remote object. Using leases to manage the lifetime of remote objects is an alternative approach to reference counting, which tends to be complex and inefficient over unreliable network connections. Although one could argue that the lifetime of a remote object is extended longer than required, the reduction in network traffic devoted to reference counting and pinging clients makes leasing a very attractive solution. Conclusion Providing a perfect remoting framework that meets the needs of the majority of business applications is certainly a difficult, if not impossible, endeavor. By providing a framework that can be extended and customized as required, Microsoft has taken a key step in the right direction. Appendix A: Remoting Sample Using a TCP Channel This appendix shows how to write a simple "Hello World" remote application. The client passes a String to the remote object that appends the words "Hi There" to the string and returns the result back to the client. In order to modify this sample to use HTTP rather than TCP, simply replace TCP with HTTP in the source files. Save this code as server.cs: <enter> to exit..."); System.Console.ReadLine(); return 0; } } } Save this code as client.cs: using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace RemotingSamples { public class Client { public static int Main(string [] args) { TcpChannel chan = new TcpChannel(); ChannelServices.RegisterChannel(chan);; } } } Save this code as object.cs:; } } } Here's the makefile: all: object.dll server.exe client.exe object.dll: share.cs csc /debug+ /target:library /out:object.dll object.cs server.exe: server.cs csc /debug+ /r:object.dll /r:System.Runtime.Remoting.dll server.cs client.exe: client.cs server.exe csc /debug+ /r:object.dll /r:server.exe /r:System.Runtime.Remoting.dll client.cs
https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/ms973857(v=msdn.10)
CC-MAIN-2019-04
refinedweb
3,717
52.29
Editors Note: This is the first in our new blog series we are entitling Nothing But .Net. Sara Morgan, our resident expert, is an independent Software Developer and long-time .NET programmer who has recently been wooed into the world of Force.com development. She recently filmed her first introductory course covering Visualforce for Lynda.com. Force.com offers several API’s for accessing data on their servers, but one of the oldest and most commonly used is the SOAP API. The first step in using the SOAP API is to download a WSDL file and then create a reference within the application. For .NET users, the reference can either be a web reference or a service reference. As with most things, there are pros and cons to using each method. I will tell you what those pros and cons are so that you can make a decision about which method is best for your particular application. Creating a service reference makes use of the newer Windows Communication Foundation (WCF) framework. This method uses configuration files to define both the binding and the configuration and therefore is loosely coupled from the service implementation. Microsoft recommends that all XML Web service clients are created using this technology. To create the service reference, download the WSDL file from Salesforce and in Visual Studio 2013 go to Project and Add Service Reference (see Figure 1). From here, you need to enter the path to the WSDL file and click GO. You should also specify a name to use as the namespace. This will be referenced from within your code. Figure 1: Dialog to add a WCF service reference to a .NET project Once the service reference is added, you can add code to login to the server and query, create, update or delete Salesforce objects. For specific instructions on how to do this, refer to this article on Consuming Force.com SOAP and REST services from .Net applications. Creating a web reference utilizes the .NET 2.0 Web Services technology and is considered much simpler and outdated. To do this, you will still need to download a WSDL, but to add a web reference using Visual Studio 2013, you will have to perform a few additional steps. You should go to Projects and Add Service Reference and then from here click the Advanced button at the bottom of the dialog (see Figure 2). Figure 2: Click Advanced from Add Service Reference to add a Web Reference This will bring up the Service Reference Settings dialog and from there you can click Add Web Reference (see Figure 3). Figure 3: Service Reference Settings Dialog is used to add a Web Reference. Finally, you can add a web reference by entering a path to the WSDL file and clicking the arrow next to URL (see Figure 4). You will then specify a web reference name and click Add Reference to add it to your Visual Studio 2013 project. Figure 4: Add Web Reference dialog in Visual Studio 2013. For more information about the specific code you should use to access the SOAP API using this method, refer to this tutorial on Integrating Force.com with Microsoft .NET. I originally was going to write this article about how you should always use a service reference, since it is the method that Microsoft recommends when working with SOAP API’s. It also exposes more functionality in terms of the additional headers it makes available. I assumed it would be a faster way to access Salesforce data and so I was surprised when a benchmark test I created revealed a different result. I created a console application using Visual Studio 2013 that created both a service and a web reference to the same WSDL file. Each reference was used to login to the Salesforce server and create a simple case. Using the web reference method, the process takes an average of less than 2 seconds. Using the service reference, that same process took an average of more than 18 seconds. That was not what I was expecting, but as you can see from this Stackoverflow post, I am not the only person to observe this result. According to the accepted answer in the post, the reason for the delay is due to a call to the Channel Factory Class. This object should be cached and reused on subsequent calls, thus making them faster. I confirmed this behavior as well. And the slow result does only apply to the first call. Subsequent calls are much faster, but this applies both to the web reference and the service reference method (see results of multiple calls in Figure 5). Figure 5: Multiple calls to benchmark application reveal that second calls for both methods are much faster. As to the question of which method you should use, I think it depends on the needs and architecture of your application. If you have an application that is already using the web reference method and you have no need to utilize one of the additional headers easily exposed with the WCF method, then I would not change a thing. If you are creating a brand new application that access the SOAP API and you know there is no chance you will ever need to modify one of the headers, then I would go with the web reference method. If however, your application does need to access the headers, then I would consider using the service reference method. It does make accessing the headers a little easier. Just make sure that your application takes into account the slow start time of loading the WCF reference. I would also suggest that you take a look at this MSDN article which shows how to use the XmlSerializer to improve the startup time of WCF client applications.
https://developer.salesforce.com/blogs/developer-relations/2014/09/accessing-force-com-soap-endpoints-net.html
CC-MAIN-2018-34
refinedweb
969
61.16
You might have SQL Mirroring enabled in your Enterprise but might not have alerting enabled or you don’t know how to enable it. If you want to enable that functionality just follow this 2 easy steps. 1. Creating SQL Alerts in SQL Server Agent Go to your SQL Server Agent and on the Alert section, right-click on it and choose New Alert. Now you are presented with the alert properties and just fill it up with the proper information Name : Choose a name for this Alert Type : There are 3 different types and since were interested in Database Mirroring State Change we need to query WMI so choose WMI event alert Namespace : The namespace it auto populated to the namespace you needed so don’t change it Query : Now write your WMI Query. We are looking for the DATABASE_MIRRORING_STATE_CHANGE class so your query goes like this. SELECT * FROM DATABASE_MIRRORING_STATE_CHANGE Now there 19 Properties for that class and you are mainly interested on DatabaseName or DatabaseID and State. DatabaseName or DatabaseID will be the database you are monitoring and State would be Mirroring State of the Database and here are the different values. - Having that in mind you can now filter out alerts by those two properties, so for example I want to have an alert for “SAMPLE” Database where the mirroring Failed Over my query would look like this SELECT * FROM DATABASE_MIRRORING_STATE_CHANGE WHERE DatabaseName = 'SAMPLE' AND State = 8 Now you have an alert you need now to define notifications for operators, you can do that by going to the Response tab and choose who do you want to notify and what notifications they want to receive. Now you define additional options such as message you want to send to those operator At this stage you have a working alert. But it might not work as by default the SQL Server Agent Alert System Mail Profile is disabled 2. Activating SQL Server Agent Alert System Mail Profile. Go to SQL Server Agents properties Then go to Alert System Tab then tick Enable mail profile and choose the Mail system installed on your server as well as its profile Now your done, all you have to do is test, You will get a message similar to this once it’s activated. Pingback: Tweets that mention Create Alerts for SQL Server Mirroring Failovers « Raymund Macaalay's Dev Blog -- Topsy.com Pingback: Create Alerts for SQL Server Mirroring Failovers « Raymund … - sql
http://www.macaalay.com/2010/11/25/create-alerts-for-sql-server-mirroring-failovers/
CC-MAIN-2019-13
refinedweb
409
59.16
Hello friends! Say hello to Magnus – A Utility-First React Native UI Framework that I built recently. Why do you need to choose Magnus UI? - Consistent Design system and API 🏋️ - Full theme customization 👌 - Easy to use. 🚀 - Expanding list of components 🧩 Overview Magnus UI is built with Typescript. Magnus UI is fully typed because it’s built with Typescript. This means that your theme is typed which ensures that you only access a value that exists on your component. Magnus comes with two main aspects: - Utilities - Components Utilities Utilities consist of fundamental properties that defines your brand guidelines. Magnus provides easy API to set the this properties. Components Magnus comes with out of the box well polished react components to get you started quickly. and many more... Getting Started This package is available in npm repository as react-native-magnus. npm install react-native-magnus --save # using yarn yarn add react-native-magnus Wrap your root component in ThemeProvider from react-native-magnus. You can also pass your custom theme as a prop to ThemeProvider import * as React from "react"; import { AppRegistry } from "react-native"; import { ThemeProvider } from "react-native-magnus"; import App from "./src/App"; const theme = { colors: { google: "#4285F4", } } export default function Main() { return ( <ThemeProvider theme={theme}> <Button mt="md" py="lg" rounded="sm" bg="google" block }>Sign-in with Google</Button> </ThemeProvider> ); } AppRegistry.registerComponent("main", () => Main); The above code will give you output like this: Advanced Example %[] Documentation and Examples : Magnus UI Home page Github: It's now your turn to try it !!! Thanks for reading! If you think other people should read this post and use this library, please tweet and share the post 🙂 What do you think, any ideas? Feel free to contact me :) Discussion
https://dev.to/jsartisan/showdev-magnus-ui-a-utility-first-react-native-ui-framework-a1a
CC-MAIN-2020-50
refinedweb
289
56.55
03 April 2012 12:57 [Source: ICIS news] By Yu Guo and Ong Sheau Ling DUBAI (ICIS)--The Gulf Cooperation Council (GCC) region's polymer conversion sector will maintain an annual growth rate of 9-10% up to 2016, GPCA general secretary Abdulwahab Al-Sadoun told ICIS on Tuesday. The actual growth rate may be higher given the increasing exposure of local industry to the global market, he added. "This [9-10%] is already a conservative estimation," he said. Al-Sadoun was speaking prior to the 3rd Gulf Petrochemicals and Chemicals Association (GPCA) Plastic Summit being held in ?xml:namespace> "In 2011, around 3.5m tonnes [of resins] are converted in the Gulf region, that represents 25% of polymer resins manufactured in the region," said Al-Sadoun. "This figure is expected to hit 5.3m tonnes in year 2016," he added. The highlight of the three-day GPCA Plastics Summit, which closes on Thursday, is the market seminar on Tuesday, covering seven papers on various regions such as "Converters will have a better understanding on these markets, so as to create more export opportunities," Al-Sadoun said. About 8.5% of the converted finished products in the Gulf region is exported, he added. "GPCA is the catalyst to facilitate the growth of export-oriented converters," he said. "The plastics industry is rather fragmented and these converters do not have the resources and experience. So, we are here to guide them," Al-Sad
http://www.icis.com/Articles/2012/04/03/9547470/gulfs-conversion-sector-to-grow-annually-by-9-10-until-2016.html
CC-MAIN-2014-10
refinedweb
242
53.81
08 June 2012 06:17 [Source: ICIS news] By Helen Yan ?xml:namespace> SINGAPORE In the week ended 7 June, BR prices were assessed at $2,900-3,000/tonne CFR (cost and freight) northeast (NE) BR prices have been tracking falls in BD values, which shed $600/tonne since early May to $1,850-1,900/tonne CFR NE Asia in the week ended 1 June, ICIS data showed. “There may still be room for the BR prices to drop further in June,” a trader said, citing the current wide spread between BR and BD prices. Taking the latest price assessments by ICIS, the BR-BD price spread is at $1,050-1,100/tonne – way above the $600-700/tonne minimum required for BR producers to generate margins. Downstream tyre makers are expecting BR prices to fall to around $2,600/tonne CFR NE Asia. Apart from the plunging feedstock BD prices, weak demand and ample supply also weighed on BR prices, industry sources said. Buying sentiment is being dampened by the ongoing eurozone debt crisis, a fragile Major downstream tyre producers have cut operating rates to around 80% of capacity, while small- and medium-sized tyre makers have implemented a deeper cut in production, with current run rates at around 50-60% of capacity, given the uncertain global market outlook. Major BR producers in “Some BR producers have high inventories and dropped their prices as they have to clear their surplus stocks,” a trader said. “We can get lower offers from other suppliers in To offset the slump in demand, some major BR producers have reduced their operating rates. Major South Korean BR producer Korea Kumho Petrochemical Co (KKPC) has further reduced operating rates at its 350,000 tonne/year BR plant at Yeosu to 60% in June from about 70-80% in May. “If the feedstock BD prices were to rebound in July, then it is possible the BR prices may bottom out then,” a trader
http://www.icis.com/Articles/2012/06/08/9567412/asia-br-dips-below-3000tonne-may-extend-falls-on-weak.html
CC-MAIN-2015-11
refinedweb
330
60.28
-2012.: =========================================================================== The following abbreviated list of release notes applies to this code base as of this writing (22 February 2012):,) Compiler Notes -------------- - Mixing compilers from different vendors when building Open MPI (e.g., using the C/C++ compiler from one vendor and the Fortran. - In general, the latest versions of compilers of a given vendor's series have the least bugs. We have seen cases where Vendor XYZ's compiler version A.B fails to compile Open MPI, but version A.C (where C>B) works just fine. If you run into a compile failure, you might want to double check that you have the latest bug fixes and patches for your compiler. -). -. - It has been reported that the Intel 9.1 and 10.0 compilers fail to compile Open MPI on IA64 platforms. As of 12 Sep 2012, there is very little (if any) testing performed on IA64 platforms (with any compiler). Support is "best effort" for these platforms, but it is doubtful that any effort will be expended to fix the Intel 9.1 / 10.0 compiler issuers on this platform. - Early versions of the Intel 12.1 Linux compiler suite on x86_64 seem to have a bug that prevents Open MPI from working. Symptoms including immediate segv of the wrapper compilers (e.g., mpicc) and MPI applications. As of 1 Feb 2012, if you upgrade to the latest version of the Intel 12.1 Linux compiler suite, the problem will go away. - see with which Fortran compiler Open MPI was configured and compiled. There are up to three sets of Fortran MPI bindings that may be provided (depending on your Fortran compiler): - mpif.h: This is the first MPI Fortran interface that was defined in MPI-1. It is a file that is included in Fortran source code. are considered thread safe. Other support functions (e.g., MPI attributes) have not been certified as safe when simultaneously used by multiple threads. - tcp - sm - self. -" and "csum" PMLs. -. ===========================================================================: INSTALLATION OPTIONS --prefix=<directory> Install Open MPI into the base directory named <directory>. Hence, Open MPI will place its executables in <directory>/bin, its header files in <directory>/include, its libraries in <directory>/lib, etc. -. Be sure to read the description of --without-memory-manager, below; it may have some effect on --enable-static. -. -cflags>: Flags passed by the mpifort wrapper to the FortranC - Fortran compiler to use FCFLAGS - Compile flags to pass to the Fortran compiler LDFLAGS - Linker flags to pass to all compilers LIBS - Libraries to pass to all compilers (it is rarely necessary for users to need to specify additional LIBS) PKG_CONFIG - Path to the pkg-config. Note that if you intend to compile Open MPI with a "make" other than the default one in your PATH, then you must either set the $MAKE environment variable before invoking Open MPI's configure script, or pass "MAKE=your_make_prog" to configure. For example: shell$ ./configure MAKE=/path/to/my/make ... This could be the case, for instance, if you have a shell alias for "make", or you always type "gmake" out of habit. Failure to tell configure which non-default "make" you will use to compile Open MPI can result in undefined behavior (meaning: don't do that). Note that you may also want to ensure that the value of LD_LIBRARY_PATH is set appropriately (or not at all) for your build (or whatever environment variable is relevant for your operating system). For example, some users have been tripped up by setting to use a non-default Fortran compiler via FC,. =========================================================================== Open. Extensions ----------------------- Open MPI contains a framework for extending the MPI API that is available to applications. Each extension is usually a standalone set of functionality that is distinct from other extensions (similar to how Open MPI's plugins are usually unrelated to each other). These extensions provide new functions and/or constants that are available to MPI applications. WARNING: These extensions are neither standard nor portable to other MPI implementations!. Using the extensions -------------------- To reinforce the fact that these extensions are non-standard, you must include a separate header file after <mpi.h> to obtain the function prototypes, constant declarations, etc. For example: ----- #include <mpi.h> #if defined(OPEN_MPI) && OPEN_MPI #include <mpi-ext.h> #endif int main() { MPI_Init(NULL, NULL); #if defined(OPEN_MPI) && OPEN_MPI { char ompi_bound[OMPI_AFFINITY_STRING_MAX]; char current_binding[OMPI_AFFINITY_STRING_MAX]; char exists[OMPI_AFFINITY_STRING_MAX]; OMPI_Affinity_str(OMPI_AFFINITY_LAYOUT_FMT, ompi_bound, current_bindings, exists); } #endif MPI_Finalize(); return 0; } ----- Notice that the Open MPI-specific code is surrounded by the #if statement to ensure that it is only ever compiled by Open MPI. The Open MPI wrapper compilers (mpicc and friends) should automatically insert all relevant compiler and linker flags necessary to use the extensions. No special flags or steps should be necessary compared to "normal" MPI applications. =========================================================================== Compiling Open MPI Applications ------------------------------- Open MPI provides "wrapper" compilers that should be used for compiling MPI applications: C: mpicc C++: mpiCC (or mpic++ if your filesystem is case-insensitive) Fortran: mpifort. sharedfp - shared file pointer operations for MPI I/O topo - MPI topology routines vprotocol - Protocols for the "v" PML Back-end run-time environment (RTE) MX / Open-MX. Each component typically activates itself when relavant. For example, the MX component will detect that MX devices are present and will automatically be used for MPI communications. The SLURM component will automatically detect when running inside a SLURM job and activate itself. And so on. Components can be manually activated or deactivated if necessary, of course. The most common components that are manually activated, deactivated, or tuned are the "BTL" components -- components that are used for MPI point-to-point communications on many types common networks. For example, to *only* activate the TCP and "self" (process loopback) components are used for MPI communications, specify them in a comma-delimited list to the "btl" MCA parameter: shell$ mpirun --mca btl tcp,self hello_world_mpi To add shared memory support, add "sm" into the command-delimited list (list order does not matter): shell$ mpirun --mca btl tcp,sm,self hello_world_mpi. ===========================================================================!
https://bitbucket.org/jimmycao/ompi-g
CC-MAIN-2017-47
refinedweb
999
55.03
Recently Microsoft added some new features in its ASP.NET Web Application Framework. SignalR is one of the prominent feature to build real time application e.g. social application, multiuser games, news weather etc. In real time applications server pushes the content to connected clients instantly it become available. It provides a simple ASP.NET API for creating server-to-client remote procedure calls (RPC) that calls JavaScript functions in client browsers from server-side .NET code. The web application works in Request-Response model. Browsers and other user agents make requests and web server provide a response to that request. The response is sent to the delivery address provided in the request by user agent. In this model server can’t make responses without a request. So in real time application server pushed newly available contents/data to the client. You can achieve this feature using ASP.NET SignalR API. For explaining the SignalR Web API, in this article we will create a chat application where you can do group chat and private chat with single user. You require Visual Studio 2012 Express Development Tool for creating this project. You can get more details on Create a new web application project in visual studio and In Solution Explorer, Right-click the project, select Add > New Item, and select the SignalR Hub Class item. Name the class and press the Add button. It will add the Hub class, required references and scripts. You can see added script and references by expanding ‘Scripts’ and ‘References’ nodes. For using SignalR API, we need to register ~/signalr/hubs URL. Add global.asax file in your solution and in the Application_Start method register hub url using RouteTable.Routes.MapHubs() command. SignalR ~/signalr/hubs global.asax Application_Start RouteTable.Routes.MapHubs() public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { // Register the default hubs route: ~/signalr/hubs RouteTable.Routes.MapHubs(); } } ChatHub class must be inherited from the Microsoft.AspNet.SignalR.Hub class. The Hub class exposes some properties and methods. Using Clients property you can communicate with connected clients. You can get the information of client who is calling method using Context and you can also manage groups using Groups property. ChatHub Microsoft.AspNet.SignalR.Hub class Hub Clients Context Groups public abstract class Hub : IHub, IDisposable { public HubConnectionContext Clients { get; set; } public HubCallerContext Context { get; set; } public IGroupManager Groups { get; set; } public virtual Task OnConnected(); public virtual Task OnDisconnected(); public virtual Task OnReconnected(); } Derived class can override OnConnected, OnDisconnected, which are very useful to perform some actions on these events. ChatHub class is derived from the Hub class and we will discuss its method in next comming sections. OnConnected OnDisconnected public class ChatHub : Hub { public void Connect(string userName); public void SendMessageToAll(string userName, string message); public void SendPrivateMessage(string toUserId, string message); public override System.Threading.Tasks.Task OnDisconnected(); . . . } Client calls Connect method when he wants to join Chat room. For sending message in chat room to all connected clients, it calls SendMessageToAll , For private chat with single user client calls SendPrivateMessage method. Connect SendMessageToAll SendPrivateMessage Add new page index.html in the solution and set the references of JQuery, SignalR and autogenerated hubs. <script src=""></script> <!--Reference the SignalR library. --> <script src=""></script> <!--Reference the autogenerated SignalR hub script. --> <script src=""></script> At the client side you need to create the hub proxy and start that proxy. You can create hub proxy using $.connection.yourHubClass and then start hub using $.connection.hub.start() method. $.connection.yourHubClass $.connection.hub.start() <script type="text/javascript"> $(function () { // Declare a proxy to reference the hub. var chatHub = $.connection.chatHub; registerClientMethods(chatHub); // Start Hub $.connection.hub.start().done(function () { registerEvents(chatHub) }); }); </script> The import thing to be noticed here is the naming convention is being used in auto generated Hub proxy. We named our class ChatHub at server in camel case but at client side we are getting it in lower camel case like $.connection.chatHub $.connection.chatHub In our Chat room user connects to the chat room by passing his name and on the successful connection, we send him a list of connected clients and some recent chat history which we saves in our application. Our first method in the ChatHub class is the Connect. public void Connect(string userName) { var id = Context.ConnectionId; if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0) { ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserName = userName }); // send to caller Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage); // send to all except caller client Clients.AllExcept(id).onNewUserConnected(id, userName); } } Get the connection id of the client who is calling the Connect method using Context.ConnectionId property. Check the id in existing connected clients list. If it does not exist then add it into the list. Now we need to do two more steps. First we have to send list of already connected clients and recent message list to the client who wants to connect and second we have to inform the other connected clients about new joiner. Context.ConnectionId So we can easily call the client side method of single client who want to connect using Clients.Caller property. Clients.Caller // send to caller Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage); Inform the other connected clients about the new client, but we don’t want to call the method of the newly connected client. Use AllExcept property of the Clients, which can excludes some client as per your wish. AllExcept // send to all except caller client Clients.AllExcept(id).onNewUserConnected(id, userName); Define/Expose your client side methods which are being called by server side code by statements Clients.Caller.onConnected(...) and Clients.AllExcept(id).onNewUserConnected(...). You can define your methods using chatHub.client.yourMethodName at client side. Clients.Caller.onConnected(...) Clients.AllExcept(id).onNewUserConnected(...) chatHub.client.yourMethodName // Calls when user successfully logged in chatHub.client.onConnected = function (id, userName, allUsers, messages) { . . . } // On New User Connected chatHub.client.onNewUserConnected = function (id, name) { AddUser(chatHub, id, name); } From the client side you can Call the server side methods using chatHub.server.yourMethod statement in your web page. chatHub.server.yourMethod chatHub.server.connect(name); In main chat room message typed by user is broadcast to all connected clients. On the server side in ChatHub class write SendMessageToAll and broadcast message using Clients.All.messageReceived method. messageReceived is a client side method. Clients.All.messageReceived messageReceived public void SendMessageToAll(string userName, string message) { // store last 100 messages in cache AddMessageinCache(userName, message); // Broad cast message Clients.All.messageReceived(userName, message); } On client side expose the messageReceived method and in this method simply add message in the chat area using JQuery. chatHub.client.messageReceived = function (userName, message) { AddMessage(userName, message); } After writing client side and server side methods, now we have to register button click event on client side and when user will click button we will call server side method sendMessageToAll, which broadcast message to the all connected clients. sendMessageToAll $('#btnSendMsg').click(function () { var msg = $("#txtMessage").val(); if (msg.length > 0) { var userName = $('#hdUserName').val(); chatHub.server.sendMessageToAll(userName, msg); $("#txtMessage").val(''); } }); You can also initiate private chat by double clicking on the connected client name. In private chat we do not send message to all connected client. In Private chat only two clients can send/receive each other message. So for sending private message sender will call server side sendPrivateMessage method. And in this method we send message to other client using Clients.Client(toUserId).sendPrivateMessage(..) method. sendPrivateMessage Clients.Client(toUserId).sendPrivateMessage(..) public void SendPrivateMessage(string toUserId, string message) { string fromUserId = Context.ConnectionId; var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId) ; var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId); if (toUser != null && fromUser!=null) { // send to Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message); // send to caller user Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message); } } On the close of the browser SignalR API calls OnDisconnected method. Override this method in your ChatHub class and in this method remove disconnected client from the cache list and send notification to other connected clients. public override System.Threading.Tasks.Task OnDisconnected() { var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId); if (item != null) { ConnectedUsers.Remove(item); var id = Context.ConnectionId; Clients.All.onUserDisconnected(id, item.UserName); } return base.OnDisconnected(); } This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) 1. Used Nuget to get the latest SignalR ("Install-Package Microsoft.AspNet.SignalR") 2. Import "ChatHub.cs" to "/Controllers" 3. Changed the "OnDisconnect()" method to use the new boolean parm in SignalR 2.1.1 4. Imported "UserDetail" and "MessageDetail" to "/Models" 5. Imported "index.html" as "chat.cshtml" and pasted script into separate "Scripts/chat.js" 6. Imported "ChatStyle.css" to "/Content" 7. Used Nuget to install JQueryUI ("Install-Package jQuery.UI.Combined") 8. Modified "Startup.cs" for SignalR 2.1.1 as per "" 9. In the "ChatStyle.css" made div section for messages "position: fixed" 9b. in "ChatStyle.css" made the div section for users signed in to "position: relative" 9c. in "ChatStyle.css" changed the Chat Window length from 300 to 200 (it is in three places) @section scripts { <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery-ui-1.11.1.js"></script> <!--Reference the SignalR library. --> <script src="~/Scripts/jquery.signalR-2.1.1.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="~/signalr/hubs"></script> <script src="~/Scripts/chat.js"></script> } General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/script/Articles/View.aspx?aid=562023
CC-MAIN-2014-41
refinedweb
1,606
51.24
chdir · getcwd · machine_name · neuronhome · nrn_load_dll · nrnversion · show_winio · startsw · stopsw · system · unix_mac_pc · WinExec System Calls¶ ↑ Path Manipulation¶ ↑ chdir()¶ ↑ - Syntax: h.chdir("path") - Description: - Change working directory to the indicated path. Returns 0 if successful otherwise -1, ie the usual unix os shell return style. getcwd()¶ ↑ - Syntax: h.getcwd() - Description: - Returns absolute path of current working directory in unix format. The last character of the path name is ‘/’. Must be less than 1000 characters long. neuronhome()¶ ↑ - Name: - neuronhome – installation path - Syntax: h.neuronhome() - Description: Returns the full installation path in unix format or, if it exists, the NEUROHOME environment variable in unix format. Note that for unix, it isn’t exactly the installation path but the –prefix/share/nrn directory where –prefix is the location specified during installation. For the mswin version it is the location selected during installation and the value is derived from the location of neuron.exe in neuronhome()/bin/neuron.exe. For mac it is the folder that contains the neuron executable program. Machine Identification¶ ↑ machine_name()¶ ↑ - Syntax: h("strdef name") h.machine_name(h.name) - Description: - returns the hostname of the machine. unix_mac_pc()¶ ↑ - Syntax: h.unix_mac_pc() - Description: - Return 1 if unix, 2 if (an older) mac, 3 if mswin, or 4 if mac osx darwin is the operating system. This is useful when deciding if a machine specific function can be called or a dll can be loaded. - Example: from neuron import h, gui type = h.unix_mac_pc() if type == 1: print("This os is unix based") elif type == 2: print("This os is mac based") elif type == 3: print("This os is mswin based") elif type == 4: print("This os is mac osx darwin based") nrnversion()¶ ↑ - Syntax: h.nrnversion() h.nrnversion(i) - Description: Returns a string consisting of version information. When this function was introduced the majorstring was “5.6” and the branch string was “2004/01/22 Main (36)”. Now the arg can range from 0 to 6. The value of 6 returns the args passed to configure. When this function was last changed the return values were. An arg of 7 now returns a space separated string of the arguments used during launch. e.g. $ nrniv -nobanner -c 'nrnversion()' -c 'nrnversion(7)' NEURON -- VERSION 7.2 twophase_multisend (534:2160ccb31406) 2010-12-09 nrniv -nobanner -c nrnversion() -c nrnversion(7) $ An arg of 8 now returns the host-triplet. E.g. $ nrniv -nobanner -c 'nrnversion(8)' x86_64-unknown-linux-gnu An arg of 9 now returns “1” if the neuron main program was launched, “2” if the library was loaded by Python, and “0” if the launch progam is unknown $ nrniv -nobanner -c 'nrnversion(9)' 1 $ python 2</dev/null >>> from neuron import h >>> h.nrnversion(9) '2' - Example: from neuron import h, gui h.nrnversion() NEURON -- VERSION 7.1 (296:ff4976021aae) 2009-02-27 for i in range(6): print('{} : {}'.format(i, h.nrnversion(i))) 0 : 7.5 1 : NEURON -- VERSION 7.5 (1482:5fb6a5cbbdb7) 2016-11-25 2 : VERSION 7.5 (1482:5fb6a5cbbdb7) 3 : 5fb6a5cbbdb7 4 : 2016-11-25 5 : 1482 6 : '--with-iv=/usr/site/nrniv/iv' '--prefix=/usr/site/../arch/nrn' '--with-nrnpython' '--with-paranrn' Execute a Command¶ ↑ system()¶ ↑ - Name: - system — issue a shell command - Syntax: exitcode = h.system(cmdstr) exitcode = h.system(cmdstr, stdout_str) - Description: - Executes cmdstr as though it had been typed as command to a unix shell from the terminal. HOC waits until the command is completed. If the second strdef arg is present, it receives the stdout stream from the command. Only available memory limits the line length and number of lines. Example: h.system("ls") - Prints a directory listing in the console terminal window. will take up where it left off when the user types the exitcommand Warning Fully functional on unix, mswin under cygwin, and mac osx. Does not work on the mac os 9 version. Following is obsolete: Under mswin, executes the string under the cygwin sh.exe in $NEURONHOME/binvia the wrapper, $NEURONHOME/lib/nrnsys.sh. Normally, stdout is directed to the file tmpdos2.tmpin the working directory and this is copied to the terminal. The neuron.exe busy waits until the nrnsys.sh script creates a tmpdos1.tmp file signaling that the system command has completed. Redirection of stdout to a file can only be done with the idiom “command > filename”. No other redirection is possible except by modifying nrnsys.sh. Timing¶ ↑ startsw()¶ ↑ stopsw()¶ ↑ - Syntax: h.stopsw() Returns the time in seconds since the stopwatch was last initialized with a startsw(). - Description: Really the idiom x = h.startsw() h.startsw() - x should be used since it allows nested timing intervals. - Example: from neuron import h, gui from math import sin h.startsw() for i in range(100000): x = sin(0.2) print(h.stopsw()) Note A pure Python alternative would be to use the time module’s time function.
https://www.neuron.yale.edu/neuron/static/py_doc/programming/system.html
CC-MAIN-2020-34
refinedweb
804
59.9
WSE helps developers build scalable, secure Web services that cross security domains. It also supports sending SOAP messages using transports other than HTTP. Another feature is the ability to build a SOAP router, so SOAP messages could be sent to a SOAP router and the router will delegate the work to the applicable Web server hosting the Web service. Yet another feature, and the subject of this article, is the support for Direct Internet Message Encapsulation (DIME). This is an important protocol for sending binary attachments, as it specifies a method for sending attachments in their binary form rather than encoding with either hexidecimal or base64 encoding, which can increase the size of the attachment by approximately 30 percent. In this article, I'll create the C# code necessary to attach a simple DIME attachment to a SOAP message. If you haven't already installed the WSE 2.0, you'll need to download it from Microsoft's Web site. (Be sure you meet the requirements specified on the WSE 2.0 Web page.) Once you install it, you can begin creating your DIME service. The first thing to do is to create an ASP.NET Web service project in Microsoft Visual Studio .NET (VS.NET). Add a reference to the Microsoft.Web.Services2 class library in your project. Then, add the following elements to the Web.config file within the <system.web> element: > Another way you can accomplish this is to right-mouse click on the Project in the project view and choose WSE Settings 2.0... Select both check boxes on the General tab; this will add the appropriate config settings. Finally, create the method that will attach the DIME attachment to the SOAP message. I'm going to add a method called CreateDimeAttachment(). This method will accept one input parameter, the absolute path to the file to attach: public void CreateDimeAttachment(string filepath) { SoapContext ctx = ResponseSoapContext.Current; DimeAttachment attach = new DimeAttachment("image/jpeg", TypeFormat.MediaType, filepath); ctx.Attachments.Add(attach); } What happens here is the current context of the Web service response is stored to the local variable ctx. A new DimeAttachment is created using the image/bmp type format and the path to the file (I'm assuming that the path to the file is going to be a bitmap file). The new DimeAttachment is added to the Attachments collection of the current response context. Now all you have to do is add the appropriate using statements to the top of the .asmx file: using Microsoft.Web.Services2.Dime; using Microsoft.Web.Services2; using System.Net; Here's my total example code for this solution: In order to test your code, you must create a SOAP client. Simply using the supplied default page for invocation of the Web service will not work. You can create a SOAP client by creating a new ASP.NET Web application and adding a Web reference to your new Web service. You must also add the WSE configuration settings as above. 1 moises - 17/02/08 hola como estas de donde eres » Report offensive content
http://www.builderau.com.au/webdev/soa/Using-WSE-DIME-in-NET/0,339024680,339170924,00.htm
crawl-002
refinedweb
514
58.38
1) Create a (C++/CX) "Windows Runtime Component" (let's say "MyComponent") add a namespace call it "XamlStuff" with a "UserControl"; 2) Create a (C++/CX) "Blank App (XAML)" Windows Store app and add the "UserControl" to your "MainPage"; 3) Build it. And surprise, it doesn't. The result is that (for some reason) it creates a directory for you XAML called "../Debug/XamlStuff/zzz" in where you will find your XAML stuff. Still while building it will try to find the needed XAML (zzz) IN "../Debug/MyComponent/XamlStuff/...". What should I do? 1) Just create a directory "../Debug/MyComponent"; 2) copy the "zzz" into this new folder; 3) Build it. It just works! I couldn't find a way to influence the compile/build process to place the XAML resources where it is expecting to find those. It is OK to do it by hand and once or twice, but every time I do an update, it is annoying. Please fix this thing, else tell me how I influence the compiler/linker/builder to do right thing! (hopefully it will be an easy task...) Ed. Thanks for you reply! I over simplify the real scenario and didn't test the simplify case I presented. In this mickey mouse sample following my instructions all works fine, still as soon as you build-up a library it is not that simple. The issue that I do have is that I don't use the default output projects folders where all (for small solutions) or a couple of components things work great, instead I use a common output assemblies repository that don't require the use of separate debug / release directories per project and there is where the build gets bad. Anyways, thanks for the reply and the time to put the sample together.
https://social.msdn.microsoft.com/Forums/en-US/48b97a57-fad2-4eb4-9b7d-3df0f51065f2/windows-runtime-component-with-xaml-resources-incorrectly-built?forum=winappswithnativecode
CC-MAIN-2021-49
refinedweb
302
72.36
#include <High_Res_Timer.h> Most of the member functions don't return values. The only reason that one would fail is if high-resolution time isn't supported on the platform. To avoid impacting performance and complicating the interface, in that case, <ACE_OS::gettimeofday> is used instead. The global scale factor is required for platforms that have high-resolution timers that return units other than microseconds, such as clock ticks. It is represented as a static u_long, can only be accessed through static methods, and is used by all instances of High Res Timer. The member functions that return or print times use the global scale factor. They divide the "time" that they get from <ACE_OS::gethrtime> by global_scale_factor_ to obtain the time in microseconds. Its units are therefore 1/microsecond. On Windows the global_scale_factor_ units are 1/millisecond. There's a macro <ACE_HR_SCALE_CONVERSION> which gives the units/second. Because it's possible that the units/second changes in the future, it's recommended to use it instead of a "hard coded" solution. Dependend on the platform and used class members, there's a maximum elapsed period before overflow (which is not checked). Look at the documentation with some members functions. On some (most?) implementations it's not recommended to measure "long" timeperiods, because the error's can accumulate fast. This is probably not a problem profiling code, but could be on if the high resolution timer class is used to initiate actions after a "long" timeout. On Solaris, a scale factor of 1000 should be used because its high-resolution timer returns nanoseconds. However, on Intel platforms, we use RDTSC which returns the number of clock ticks since system boot. For a 200MHz cpu, each clock tick is 1/200 of a microsecond; the global_scale_factor_ should therefore be 200 or 200000 if it's in unit/millisecond. On Windows QueryPerformanceCounter() is used, which can be a different implementation depending on the used windows HAL (Hardware Abstraction Layer). On some it uses the PC "timer chip" while it uses RDTSC on others. Gabe <begeddov@proaxis.com> raises this issue regarding <ACE_OS::gethrtime>: on multi-processors, the processor that you query for your <timer.stop> value might not be the one you queried for <timer.start>. Its not clear how much divergence there would be, if any. This issue is not mentioned in the Solaris 2.5.1 gethrtime man page. A RDTSC NOTE: RDTSC is the Intel Pentium read-time stamp counter and is actualy a 64 bit clock cycle counter, which is increased with every cycle. It has a low overhead and can be read within 16 (pentium) or 32 (pentium II,III,...) cycles, but it doesn't serialize the processor, which could give wrong timings when profiling very short code fragments. Problematic is that some power sensitive devices (laptops for example, but probably also embedded devices), do change the cycle rate while running. Some pentiums can run on (at least) two clock frequency's. Another problem arises with multiprocessor computers, there are reports that the different RDTSC's are not always kept in sync. A windows "timer chip" NOTE: (8254-compatible real-time clock) When QueryPerformanceCounter() uses the 8254 it has a frequency off about 1.193 Mhz (or sometimes 3.579 Mhz?) and reading it requires some time (several thousand cycles). Initialize the timer. Destructor. Set (and return, for info) the global scale factor by sleeping for usec and counting the number of intervening clock cycles. Average over iterations of usec each. On some platforms, such as Pentiums, this is called automatically during the first ACE_High_Res_Timer construction with the default parameter values. An application can override that by calling calibrate with any desired parameter values _prior_ to constructing the first ACE_High_Res_Timer instance. Beware for platforms that can change the cycle rate on the fly. Dump the state of an object. Calculate the difference between two ACE_hrtime_t values. It is assumed that the end time is later than start time, so if end is a smaller value, the time counter has wrapped around. Sets usecs to the elapsed (stop - start) time in microseconds. Will overflow on windows when measuring more than appox. 2^^54 ticks. Is still more than 48 days with a 4 Ghz counter. Set nanoseconds to the number of nanoseconds elapsed. Will overflow when measuring more than 194 day's. Set tv to the number of microseconds elapsed. Could overflow within hours on windows with emulated 64 bit int's and a fast counter. VC++ and Borland normaly use __int64 and so normaly don't have this problem. Set <nsec> to the number of nanoseconds elapsed between all calls to start_incr and stop_incr. Set tv to the number of microseconds elapsed between all calls to start_incr and stop_incr. Sets the global_scale_factor to the value in the env environment variable. Returns 0 on success, -1 on failure. For internal use: gets the high-resolution time using <ACE_OS::gethrtime>. Except on platforms that require that the <global_scale_factor_> be set, such as ACE_WIN32, uses the low-resolution clock if the <global_scale_factor_> has not been set. Get the current "time" as the high resolution counter at this time. This is intended to be useful for supplying to a ACE_Timer_Queue as the gettimeofday function, thereby basing the timer calculations on the high res timer rather than wall clock time. Returns the global_scale_factor. global_scale_factor_ is set to gsf. All High_Res_Timers use global_scale_factor_. This allows applications to set the scale factor just once for all High_Res_Timers. Check High_Res_Timer.cpp for the default global_scale_factors for several platforms. For many platforms (e.g., Solaris), the global_scale_factor_ is set to 1000 so that <scale_factor> need not be set. Careful, a <scale_factor> of 0 will cause division by zero exceptions. Depending on the platform its units are 1/microsecond or 1/millisecond. Use <ACE_HR_SCALE_CONVERSION> inside calculations instead a hardcoded value. Converts an hrt to tv using global_scale_factor_. Print average time. Print total time. print_totalif incremental timings had been used! Reinitialize the timer. Start timing. Start incremental timing. Stop timing. Stop incremental timing. Declare the dynamic allocation hooks. Ending time. Converts ticks to microseconds. That is, ticks / global_scale_factor_ == microseconds. Indicates the status of the global scale factor, 0 = hasn't been set 1 = been set -1 = HR timer not supported Starting time. Start time of incremental timing. Total elapsed time.
http://www.dre.vanderbilt.edu/Doxygen/5.6.8/html/ace/a00244.html
CC-MAIN-2014-42
refinedweb
1,052
59.19
ATAN(3P) POSIX Programmer's Manual ATAN(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. atan, atanf, atanl — arc tangent function #include <math.h> double atan(double x); float atanf(float x); long double atan [−π/2,π/2] radians. If x is NaN, a NaN shall be returned. If x is ±0, x shall be returned. If x is ±Inf, ±π/2 shall be returned. If x is subnormal, a range error may occur and x should be returned. If x is not returned, atan(), atanf(), and atanl() shall return an implementation-defined value no greater in magnitude than DBL_MIN, FLT_MIN, and LDBL_MIN, respectively.. atan2(3p), feclearexcept(3p), fetestexcept(3p), isnanAN(3P) Pages that refer to this page: math.h(0p), atan2(3p), atanf(3p), atanl(3p), tan(3p)
http://man7.org/linux/man-pages/man3/atan.3p.html
CC-MAIN-2017-39
refinedweb
162
58.58
I am working on web services in struts. Now I want json object using its key value. Then I have to post something like array in response. I have no idea how to do that in Struts. I know how to do it in Servlets. So, I am using the following code I have tried, but I think it is different in Struts. JSONObject json = (JSONObject)new JSONParser().parse(jb.toString()); String key_value= json.get("key").toString(); Working with JSON not necessary to send JSON to Struts. Even if it could be configured to accept JSON content type, it won't help you. You can use ordinary request to Struts with the data passed in it. If it's an Ajax call then you can use something like $.ajax({ url: "<s:url", data : {key: value}, dataType:"json", success: function(json){ $.each(json, function( index, value ) { alert( index + ": " + value ); }); } }); The value should be an action property populated via params interceptor and OGNL. The json returned in success function should be JSON object and could be used directly without parsing. You need to provide action configuration and setter for the property key. struts.xml: <package name="aaa" namespace="/aaa" extends="json-default"> <action name="bbb" class="com.bbb.Bbb" method="ccc"> <result type="json"> <param name="root"> </result> </action> </package> This configuration is using "json" result type from the package "json-default", and it's available if you use struts2-json-plugin. Action class: public class Bbb extends ActionSupport { private String key; //setter private List<String> value = new ArrayList<>(); //getter public String ccc(){ value.add("Something"); return SUCCESS; } } When you return SUCCESS result, Struts will serialize a value property as defined by the root parameter to the JSON result by invoking its getter method during serialization. If you need to send JSON to Struts action you should read this answer.
https://codedump.io/share/NxkmkTU5Y349/1/how-to-get-json-object-using-its-key-value-in-struts
CC-MAIN-2017-26
refinedweb
308
66.64
Hi, I want to edit a ms word document online i.e. on browser. Actually I want to open a ms word document from the server using ASPOSE.WORDS for .NET on the browser, want to make some modification on it and finally want to reflect these changes corresponding document on the server. Is it possible through ASPOSE.WORDS for .NET. I'm using ASP.NET. This message was posted using Aspose.Live 2 Forum Hi <?xml:namespace prefix = o Thanks for your inquiry. Aspose.Words is a class library for processing Word documents programmatically, it does not provide user interface for editing your documents. There are a lot of good products on the market which provide user interface for editing documents, like "TX Text Control", "Subsystems TE", "Text Dynamics", "Rad Editor", "ALLText HT/Pro". Also there are some web-based editors like Buzzword, Google Docs, ZohoWriter. Best regards,
https://forum.aspose.com/t/editing-a-ms-word-file-online/77582
CC-MAIN-2022-27
refinedweb
149
58.69
Ok I have another homework problem. Essentially I am to make a text file of randomized characters ( leters bothe upper and lower case, numbers, spaces and specialized characters) and import it as a string into my program. From there I am to make all lowercase letters uppercase. I think I can handle the latter but the part I'm having issues with is bring in the file. I have looked through the forum and found some stuff about bufferereader and io exceptions thrown and null etc but that didn't make any sense plus that solution seemed very complicated for something that seems like it should be maybe 2 lines. I have some of the initial code: package lab7a; /** * * @author 24x24 */ import java.util.Scanner; public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String filePath = getFilePath();//gets the file path from user String random = getString(filePath);//finds string from the filepath String convert = convertString();//converts the lower case in string to uppercase String write = writeString();//rewrites file } public static String getFilePath (){ System.out.print("Enter the file name: "); Scanner keyboard = new Scanner(System.in);//user input for the file path String filePath = keyboard.next(); return filePath;//returns filePath }//end getFilePath public static String getString (String filePath){ //this is where I am currently stuck }//end getString } Once I get the string from the file I am assuming I can just use toUpper and it will only change the letters that are lower case. If not I could put the string into an array or something and search the array for letters that are equivalent to ascii values from a-z convert then copy it all to a new array, output as string and then write to file. I'm pretty certain I can figure that one out either way. Its the read from file issue that I'm in need of some assistance. Thanks in advance, 24x24
https://www.daniweb.com/programming/software-development/threads/349937/homework-import-string
CC-MAIN-2017-47
refinedweb
329
67.69
Conditional rendering and List rendering React interview cheatsheet series 23 April, 2021 A quick answer in a interview would be something like: In ReactJS you can create components that renders different code depends on the state of the app, so for example: function ConditionalRenderingComponent(props) { const isTrue = props.isTrue; return ( <p>It's { isTrue ? 'true' : 'false' }</p> ); } ReactDOM.render( <ConditionalRenderingComponent isTrue={true} />, document.getElementById('root') ); So our component is listening a state var or a prop and depends on its value, the component renders a block of code or other. Lists and keys Each time you render a list, you have to set a unique key to that list so react knows which elements (list items) are changed and which not, avoiding render more than the needed. Important to mention ReactJS's key prop, which gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps the same DOM, even if the props changed. The exception to this is the key prop. This allows you to return the exact same element type, but force React to unmount the previous instance, and mount a new one. Also to mention that using index as a key is an anti-pattern. If the prop 'key' is used to identify DOM elements which are unmounted and mounted again, if the key prop is the same again and again, Reacts think that the DOM is exactly the same than before, which is not the case. So instead of doing this: todos.map((todo, index) => ( <Todo {...todo} key={index} /> )); } Do this: todos.map((todo) => ( <Todo {...todo} key={todo.id} /> )); } The only exception is when the list of elemets are static, they are not filtered or reorders,, or they don't have an id either. See official doc:.
https://www.albertofortes.com/conditional-rendering-and-list-rendering/
CC-MAIN-2021-31
refinedweb
321
62.88
View Source README Easily backup your SQLite database right from Elixir using Litestream Contents installation Installation Available in Hex, the package can be installed by adding litestream to your list of dependencies in mix.exs: def deps do [ {:litestream, "~> 0.3.0"} ] end Documentation can be found at. supporting-litestream Supporting Litestream If you rely on this library to backup your SQLite databases, it would much appreciated if you can give back to the project in order to help ensure its continued development. Checkout my GitHub Sponsorship page if you want to help out! gold-sponsors Gold Sponsors silver-sponsors Silver Sponsors bronze-sponsors Bronze Sponsors setting-up-litestream Setting Up Litestream After adding {:litestream, "~> 0.2.0"} in your mix.exs file and running mix deps.get, open your application.ex file and add the following to your supervision tree: @impl true def start(_type, _args) do children = [ # Start the Ecto repository LitescaleTest.Repo, {Litestream, litestream_config()}, ... ] opts = [strategy: :one_for_one, name: MyApp.Supervisor] Supervisor.start_link(children, opts) end defp litestream_config do Application.get_env(:my_app, Litestream) end In your runtime.exs (or dev.exs if you are just developing locally): config :my_app, Litestream, repo: MyApp.Repo, replica_url: System.fetch_env!("REPLICA_URL"), access_key_id: System.fetch_env!("ACCESS_KEY_ID"), secret_access_key: System.fetch_env!("SECRET_ACCESS_KEY") With those in place, you should be all set to go! As soon as your application starts, your database will be automatically synced with your remote destination. attribution Attribution - The logo for the project is an edited version of an SVG image from the unDraw project - The Litestream library that this library wraps Litestream
https://hexdocs.pm/litestream/readme.html
CC-MAIN-2022-40
refinedweb
261
52.36
after the process mail, now one on the contents. On Wed, 20 Jul 2005, Andrew Liles <al@starfishzone.com> wrote: > Alternatively I could offer the tasks as an External Tool, this > route would affect namespace choice etc, but I would prefer the > former. Why? > My tasks are: 1. CvsExportDiff - extracts files altered betwen two > tags/dates from CVS ready for zip/etc as a patch set. [...] > I guess that either no-one felt this task useful or I submitted this > in the wrong way (and hence the purpose of this question email). You did not submit it the wrong way, but if you want discussions to happen, use email instead of a webpage. > 2. SqlSync - a task to replicate data (one-way) between two JDBC > compliant databases. Both look interesting on their own right, but neither of both has a reason to be a part of Ant instead of something external IMHO. Stefan --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org For additional commands, e-mail: dev-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-dev/200507.mbox/%3C87u0ipo91g.fsf@www.samaflost.de%3E
CC-MAIN-2014-10
refinedweb
172
65.52
Lesson 6 - Arena Warrior - Encapsulation In the previous lessons, The this pointer in C++, we explained the this keyword. We already have one fully-featured object which us a rolling die. We're going to finish up our arena in the next two lessons. We already have a rolling die, but we're still missing two essential objects: the warrior and the arena itself. Today, we're going to focus mainly on the warrior. First, we'll decide what he (or she) will be able to do, and then we'll write our code. To begin with, please delete printing to the console in the RolligDie constructors and destructor. For further work, these logs would mess with our output. Fields The warrior will have HP (which stands for health points/hit points, e.g. 80hp). We'll store his maximum health, which will vary each instance, and his current health, e.g. a wounded warrior will have 40hp from 80 total. The warrior will have a damage and defense, which will be both defined in hp. When a warrior, with 20hp damage, attacks another warrior with 10hp defense, he takes 10 points of his health (we'll improve this formula later). The warrior will have a reference to the rolling die instance. We'll always roll the die and add a particular random number to his attack/defense to make the game more unpredictable. Of course, each warrior could have their own rolling die, but I wanted this to be as close to a real board game as possible and show you how OOP simulates reality. The warriors will share a single rolling die instance, which will add an element of randomness to the game and make the game a bit more realistic. Last of all, we'll make the warriors send messages about what is happening in the fight. The message will look something like this: "Zalgoren attacks with a hit worth 25 hp." However, we'll put the message part off for now, we'll mainly focus on creating the warrior object. Now when we've got a good idea of what we want, let's get right into it! Let's add a Warrior class to the arena project and add fields to it accordingly: Warrior.h #ifndef __WARRIOR_H_ #define __WARRIOR_H_ #include <string> #include "RollingDie.h" using namespace std; class Warrior { public: float health; float max_health; float damage; float defense; RollingDie ¨ }; #endif We have deleted the constructor and destructor so far. Likewise, we must not forget to include RollingDie.h for the warrior. Methods Let's start off by creating a constructor for the fields. It won't be hard. We'll want to set all the fields the class has. Let's add declaration to the Warrior.h header file and initialize the fields in the implementation file: Warrior.cpp Warrior::Warrior(float health, float damage, float defense, RollingDie &die) : die(die) { this->health = health; this->max_health = health; this->damage = damage; this->defense = defense; } We assume that the warrior has a full health once he's created, so the constructor doesn't need a maxHealth parameter. It's easier to just set the maxHealth to whatever the starting health is. Next, notice the reference initialization. We pass the die by reference to be able to have only one die in the program. If the die wasn't a reference (or pointer), then each warrior would have its own die. As we said in the Reference lesson, we must initialize the reference when we create it. And as we know from previous lessons, that is before the constructor is called. That's why we need to use this syntax. In general, all fields should be initialized this way if it's possible. Therefore, we'll now modify the constructor: Warrior::Warrior(float health, float damage, float defense, RollingDie &die) : die(die), health(health), max_health(health), damage(damage), defense(defense) {} Now it's according to good practices. Let's move on to the methods. Apparently we're going to need some alive() method to see whether the warrior is still alive. Similarly, we're going to need the attack() method to attack another warrior. First, we'll look at the alive() method. We'll figure out whether the warrior has any health left. If he doesn't, then he's apparently dead. bool Warrior::alive() { if (this->health > 0) return true; else return false; } Due to the fact that the expression this->health > 0 is actually a logical value, we can return it and the code will become shorter: bool Warrior::alive() { return this->health > 0; } I often meet such an unnecessary condition very often even in code written be experienced programmers, that's why I'm pointing this out. The if- else construct in this case only says how unexperienced the programmer probably is. Now let's look at the attack() method. Based on the defense, die roll and attack, it calculates the damage as we described it at the beginning. void Warrior::attack(Warrior & second) { float defense_second = second.defense + second.die.roll(); float attack_first = this->damage + this->die.roll(); float injury = attack_first - defense_second; if (injury < 0) injury = 0; second.health -= injury; } The calculation should be easy. We'll calculate the defender's defense (including the number rolled on the die), then the attacker's damage (again including the rolled number) and subtract these values - we get the final injury. We must also reckon with a situation where the defense is higher than the damage - hence the condition (if it wasn't there, the defender's health would be increased). Finally, we subtract the damage from the defender's health and we're done. Visibility Now we have warriors who can fight each other. But what if one of the players wants to cheat and wants to take more health? If it was a programmer who used our warrior (for example, because it's included in some library), he could do that, because we allowed programmers to change the health freely. One of the fundamentals of OOP is encapsulation, i.e. to keep the fields for the class itself and to expose only the methods outside. We'll handle this by that magic public: part at the beginning of the class. Please edit your Warrior class as follows: Warrior.h class Warrior { private: float health; float max_health; float damage; float defense; RollingDie ¨ public: Warrior(float health, float damage, float defense, RollingDie &die); bool alive(); void attack(Warrior &second); }; Note the use of private: at the beginning of the class. All fields (and methods) following this construct will not be visible from the outside. For example, we won't be able to execute the following code after this change: Warrior me(100, 8, 4, &die); Warrior enemy(100, 8, 4, &die); me.health = 99999; // Haha, I'm almost immortal me.defense = 99999; // Haha, I'm invincible enemy.damage = 0; // Haha, you wouldn't hurt a fly enemy.health = 1; // Haha, you are weak The programmer won't have access to either of the fields because they are private. But perhaps someone might want to know how much health the warrior still has. We use getters and setters for this. These are methods starting with get or set, then the field name follows. In principle, these are fully-featured methods, returning or setting the value of a private field. It's only this naming convention which makes them getters and setters. For example, for health, these methods would look like this: Warrior.h class Warrior { private: float health; float max_health; float damage; float defense; RollingDie ¨ public: Warrior(float health, float damage, float defense, RollingDie &die); bool alive(); void attack(Warrior &second); float getHealth(); // getter void setHealth(float health); // setter }; Warrior.cpp float Warrior::getHealth() { return this->health; } void Warrior::setHealth(float health) { if (health < 0) // validation return; this->health = health; } Using the getHealth() method, we can now get the life of the warrior, even if the field is private. On the contrary, with the setter we can set the health. Note that it's not possible to set the health to less than 0 due to the condition in the setter. We don't want a setter for the health because the injury is handled by the attack() method, but I also wanted to show it to demonstrate how we can validate the input by it. If the field was publicly available, we won't have be able to ensure this validation process and someone could easily set a negative health. We can access fields and methods marked as public from outside. On the contrary, fields and methods marked as private are secured and we can be sure that the only one who sees them is us. We can access these methods and fields from other methods within the same class (including public ones) and through the this pointer. This is the encapsulation principle - to protect our own data from being changed. Fight Now we can make such a small fight. In main.cpp, we'll create two fighters and fight each other until one of them dies (we don't forget to include Warrior.h). int main() { RollingDie die; Warrior first(100, 8, 4, die); Warrior second(100, 8, 4, die); while (first.alive() && second.alive()) { first.attack(second); if (second.alive()) second.attack(first); } if (first.alive()) cout << "The first warrior won with " << first.getHealth() << " hp left" << endl; else cout << "The second warrior won with " << second.getHealth() << " hp left" << endl; cin.get(); return 0; } Console application The second warrior won with 22 hp left Conventions You've certainly noticed that methods and fields are written in a different style (such as letter case, spaces, etc.). In C++ (as opposed to Java or C#, for example), there are no rules on how to write code. The developers didn't even agree on how to write braces - whether after the method name (as Java does for example) or under the method name (as C# does). I personally follow the convention stated in the series, i.e. the field names and variables are in the snake-case notation: in lowercase and separated by underscores ( int my_variable, string player_name). I write methods in the camelCase notation ( myMethod(), roll()). Then constants in ALL_CAPS notation ( MAX_PLAYER_COUNT, LEVEL_COUNT). As for brackets, I use the Allman style (braces go under the method name), you can find different conventions on Wikipedia. In this, C++ is not unified and it's up to ebery programmer to choose his style. That would be all for today's lesson. In the project, we have modified visibility for other classes and added getters and setters. If you want to be sure that we are working with the same code, please download the source code below the article. We'll continue with it in the next lesson. And what's next? In the, Arena with warriors in C++, lesson, we'll write some basic arena functionality to make the program finally do something. Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily. DownloadBy downloading the following file, you agree to the license terms Downloaded 1x (1003.99 kB) Application includes source codes in language C++ No one has commented yet - be the first!
https://www.ictdemy.com/cplusplus/oop/arena-warrior-encapsulation
CC-MAIN-2021-25
refinedweb
1,887
72.97
Hi We are using USB barcode scanner to scan material barcode labels. These lables are from our vendors. We does not have control over the label generation. We are using USB barcode scanner for scanning purpose. We want to capture USB barcode scanner output. Normally the scanner returns output in the place holder in which the cursor present. But we do not put writable text box for the cursor. Instead of write allowable text box we want to put locked or readonly text box in the screen and want to capture scanner value. How can we do? Assume that our barcode scanner does not support serial ports. Regards S. Muhilan View Complete Post I Dear All, I'm creating simple web service that will accept some parameters (such as customer name and file name) and return content of an xml file as a string and WS client will save it on his side. I'm using custom binding with binaryMessageEncoding and httpTransport. The question is if it is possible to have these input parameters as well as returned xml content binary encoded somehow? Thanks in advance for your help! I have a user table with userID, userName ...the standards.I also have a "Material" table with materialID, materialName, etc. I combine these in another table "UsersMaterial" with userID and materialID, depending on which materials the user has chosen (between 0 and 5). Now I need a stored procedure that returns the user information + the set of materials that is mapped to the user. But I can't see how I can return one row of user information combined with a set of the user materials? Do I join or can I return a set + one row? Thanks in advance! Niklas I am using the MsiEnumRelatedProducts function and according to all the articles I should be getting text return values such as: But I am only getting numbers returned from the function. I assume I need to use some Enum but I cannot find any example anywhere. I have looked at this article: But there is no explanation of how to actually get those text return values back? I have been reading that a value needs to be returned by a function, otherwise the following error will occur: "Function <function name> doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used." The cure, I have found, is to return something (i.e. "Return 0") before exiting the function. Can someone please enlighten me as to why this might be useful? Can I pass this return value back to the routine that called the function? If so, how do I code this? Most of the time, however, I find I'm not needing to return a value anyway, and just end up adding "0" to the ends of all my Return statements. Does anyone have any comments on this? Links referred to: Thanks! i'm trying to check if the text fields are blank i attached the code below, if i leave both textbox blank, both alerts pop up but confirm how to make it like if the first textbox is blank, alert pop up then exit everything? function Validation(){ if (IsValid()) { if (!(confirm("Are you sure you want to save this record?"))) { return false; }return true; } function IsValid() { if (!isDate(document.getElementById('txtTest'))) { alert("Please insert a Date"); return false; } if (!isBlank(document.getElementById('txtTest2'))) {alert("Please insert a Holiday Name "); return false; } return true; } asp:button onclientclick="return Validation()" hi all, i need your assistance please. select Comments.Id,SuroundId,ArticleId,PosterId,PostRime,Subject,Body,Visible,Users.Username from dbo.Comments inner join Users on Comments.PosterId=Users.Id where SuroundId=@suround and ArticleId=@articleId for some reason it doesnt return any values. before i've added the inner join it worked perfectly. i couldn't find my mistake, though i passed over it several times. thanks. I have the following stored procedure ALTER PROCEDURE dbo.GetProvMoveModifier ( @prov_id int ) AS DECLARE @mod float SELECT @mod = PROV_TYPES.MOVE_MOD FROM PROV_DETAILS INNER JOIN PROV_TYPES ON PROV_DETAILS.TYPE_ID = PROV_TYPES.TYPE_ID WHERE (PROV_DETAILS.PROV_ID = @prov_id) RETURN @mod MOVE_MOD is defined as a float. Yet within Dataclasses.designer.cs the function gets added as: [Function(Name="dbo.GetProvMoveModifier")] public int GetProvMoveModifier([Parameter(DbType="Int")] System.Nullable<int> prov_id) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), prov_id); return ((int)(result.ReturnValue)); } Naturally this is causing some issues as my C# code needs to handle decimal values. If I try to manually change the designer code to use floats, I get the following error 'System.Single' is not a valid return type for a mapped stored procedure method. Any thoughts? I could setup a work-around, but I would think I could return a decimal value from a stored procedure.
http://www.dotnetspark.com/links/33470-capturing-usb-barcode-scanner-return-values.aspx
CC-MAIN-2017-13
refinedweb
807
58.58
CoverStory LANGUAGES: ALL ASP.NET VERSIONS: 2.0 What s New in Windows Forms 2.0: Part I Improved Productivity By Wei-Meng Lee With the release of Microsoft Visual Studio 2005, a lot of media attention has been focused on the new and improved ASP.NET 2.0. However, a lot of improvements have also been made on the other side of the fence; in this case, Windows Forms 2.0. In this two-part article, I ll walk you through some of the new and cool features in Windows Forms 2.0 and how you can take advantage of them in your next application. Snaplines One significant improvement in the Windows Designer is the support for Snaplines. When you position a control on a Windows form, lines known as Snaplines will be shown to help you position the control in the correct place on the form. Figure 1 shows two lines in blue showing you the recommended distance to position the Button control from the edges of the window. Figure 1: Snaplines showing the recommended distance from the edges of the window. Snaplines also help you align multiple controls. Figure 2 shows how two controls can be aligned either based on the lower edge of the control or based on the text contained within the control. Figure 2: Aligning controls using Snaplines. Data-binding Data-binding is another area which is much improved in Windows Forms 2.0. To see the new data-binding feature in action, I will walk you through a simple example. For this example, let s create a Windows application using Visual Studio 2005 and name it WindowsForms2.0. To use data-binding, first add a data source to the project by going to Data | Add New Data Sources. In the Choose a Data Source Type dialog box (see Figure 3), select Database and click Next. Note that you can also data-bind to a Web service or business object. Figure 3: Selecting a data source. In the Choose Your Data Connection dialog box, click the New Connection button (see Figure 4) to establish a connection to the database you want to use. Figure 4: Establishing a new data connection. Enter the name of the database server (I will use the default-installed SQL Server 2005 Express database that comes with Visual Studio 2005) and select the Northwind database (see Figure 5). Click OK. Figure 5: Selecting the database and table. Unlike SQL Server 2000, SQL Server 2005 Express and SQL Server 2005 do not come with the default sample databases. If you would like to install the sample databases on these servers, you can download them from. When back in the Choose Your Data Connection dialog box, click Next. You will be prompted to save the connection string of the database into the application configuration file (see Figure 6). Click Next. Figure 6: Saving the connection string into the application configuration file. In the Choose Your Database Objects dialog box, expand the Employees table and check the fields shown in Figure 7. Click Finish. Figure 7: Selecting the fields and tables to use. You can now view the newly added data source by going to Data | Show Data Sources (see Figure 8). Figure 8: Viewing the newly added data source. If you have upgraded from a previous version of Visual Studio 2005 (such as Visual Studio 2005 Beta 2, or one of the various CTP releases), you may encounter the situation where the Data Sources window is empty after adding a new data source. To resolve this known issue, check out the following link:. If you click on the drop-down button on the Employees table, you ll see that it is bound to the DataGridView control. This means that when you drag the employees table onto a Windows form, a DataGridView control will be added to the form to display the content of the Employees table. For now, let s change the binding to Details (see Figure 9). Also, change the EmployeeID field to a Label control (since this field should not be modifiable) and the Photo field to a PictureBox control (to display the image of the employee). Figure 9: Changing the default binding of the table and its fields. Drag and drop the Employees table from the Data Sources window onto a Windows form. Figure 10 shows what the form looks like after the operation. Also notice that there are four new controls added to the form. These controls perform the necessary data-binding between the database and the controls on the form. Figure 10: Dragging and dropping the data source onto a form. For the PictureBox control, set the SizeMode property to AutoSize so that the control can automatically resize according to the image. Press F5 to test the application. You will now be able to navigate between the records in the table by clicking on the navigational bar located at the top of the window (see Figure 11). Figure 11: Testing the application. You can also make changes to the records by directly modifying them in the text boxes. To save the changes, click the Save icon (represented by the diskette icon). To add a new record, click on the + button, then the Save button. To delete a record, click the x button, then the Save button. Notice that we have not written a single line of code and all this is done automatically for us. Amazing! Application Settings The new Application Settings feature in Windows Forms 2.0 makes it a breeze for developers to persist personalized information for each user, as well as information for the application. Using the Application Settings feature, you can save the state for an application without needing to write the plumbing code to save and read the information from disk. As an example, let s use the Application Settings feature on our previous project to save the last record that is shown on the form so that the next time the application is loaded, the last record is shown. To do so, let s add an application setting to the project. Right-click on the project name in Solution Explorer and select Properties. On the Settings tab, add a new setting and name it CurrentRecord (see Figure 12). Set its data type to Integer and use the scope of User. Save the project. Figure 12: Adding a new application setting to the project. Notice that there already exists a setting called NorthwindConnection. This setting was created earlier when you added a new data source. There are two scopes for application settings: - Application. An application-scope application setting is specific to the entire application. This scope is useful for information specific to the application, such as a database connection string, Web services settings, etc. - User. A user-scope application setting is specific to individual users. This scope is useful for persisting user-specific information, such as the size of the form, preference settings, etc. For our sample application, we will save the position of the current record when the form is closed. To do so, code the FormClosing event of the form, as follows: Private Sub Form1_FormClosing( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.FormClosingEventArgs) _ Handles Me.FormClosing My.Settings.CurrentRecord = EmployeesBindingSource.Position End Sub Notice that the CurrentRecord application setting you created can be accessed directly from the My.Settings namespace (if you don t see the CurrentRecord setting appearing under My.Settings in IntelliSense, then you most probably have not saved the project yet). When the application is loaded again, we will restore the position of the record by retrieving the value from the application setting:) EmployeesBindingSource.Position = My.Settings.CurrentRecord End Sub By default, when you assign a value to an application setting, it is saved automatically when the application is shut down. This can be verified by viewing the Application tab in the project properties window (see Figure 13). Figure 13: Automatically saving My.Settings on application shut down. If the Save My.Settings on Shutdown checkbox is unchecked, you can explicitly save the application settings by calling the Save method: My.Settings.Save() But where are the values of the application settings stored? For user-scope application settings, the values are stored in the user.config file (see Figure 14) located in directories deeply nested within the C:\Documents and Settings\Wei-Meng Lee\Local Settings\Application Data\ folder. For application-scope application settings, they are stored in the app.config file usually deployed together with the application..ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> Figure 14: The contents of the user.config file for our application. Application Events One very useful new feature in Windows Forms 2.0 is the application events handlers. To view all the application events, click the View Application Events button on the Application tab (see Figure 15). Figure 15: Viewing the application events. The ApplicationEvents.vb file contains the code for servicing the various events in the application. The following events are supported: - NetworkAvailabilityChanged. Occurs when the availability of the network changes. - Shutdown. Occurs when the application shuts down. - Startup. Occurs when the application starts. - StartupNextInstance. Occurs when attempting to start a single-instance application and the application is already active. - UnhandledException. Occurs when an exception is not caught by an event handler. You can add the event to service by selecting the events from the drop-down list located at the top of the window (see Figure 16). As an example, if you want to ensure that only one instance of your application can run at any one time, select the StartupNextInstance event. Figure 16: Setting the application events to service. Also check the Make single instance application checkbox, as shown in Figure 15. This will ensure that when another instance of the application is executed, the StartupNextInstance event will be fired. This event is useful for cases where you want to allow a single instance of your application to run on a client s machine. Code the StartupNextInstance event handler as follows: Private Sub MyApplication_StartupNextInstance( _ ByVal sender As Object, _ ByVal e As Microsoft.VisualBasic.ApplicationServices. _ StartupNextInstanceEventArgs) Handles Me.StartupNextInstance MsgBox("Another instance of the application is " & _ " already running. Application will now exit.") End Sub When you try to run more than one instance of the application, the message box shown in Figure 17 will appear. Figure 17: Displaying the error message when trying to start another instance of an application. Conclusion In this article, you have seen some of the new productivity features of Windows Forms 2.0. In particular, you have seen how the visual designer uses Snaplines to help you position your controls. You have also learned how to use the data-binding capabilities of Windows Forms 2.0 to display records on your form without writing a single line of code. Last but not least, the Application Settings feature allows you to persist application state easily by providing all the plumbing code needed. As you can see, all these new features save you lots of effort in writing code usually required for mundane tasks, freeing you to spend more time to add features to your application. In Part II we ll look at the new deployment technology known as ClickOnce, as well as discuss a new feature known as RegFree COM and how it can be used together with ClickOnce to simplify your deployment tasks. We ll wrap things up with a look at some new and improved Windows controls and how you can use them to create professional Office-like applications. Wei-Meng Lee () is a technologist and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies, including ASP.NET 2.0: A Developer s Notebook and Visual Basic 2005 Jumpstart (both from O Reilly Media, Inc.).
http://www.itprotoday.com/microsoft-visual-studio/what-s-new-windows-forms-20-part-i
CC-MAIN-2018-13
refinedweb
2,009
56.15
You can subscribe to this list here. Showing 1 results of 1 Hi all, I have a simple script which uses Mark Hammond's win32 utils to build a simple Windows service. When I run it as a python script, all goes well: python MyService.py install python MyService.py start The service starts and in the the Windows services list, I see it is pointing off to the default PythonService.exe. Next, I tried to use py2exe to compile it as an executable and have that be the service. The compilation looks good and there are no errors in the log file. This: MyService.exe install works like a charm. In the Windows service list, it now points to MyService.exe. However, when I try to do this: MyService.exe start Windows complains that the service did not respond in a timely manner and sure enough, it doesn't start. What am I doing wrong here? Here's the code for the service. I'm using py2exe 0.6.6 and python 2.5. from ctypes import * import time import win32api import win32serviceutil, win32service, win32event import pywintypes class MyService(win32serviceutil.ServiceFramework): _svc_name_ = "test" _svc_display_name_ = "test service" _svc_description_ = "Just some test service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.overlapped = pywintypes.OVERLAPPED() self.overlapped.hEvent = CreateEvent(None,0,0,None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): started = True while True: self.run() stopsignal = win32event.WaitForSingleObject( self.hWaitStop, 1*1000) if stopsignal == win32event.WAIT_OBJECT_0: break def run(self): #This is where I would actually do stuff.... return True if __name__=='__main__': win32serviceutil.HandleCommandLine(MyService) Thanks in advance for your help. Cheers, Jason
http://sourceforge.net/p/py2exe/mailman/py2exe-users/?viewmonth=200711&viewday=11
CC-MAIN-2015-27
refinedweb
290
53.58
this file which give me JSON output from mysql database: <?php require 'core/init.php'; $general->logged_out_protect(); $username = htmlentities($user['username']); $user_id = htmlentities($user['id']); try { $result = $db->prepare('SELECT I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree. For example, given this JSON tree { "files": { "folder": { "file1": { "prope As the title describes, I am trying to find out if I can instantiate a new mongoose model and schema with the JSON of a existing MongoDB document? It seems like I could do it as long as I have retrieve the document before Mongoose runs. Is this possi I've been thinking in how to do this. I've read trough the OKHTTP documentation, I have an idea on how to handle this but I'm not entirely sure. I'll have the user submit three fields ( Username, Password, Database ). I'll have a PHP file uploaded to I have used Laravel Response::json to generate a JSON response. return Response::json(array('subjects' => $subjects, 'year' => $year, 'sem' => $sem)); When I run the request, I get a valid JSON (tested in JSONLint) as a response. But the followin'm using the following code to post a json object to php server : Map<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("tag", "jsonParams"); JSONObject jsonObject = new JSONObject(paramsMap); Log.d( I am designing a custom Appender(How to create a own Appender in log4j?) in Log4j to meet my requirement. The log files on which I have to do some operation is of the form {JSONObject} {JSONObject} ........... ........... {JSONObject} Each JSON Objec This is my JSON response: { MyResult: { Apple=[ "iPhone 4S", "iPhone 6" ];Microsoft=[ "Lumia 535", "Lumia 640" ];Samsung=[ "Galaxy A3", "Galaxy A5", "Galaxy A7" ]; } } I would like to d I'm trying to understand the best way to set up a class in .NET 3.5. I have a JSON object that's a collection of Order Shipments defined as something like this: [ { "BaseOrder": { "order_id": "503", "BillingAddress" I have json array named JsonTempArray. And I have mappingId and Name as two fields. When clicking Male or Female It automatically creates 5 mappingids(1 to 5) and Name field is Empty. Like :- JsonTempArray[length]= { mappingid: Number,//Number has 1 I have three classes corresponding to three tables in mysql database. My classes are as follows. @Entity @Table(name="location") public class Location { private Integer locationId; private Integer hospitalId; private Integer regionId; private St With below code i got all uploaded images with DropZone,but i now i have a simple problem, it already showing Orginal images as thumbnail but i need to show thumbnail with base64 same as dropzone made when want to upload new image. dropzone.js init: i am getting DOB from json var date=data.dob; by using this ` var today = new Date(86400000); var date=data.dob; var timeDiff = Math.abs(today - date); rangeOneMin1 = parseInt(timeDiff); var age1 = Math.ceil(rangeOneMin1 / (1000 * 3600 * 24)) / 365; I am trying to send multiple images to server but,so I am storing all the images in one arraylist,but after that when I need to send to server,it shows error near line ,,...................... conn.setRequestProperty("image", multimgss); error T I've been working on an app to utilize google's YouTube API. I had this app fully functioning in Objective-C, but I've ran into some problems in Swift. This is what is looks like in Objective-C, -(void) retrieveData { AFHTTPRequestOperationManager *m I am trying to deserialize a json string which contains interfaces and hashmaps which has interface type and lists containing interface type into a java object using Gson. But I am getting java.lang.RuntimeException: Unable to invoke no-args construc In my project, I am fetching rows of data from the database and using json_encode to transform the data to JSON. I am echoing the JSON and so far it is displaying the correct result. Here is a sample: {"results":[{"id":"1",&q I've looked for a couple hours now, hoping not to duplicate a question, and I just can't find what I'm looking for. I am working on passing a complex object back from a form to a controller, and having it parse everything out. The problem I get is th
http://www.dskims.com/tag/json/
CC-MAIN-2018-22
refinedweb
727
61.77
Valdis.Kletnieks@vt.edu wrote:> On Wed, 08 Nov 2006 16:15:46 CST, Corey Minyard said:> >> Ouch, I guess we've never had a system with these address types. Thanks.>> >> If we never had a system with these address types..>> >>> static unsigned char intf_mem_inw(struct si_sm_io *io, unsigned int offset)>>> {>>> return (readw((io->addr)+(offset * io->regspacing)) >> io->regshift)>>> - && 0xff;>>> + & 0xff;>>> }>>> >> Is this dead code that isn't called by anybody?> Well, not exactly. The SMBIOS or ACPI tables that report these interfaceshave various options for the size of the device registers. The driverimplements all the options, but there may or may not be systems withevery option available. But I can't exactly guess what is available in thefield.-Corey-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2006/11/9/92
CC-MAIN-2015-32
refinedweb
149
56.96
Buttonclass, but because Buttonis implemented through platform-dependent GUI components, you can't draw into a button and expect your image to display properly, if at all. Before you start cursing the AWT (yet again), let me assure you that a solution exists. The most straightforward approach and the technique we'll be examining in this article involves subclasssing the AWT's Canvas class. Although the primary purpose of the Canvas class is drawing (perfect for our purposes), it doesn't provide the mouse handling or any of the typical button-press effects (let alone mouse-over effects) you would expect for a button. We'll address these limitations by working with several classes I've created to support fully flexible, active image buttons. ImageButton.java) works within the Java environment, we should subclass it from an existing AWT component. The AWT contains two candidates -- Canvasand Panel-- that support drawing. Although we could use either class, Panelhas additional capabilities that we don't need, so we'll go with Canvas. Here is the class declaration: public class ImageButton extends Canvas { When the user is not interacting with the button in any way, the button is in its UNARMED state. To follow suit with many applications, such as Internet Explorer and the new Netscape Navigator 4.0 pre-release, we're going to implement an OVER state, which will highlight a button as the user moves the mouse over it. The ARMED state, which we'll represent by showing a depressed button, occurs when the user clicks and holds on a button. If the user releases the mouse while the button is in the ARMED state, the corresponding action will be performed; however, users can return to the UNARMED state by moving the mouse off of the button without releasing the mouse. The last state we'll be supporting is DISABLED, which is implemented through the ImageButton programming interface by calling the AWT disabled function. A disabled button should not respond to any user action. We'll be using a grayed-out effect to indicate a disabled button. Our image button will support only one state at a time (a button can't very well be ARMED and UNARMED at the same time now, can it?). We'll represent the four states in a single int, with four constants, as shown here: public static final int UNARMED = 0; public static final int ARMED = 1; public static final int OVER = 2; public static final int DISABLED = 3; private int buttonState = UNARMED; Canvascomponent is completely blank by default, and it doesn't provide any built-in support for drawing a border around the rectangular region it encompasses. We will have to draw the borders ourselves, so our next step is to decide what type of borders we want and which states they will correspond with. By implementing the border features in a separate class (we'll call this class Border), we can use one or more instances of the class in our ImageButton and switch between them as the states change. Currently, the most popular kind of border is the shaded 3D-style border. We can actually use this border style for two of our button states: To indicate a button is unarmed, we'll use this style with darker bottom and right edges and lighter top and left edges; to indicate a button is armed (depressed) we'll use this style with darker top and left edges and lighter bottom and right edges. I have implemented a very configurable class (Border.java) that supports multiple border styles, including NONE, THREED_OUT, and THREED_IN, among others. Two of Border's methods -- getInsets() and paint() -- do the bulk of the work. The getInsets() method returns the number of pixels at the top, left, bottom, and right that are necessary to make space for the border. (Note that the border is not required to be symmetrical.) The getInsets() method is used both to determine the size of the image button and to calculate the appropriate location at which to draw the button's image. As shown in the following snippet, getInsets() takes into account the border thickness and variable margins at each edge: public Insets getInsets() { int top = borderThickness + topMargin; int left = borderThickness + leftMargin; int bottom = borderThickness + bottomMargin; int right = borderThickness + rightMargin; return new Insets( top, left, bottom, right ); } The Border paint() method, which is similar to the AWT Component paint() method, takes a Graphics parameter as input and draws the border in its current configuration. Border does not maintain the x-y coordinates or size of the image button, so these are passed to paint(). Also, the border color, if not set explicitly, can be derived from the button's current background color, another parameter to paint(). (This approach is desirable for borders like the 3D borders that should be given brighter and darker colors relative to the current background color.) Here is the function declaration for paint(): public void paint( Graphics g, Color background, int x, int y, int width, int height ); Back in the ImageButton class, a button needs to maintain variables for, potentially, four different borders and four different images for each of the four button states. Since we already defined the states as integers 0 through 3, we can use these values as indexes into the following arrays: main()function also uses the DummyAppletContextclass to enable the applet to be tested and run as a standalone application. I described the DummyAppletContextclass in detail in my article in the January 1997 issue of JavaWorld Free Download - 5 Minute Product Review. When slow equals Off: Manage the complexity of Web applications - Symphoniq Free Download - 5 Minute Product Review. Realize the benefits of real user monitoring in less than an hour. - Symphoniq
http://www.javaworld.com/javaworld/jw-03-1997/jw-03-imagebutton.html
crawl-001
refinedweb
958
54.56
you're several versions back. *ADVISEMENT* -- autopat is NOT the preferred patching tool. however in this particular case a 'design feature' in patch/ix makes updating ftp a bloody pain. normally, you DO want to use patch/ix! so...to start at the beginning... connecting to the itrc and doing a 7.5 patch search for ftp, you'll see that this...{ mpeix:c.75.00,}&BC=main|search| ....is the current release of ftp. (a quick read of the fixes indicates that (oh!) there is a repair for connecting with linux systems (well how about that)) the next thing to do is get a copy of the patch installation guide: UsageGuide&BC=main|search| - make sure you get an up-to-date copy of unpackp. if you haven't patched in a while (years) -- it's very worthwile. - for ftp you'll be using autopat, not patch/ix. HOWEVER, it's still a *good idea* to make sure patch/ix is up-to-date too. you can get patch/ix here: DownloadPatchixHelp ----------------------- as alfredo says -- read your directions like a love letter (eg, carefully, thoroughly and repeatedly). patching on mpe is relatively easy but if you're unfamiliar with the process the installation guide is invaluable. (did I mention it's a really good idea to have local *copies* (plural) of these instructions?) ------------------------ so jumping forward in time a bit.... you've made a quick backup of @.arpa.sys... (ftp is NOT in use, right??) ....and unpackp, patch/ix and your bright shiny ftp patch are all on your system. log on as MANAGER.SYS,INSTALL. you need to unpackage your patch according to the patching tool you're going to use. since you're going to use autopat. use the following command: :UNPACKP MPEIX01A, AUTOPAT upon completion, UNPACKP will place all component patch files in the proper group and account. AUTOPAT places files in the PATCHXL.TELESUP group and account. (do a listfile for warm fuzzies) since being logged on into the INSTALL group is unusual, it's a good idea to do a normal manager.sys log on now. start the patch installation process by entering the following: :XEQ AUTOPAT.PATCHXL.TELESUP AUTOPAT builds a workgroup, PATCHXL.SYS, and does most of its work from there. there's an outside chance that the group PATCHXL.SYS already exists and autopat will be quite unhappy about that. being the mild-mannered script (did I mention autopat was a script?) that it is, it polite tells you exactly what to do -- PURGEGROUP PATCHXL.SYS (copy-n-paste is wonderful ;-). You will prompted to enter your name and the passwords for MANAGER.SYS. The system will turn the terminal's echo off, so the passwords will not appear as you type them in. You will be prompted as follows: (AUTOPAT) (your reply) --------- ------------ Your name: < > Account password for MANAGER.SYS: < > User password for MANAGER.SYS: < > Repeat passwords for confirmation; Account password for MANAGER.SYS: < > User password for MANAGER.SYS: < > next AUTOPAT will prompt you to enter the patch ID(s) for the patch(es) you will install. for 7.5, the (latest) patch id is: FTPHDJ5A. since autopat can apply several patches at once it will prompt for another patch id. use // to terminate the prompting loop. autopat will construct a patch installation job then it will then prompt you to "STREAM PATINSTL.PATCHXL"....which you do...and let the job run. since this is ftp that you're patching all that needs to be done is to stream this job. there will be no tape to create, no cslt creation and no update from (cslt) tape. clean and simple. now when you run -- you should see an update version number. - d --- Donna Hofmeister Allegro Consultants, Inc. 408-252-2330 > -----Original Message----- > From: HP-3000 Systems Discussion [mailto:HP3000-L@RAVEN.UTC.EDU] On > Behalf Of James B. Byrne > Sent: Friday, September 26, 2008 8:56 AM > To: HP3000-L@RAVEN.UTC.EDU > Subject: Re: [HP3000-L] MPE FTP transfer into HFS namespace > > On: Thu, 25 Sep 2008 17:11:41 -0700, donna hofmeister > wrote: > > > > > I don't think anyone asked....what version of ftp are you (james) > running. > > the standard answer is always update to the latest version. ftp is > (way) > > easy to update. use autopat...no tape or reboot needed. > > Version info: > > :ftp > File Transfer Protocol [A0012E07] (C) Hewlett-Packard Co. 2002 [PASSIVE > SUPPORT] > ftp> > > Thanks for all of the suggestions. I regret the delay in replying to > some > of them, but as I am a digest subscriber I did not see all of them > until > this morning. > > There are a few points about my situation. > > 1. We are not on HP support and have not been since shortly after the > 2001 > announcement of the HP3000 end of life. > > 2. The current OS on the system is: > RELEASE: C.75.00 MPE/iX HP31900 C.45.05 USER VERSION: C.75.00 > > 3. It has probably been 8 years since I last used autopat, or autopatch > or > whatever it was called, and my recollections of it do not extend beyond > the "Oh yeah... I recall something like that" level of detail. > > I googled for info on this utility/script and I searched my system but > I > came up empty on any meaningful references. > > So, what I now need are detailed answers to two questions: > > 1. May I update my HP3000 ftp client without having to contract for > services from HP? > > 2. If so, then exactly what steps do I follow? A recipe is what I > need. > > Regards, > > -- > *
http://fixunix.com/hewlett-packard/538611-re-mpe-ftp-transfer-into-hfs-namespace.html
CC-MAIN-2015-22
refinedweb
928
77.33
How to connect Qt with postgreSQL? Hi, how do i Fix the problem of "QSqlDatabase: QPSQL driver not loaded QSqlDatabase: available drivers: QSQLITE "Driver not loaded Driver not loaded" its really getting weird for me to solve this please help and save me. My code is as follows #include "mainwindow.h" #include <QApplication> #include <QSqlDatabase> #include <QDebug> #include "QSqlError" int main(int argc, char *argv[]) { QApplication a(argc, argv); QSqlDatabase db=QSqlDatabase::addDatabase("QPSQL"); db.setHostName("localhost"); db.setDatabaseName("conf"); db.setPassword("cdt321"); db.setUserName("postgres"); if(db.open()) { qDebug() <<"opened" ; db.close(); } else { qDebug() << db.lastError().text(); exit(1); } MainWindow w; w.show(); return a.exec(); } Thank you in advance.. Hi and welcome to devnet, you have to check 2 things: - The plugin database driver must be built; - the postgres client library must be in the PATH you can find some information here. I think you can avoid the necessity of the Qt plugin database driver by using Postgres libs directly with something like that in your .profile: win32:INCLUDEPATH += "C:/PostgreSQL/9.4/include" unix:INCLUDEPATH += /usr/include/postgresql win32:LIBS += "C:/PostgreSQL/9.4/lib/libpq.lib" unix:LIBS += -L/usr/lib -lpq Of course, your Qt compiler and the compiler, which the Postgres libpq was built with, should be the same. This is not the level of abstraction you achieve with QPSQL driver but I guess you get less overhead by simply writing a C++ Wrapper for libpq C. Thank you for replying, I am sorry, i am the beginner to Qt so will you please help me with the steps. Thank you. @mcosta , i tried running those commands in terminal but the response was..as follows root@rcdtcpu24:/# cd $QTDIR/src/plugins/sqldrivers/psql bash: cd: /src/plugins/sqldrivers/psql: No such file or directory root@rcdtcpu24:/# qmake "INCLUDEPATH+=/usr/include/pgsql" "LIBS+=-L/usr/lib -lpq" psql.pro Cannot find file: psql.pro. root@rcdtcpu24:/# make make: *** No targets specified and no makefile found. Stop. Please do help with the steps.... - jsulm Moderators You should read the output more carefully: bash: cd: /src/plugins/sqldrivers/psql: No such file or directory That means there is no /src/plugins/sqldrivers/psql directory. QTDIR is not set. Just use the whole path to Qt sources directly. @vIJI So you seem to be on Linux? If you have an installation of Postgres on your machine, then you have to find out where Postgres include and lib directories are. The include these paths into your Qt project file (yourproject.pro). Nope its not working...... i have added them, the location was just "/usr".... unix:INCLUDEPATH += /usr/include/ in .pro file but im unfortunate to get it success.. can you tell me how to build it step by step please if you dont mind... thank you. You are right about the code connecting to the DB. But it is not true that you have to use QSql* in order to connect to the DB. Postgres has C API for this purpose which one can easily write a C++ wrapper for. So my advice was: if Qt way is too abstract, do it with a C++ wrapper of Postgres C API. @sirop, You're right: you don't have to use Qt to connect to the DB but the topic of the thread is How to connect Qt with PostgreSQL so probably the author wants to understand how to do it. - SGaist Lifetime Qt Champion Hi, @vIJI First thing to check: How did you install Qt ? Are you using the Online Installer ? Your distribution's package manager ? If the former: did you install the Qt sources ? You can make that through the installer. If the later, what distribution is it ? Most of them provide all database drivers.
https://forum.qt.io/topic/61595/how-to-connect-qt-with-postgresql/7
CC-MAIN-2018-47
refinedweb
627
67.15
I want to know how to modify the default addition property of a class. For example, if I were to create a class Complex, then the addition goes by adding the real components and the imaginary components. Suppose I have two complex numbers z1 and z2. I'd like it such that whenever I put: function (z1+z2) (here function is anything cout, return, parameter...). Then it would automatically use this addition rule, defined perhaps in the class. I know a little Python, and it's very easy there, you just have to put: def __add__(x,y): (the general way, not specifically this case) return x + y def __mult__(x,y): return x*y I wonder how to do this in C++.
http://cboard.cprogramming.com/cplusplus-programming/84727-modifying-default-algebra-functions.html
CC-MAIN-2016-07
refinedweb
123
60.45
I have a class called HttpSvc which implements one of our interfaces called IHttpSvc. The code goes a little like this public class HttpSvc: IHttpSvc { private readonly HttpClient _serviceClient; // constructor which will get Base Address from the appSettings.json file public HttpSvc(IConfiguration config) { _serviceClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }); _serviceClient.BaseAddress = new Uri(config.GetSection("AppSettings:Urls")["ServiceClient"]); } public HttpClient GetServiceClient() { return _serviceClient; } public IList<HttpClient> GetHttpClients() { return new List<HttpClient>() { _serviceClient; } } } That's the class I'm trying to Mock or at least have some way of faking it so that it doesn't make any real calls to another web service that I have. I read that HttpClient does not inherit from any interface, so I am stuck on that part and on what I should do from there. Any tips?
https://www.dreamincode.net/forums/topic/414477-unit-test-httpclienthttpclienthandler/
CC-MAIN-2019-51
refinedweb
135
50.97
Thomas DeWeese <Thomas.DeWeese@Kodak.com> writes: > Hi Ari, > > So the answer to your question is, I don't know. > The real question is how much would be broken if the > code started to "trust" the code calling the ContentHandler? :) Yes. You trust it for local names, why not for qnames? > I think I already identified one case where it wouldn't > work properly (a 'raw' SVG file with no namespace decls > or DTD specified). This is I think an important case. The only case where that would be appropriate is where no namespace attributes have been defined on the outermost <svg> or any of its ancestors. If an unprefixed svg element appears inside, say, a <xhtml:p>, and there is no default namespace declared, the <svg> cannot be interpreted as an element from the SVG namespace, it is an element in a null namespace. (If the default namespace /is/ declared and is not SVG, it certainly cannot be an SVG element) Right now, it interprets any non-prefixed elements whose names match SVG elements as svg, regardless of the declared default namespace. The following is /not/ an SVG document no matter how you look at it, but I get a pretty picture out of the transcoder. <svg xmlns="non-svg" width="20" height="30"> <circle r="10" style="stroke:black; fill:none"/> </svg> I can see how this can be helpful for users who can't figure namespaces out (it's harder than it should have been, I know), but this is in violation of the Namespaces Rec (and it can't claim that it's pre-namespaces, because it interprets prefixed elements according to the Rec) > If the code can be constructed such that it handles this > case and still properly respect the ContentHandler interface > (which admittedly it is currently not doing a good job of) > then that would be great. Even if there is no DTD specified in a document, if the application interprets it as an SVG document, it is in effect associating the SVG DTD with the document. There is nothing that prevents it in this case from defaulting attributes from the SVG DTD, which include default vaules for xmlns and xmlns:xlink. That's OK, because SAX parsers are not supposed to report defaulted attributes, only ones actually found in the document. > I suppose one option is to keep the code mostly the > same except have it use start/endPrefixMapping to update > the namespace hash it maintains rather than parsing the > attributes it's self (then it can still 'stuff' the > namespace has with a default namespace). That was the second approach I was talking about. There shouldn't need to be any changes to the factory's heuristics (unless you want to make it compliant with the namespaces rec). The only change would be that it will respect startPrefixMapping() as much as it respects raw xmlns attributes. A SAX parser reports startPrefixMapping for every xmlns attribute it finds before it reports startElement for the element on which the xmlns attribute was found. It saves the ContentHandler looping twice through the attributes, first to update the map of currently declared namespaces then to interpret the attributes according to this updated context. startPrefixMapping is a direct replacement for manual namespace attribute parsing. To have the factory take advantage of this facility in the parser, you only need to override startPrefixMapping in the factory to call the same code that is called when it finds xmlns attributes. > Part of the issue is that I really trust the guys > who wrote this code to know the DOM so I am loath > to muck with it too much. Any idea if SAX impls > tend to 'mess up' start/endPrefixMapping? Not to my knowledge, but I can ask people who know better. Can the guys who wrote the code shed some light on it? Ari. -- Elections only count as free and trials as fair if you can lose money betting on the outcome. --------------------------------------------------------------------- To unsubscribe, e-mail: batik-users-unsubscribe@xml.apache.org For additional commands, e-mail: batik-users-help@xml.apache.org
http://mail-archives.apache.org/mod_mbox/xmlgraphics-batik-users/200403.mbox/%3C861xodc6n1.fsf@fdra.lib.aero%3E
CC-MAIN-2016-30
refinedweb
685
65.76
I've been doing web development in python, now, for five years, since I wrote my first python cgi script running out of CGIHTTPServer.py, and have loved it ever since. This article describes what technology I am using today, and wish I had found, or that it had been available, then: mod_python, sqlobject, formencode, htmltmpl and PIL. Python has come on drastically in five years: in 2001 i met someone who was excited to hear that i had been working for six months to produce a 25,000 line project: at the time, aside from Zope, that was the biggest they'd ever heard of. By contrast: some time last year, I heard of a company doing an ERP project with a MILLION lines of python under their belt. I started out with the usual: cgi-script programming. After two months, i had already got fed up with cut/paste of the hand-coded python/SQL programming and written a template-generator (pysqlgen) and some helper-functions to construct SQL (pysqldb); had written pyxsqmsll2000 (MS-SQL 2000 accesser via the XML interface); helped do a couple of tiny patches to python 2.0, and had done a very basic table/form generator to help me do horizontal and vertical tables, and auto-generate < select > lists. it was all thoroughly archaic, and it clunked along nicely. this technology i used successfully over the next four years, to write all sorts of little projects for myself, some of which i even got paid for. in the back of my mind, however, was the nagging feeling that there had to be something better out there. to zope or not to zope well, I got an opportunity to focus my tiny brain onto Zope, this january, and i have to say that i am genuinely disappointed by it. i had been led to believe that zope is fantastic as a web development tool. what Zope _actually_ is is a web development tool _kit_, and it has taken me about two months to work this out. Zope allows non-programmers to plug things together: you can "plug in" a SQL statement in the zope administrative front-end, and then you can use that SQL statement to generate as many tables as you want - again, with the zope administrative front-end. i don't know about you, but if you want to go beyond that - into actual web development (as we, as programmers, would expect), then it all starts to get a bit... well... hairy. the entry-level requirements are quite high: plus, you have to "worm" your way through the google searches, eliminating all of the "not-quite-useful-to-programmers" stuff that makes Zope so successful to non-programmer-types. let me put it this way: when you feel the need to start a web site "zope for real programmers" then you know that something's not quite right. the final straw for me was when i started writing my OWN project in zope, hoping to use and then learn more about SQLObject (very good article about sqlobject on ibm developerworks network by the way) only to find that it conflicts badly with zope 2.6 to 2.8 due to "refresh cacheing" of modules. i took one look at zope 3.0's xml-based config files and went "nnnnnn....naah". at that point, i had about four days worth of programming already done, but my experience with zope (from my day job that i started two months ago) had ALREADY led me to write-off dtml-call, dtml-let etc. leaving me with true/false-based dtml-if statements, dtml-var "somevariable" and dtml-in (if you've ever used htmltmpl, you know what's coming next...) mod_python and htmltmpl converting the code to use mod_python took, if i am to be honest, about a day - including looking up the documentation on how to use Cookies, how to use requests, doing the apache2 configuration, converting the use of http get/post variables (which didn't take a lot because it's just a dictionary of values or lists)... ... but what _should_ have been the trickiest bit (converting from dtml to htmltmpl) was actually the simplest: global/search/replace "mapping" with ""; global/search/replace "dtml-if" with TMPL_IF; ... etc. one gotcha: htmltmpl has "cgi escape" on as the default (for safety reasons) - so you can either make sure that any template-variables that are hyperlinks you use < TMPL_VAR theweblink, or you can set the default of the TemplateManager to not do cgi-escaping of any template-variables. here's where i cheated a bit, because i've been using htmltmpl since i discovered it, two years ago, and i created a REALLY useful class which wraps TemplateProcessor as a dictionary, and overloaded the __str__ method: you then declare an TMPLdict object with the filename as the argument, set all of the template variables you need to be substituted, and then when you're ready, do return str(tmpl_object) and voila you get your rendered HTML page. so, that class was _pretty_ much identical to zope's HTMLfile class - close enough for me to write some vi macros which warped the code, carefully, so i was done converting within a couple of hours. there are two absolutely _vital_ bits of technology - both by ian bicking - which make web development an art to enjoy rather than a "job to be done", and they are SQLobject and FormEncode. SQLobject is incredibly powerful, but i found that (back in 2002/3) its requirement (since lifted) that all tables must have an auto-numbered "id" field, very restrictive except for new projects. this being a new project, i could use it. sqlobject wow, wow, i love this stuff. it's very powerful and it supports six well-known database back-ends - all seamlessly. the only thing is that, as someone who has been doing relational database programming "the hard way", keeping a list in my head of the top most complex database queries i've had to design (eight weeks design and two weeks implementing is the record, so far), i find sqlobject a little difficult. my associate, however, who has had _zero_ relational database experience, finds it stunningly simple to use :) unfortunately, i taught him about 4th normalised database forms and we only have... *frantic* one table! yes, one table! we're about to make it a few more (one for each type of object - float, blob, string) but it's even stretching what sqlobject is capable of. ... fortunately, between the two of us... :) at some point, we'll make a decision as to whether to make the code free software or not: certainly the object-orientated database access module is something worth open sourcing, but it's also worthy of an article on its own, it's that horrendous, and we're just investigating python meta-classes as part of making the api very easy to use. formencode FormEncode. wow, how i wish i'd found formencode before now. it's incredible. you pass it a straight, vanilla, plain, £6/hr-web-designer-written form, a cgi-based dictionary of web-form-values and a validator class, and it gives you a dictionary of results, plus some errors back. you can then go "oh look, errors", and hand the results and the errors BACK to FormEncode, and it will generate the HTML page containing those errors (substituted into the right places!) plus the results substituted into the page AS WELL, so that the user can re-submit the form without having to go "back". it's just... incredible! unfortunately, ian believes that zope (ptoooey) has superseded formencode (with things like Formulator and ZPT) and ... how wrong, wrong wrong could he be (fortunately this assessment ability doesn't affect his programming abilities - hi ian, love your code! :) ZPT is a macro-based programming language embedded in HTML pages with an XML syntax (more on this later) - formulator is a python-based library that understands HTML (input, textarea, select - the works) as it uses the python "SGML / SAX" library to walk the html nodes, looking for the right places. bottom line: gimme formulator any day. AJAX the other technology that i've discovered (through my day job) is AJAX. now, given that i'm a javascript-hater, for me to be advocating AJAX there'd better be a damn good reason for it - and it's this: insanely, insanely fast web sites. what is the _one_ thing that you find most annoying about web pages? REFRESH!!! _dang_ - hitting a button and the ENTIRE page has to be regenerated at the server-end, and then fed over the internet connection, AND THEN it gets redrawn (from scratch, with a flicker), including all those REALLY annoying flashing images, and because it's badly-written html, the tables go "splurge" sideways until all the content is finally downloaded... have you ever _looked_ at myspace.com? ... don't! the alternative is AJAX, and the site i'm writing now uses it to the extreme: as an alternative to frames and iframes. in combination with carefully-crafted CSS stylesheets, it's FAST. whenever a user clicks on a link, the only html that is loaded from the server, which is done via an XmlHTTPRequest object on the browser, is that tiny fragment which is then substituted into a < div > tag. the only down-side of AJAX is that if you use it, you must USE it, including for forms, because the user's browser is storing all the state information about the current page - your server certainly isn't! so when you click that POST form, you lose everything to the "action" destination page. before i started using AJAX "post" on forms, i did come up with a "solution": i made the "main index page" the form "action" for EVVEERRYYTHING - and redirected all of the POST arguments dynamically through to the (ajax-based) frame targets, which themselves had to be dynamic. this quickly got out-of-hand beyond the fourth form that i added, and at that point i began to investigate the POST method of XmlHTTPRequest. the tricky bit of using AJAX on forms is that you must parse the HTML form yourself, looking for all the form "elements" in, yep, you got it: javascript. fortunately i found a very good half-working example. another alternative is to put the form into an iframe. and for "file upload", well... you _have_ to use a standard form, because javascript isn't allowed access to the local filesystem as it's a security risk, so you can't get at the file in order to read it in order to POST it via an XmlHTTPRequest javascript object. ... i have to say, it's quite complex, but well worth the effort. ... if you can tolerate javascript. CSS styles i now _love_ css. the site i'm doing would make a lynx user proud. at my associate's recommendation, there are ZERO colour codings, ZERO font tags, and judicious use of "em" instead of "px". the reason is this: if people _want_ to make their fonts smaller or larger, they should be able to. if people _want_ to select a different background/foreground, they should be able to. without fear of retribution from their own computer. want to lose customers and clients? write crap or overblown html. you remember that ugly web site article on slashdot? (this one) - well worth reading. what have you _done_, dude???? i'm writing a social networking site (yes, another one). because i can. because i don't like the existing ones. because i want to do cool stuff that i can be proud of achieving. because i want to learn about elegant and useful stuff that will help me do my job better and make stacks of wonga. in two weeks, using these simple python technologies, i and a very technically competent associate of mine have an alpha version of our site that already rivals the worst of the worst dating sites you've probably never dared to go near - and it's FAST, simple and... well, it's early days yet :) links here is a quick list of the components and some links where relevant: web-programming in unprogrammable languages one final and very important thing - my recommendations on what to use for web development. avoid dtml-call and dtml-let like the friggin plague. why am i making these recommendations? ... well... it goes like this. i was asked to take over a project that was written in php, and the guy had been working for a year on it - cutting and pasting some MASSIVE forms, several thousand lines long - to produce near-identical add, edit and error pages. absolute insanity. the reason? it had never crossed his mind to use templating, because when you are presented with a page full of php, it's simpler to cut/paste than it is to think. consequently, the site, which is very useful and runs a 100,000-strong subscription list with over two million database records, now has an absolute nightmare maintenance headache on its hands. formencode and htmltmpl are the FIRST tools you should look to (or their perl or *shudder* php variants) dtml is, for similar reasons, a pile of pants. ... but, worse, it's got an XML syntax! and the poor people who know and love it are beginning to realise that something is wrong, so they're recommending ZPT (zope page templates) instead, which is not quite as bad. that's a bit like saying "oooooh, isn't the air fresh today?" as you walk out of a decaying fish-market and slip nose-first into dogshit. but seriously: the "macro" system of ZPT is a really good idea, but you _can_ avoid it altogether by doing your web programming in an actual programming language (like python, for example). dtml is fine - _if_ you stick to dtml-if, dtml-in and dtml-var! but htmltmpl is better, because it does cacheing and pre-parses/compiles the templates (like php does, i assume). stay away from psp, for exactly the same reasons: it will only encourage your programmers to embed python code into an html page, where it will get cut-and-paste beyond reasonable and sane limits. if you _have_ to use PHP, write every page as two separate pages - one which contains the programming, and the other which contains the HTML - even write your own templating system if you can't be bothered to use the php-version of htmltmpl. just... *slap* don't do it! maybe i'm preaching to the converted, here, i dunno. i just can't get over how little code is actually needed to do so much, with the above list of technologies. i've been fishing and floundering around for several years, and finally found something reasonable. just had to tell you about it. here's my "htmldict" class, which wraps htmltmpl. the __access__ bit is so that mod_python can't get at any functions/classes in it. you use this as: content = HTMLdict('www/maincontent.tmpl') content['name'] = 'fred' page = HTMLdict("www/index.tmpl") page['title'] = 'hello' page['content'] = contentpage return str(page) on e.g. www/index.tmpl:< html > < title > < TMPL_VAR title > < /title > < body > < TMPL_VAR content > < /body > < /html > and e.g. www/content.tmpl:< p > hurrah, welcome, < TMPL_VAR name > < /p > < /pre > __access__ = 0 from htmltmpl import TemplateProcessor, TemplateManager class HTMLdict(dict, TemplateProcessor): def __init__(self, fname=None, htmlescape=0): self.tmpl_fname = fname dict.__init__(self) TemplateProcessor.__init__(self, html_escape=htmlescape) def __str__(self): if self.tmpl_fname is None: return '' for (k, val) in self.items(): if type(val) != type([]) and type(val) != type('') and \ val is not None: self.set(k, str(val)) elif val is not None: self.set(k, val) template = TemplateManager().prepare(self.tmpl_fname) return self.process(template) i just received word from someone who read this article, and they kindly pointed out a couple of things. the first one is that ZPT makes it incredibly easy to hand HTML to web designers: the syntax is < tal:table > and so the template macro stuff doesn't interfere, in any way, with the web designer's job - unlike dtml and htmltmpl. i pointed out to him that if ZPT only supported if-true-false, variable substitution and loop-on-list-of-dictionaries, i would consider it to be ideal. in situations where you put a "cool toy" in front of people whose job it is to "do", they will "do", and they will use every "cool toy" possible. regardless of the consequences, because it's not their job to think of that. hence, why i have such a problem with zope: so much _can_ be done with it that people _will_ do it - and get themselves into a mess. Thanks for the article. Always interesting to read your output. You're an interesting person to ask this: since you hate javascript, what do you do for those who turn it off? Do you write two versions of your site? Personally, since I usually have javascript turned off in my main browser configuration, I feel morally obligated to write sites that are still usable that way. It wouldn't be right to force others to use javascript if I don't want to use it myself. Not to mention the security side of things. It wouldn't be right to force my users to make their computers less secure just to use my site either. Thoughts? hiya cdfrey, well, what i've done is written a simple javascript function which walks the DOM model, looking for "onclick". i then "overwrite" the href with a javascript "void" function. this stops double-linking, but also allows people to click on the href if they have javascript disabled. then, i make sure that all hrefs are like this: < a click here < /a >=''; } } } the maintenance effort of having two sites really would be a nightmare. so i hope to come up with some tricks where, with ease, i can switch between frames, non-javascript, iframes, ajax... we'll see what happens :) the syntax of ZPT (tal) is like this: < td tal: < /td > which means of course that the "unrecognised" attributes simply get ignored by "industry-standard" web design tools. and i was very interested to hear (from matthew hamilton, of netsight) that a lot of people who are using ZPT are advocating the same things that i am - namely that ZPT should be restricted to if-true-false, loop-on-list-of-dictionaries, and text-substitution. btw, also, it's worth pointing out: ZPT doesn't have to be used exclusively in zope. < noscript > do something here like put in an href to a different style menu < /noscript> according to the above article, what i am apparently _supposed_ to do is return "true" from the "onclick" function and then the href won't be actioned. hm. oh well! Just now I posted a diary about how I'm learning C# ASP.Net so I can put those two all-important buzzwords in my resume. It seems the the once proud and independent nation of Canada is now completely within the grip of the Evil Empire. To prove I can do it, and hopefully make a little coin on my own, I'm using them to write a web application that will run on Mono, Apache and Linux rather than Windoze and IIS. From what I've seen of C# so far, it looks like a well-designed language, and I hear good things about it all the time. I personally am a big fan of Python, and would prefer to code my new web app in it, if it weren't for the fact that there seem to be no Python jobs to be found anywhere in Canada. I need the website to give me a foot in the door for C# contracts, as I don't have any paid experience using it. this may come as a surprise, but i actually really like mono and .net and what it promises - but then, i was privileged to hear what the designers had in mind for it - namely that it should be a common binding for _all_ the possible languages that ms could get their hands on. to that end, they hired the guy who wrote ironpython, which if you have the time and love python, i do recommend that you investigate it. it's basically .net (mono) with a python syntax. you CANNOT get access to the standard python librariey: ironpython is actually a compiler that happens to have a python syntax, it really DOES have absolutely nothing to do with python2.X, so you have all of the .net and mono libraries available to you instead. okay. here's what i would like to see happen, wrt mono. namely, that they go get libwine, and then add a COMPLETE set of bindings into mono, for Win32. this would truly make it possible for .net applications to run cross-platform. already, from what i can gather, it's possible to run applications written for ASP/.NET under apache2 - it would be absolutely perfect if you could run win32 graphical applications, too. UGH! lovely syntax (right up to the ${fruit} bit). love the < ul py:xxx > bit: like tal that makes it possible to hand the html to a specialist html designer without them needing to know about "code". ... but evaluation of functions? NNOOOOO! template-based functions/macros? NOOOO! ... y'know... i really should set up an example site of what i've been using... i'd love to see how it compares against e.g. cherrypy. might as well dump the javascript i use at you - it's a mish-mash of various examples i've found online, some of which needed work. one little "trick" that i do is, if you download an HTTP fragment which contains < script >, then i execute its content! this is an unbelievably incredibly useful trick, because what you can use it for is to put in further ajax calls in to update other < div > tags. for example, my "congratulations you logged in" welcome message appears in my "centrepage" div, and that div tag is the target of the AJAX POST of the login form. being greeted by "congratulations you logged in" is friggin boring, so i added < script > ajax_dlink('leftcontext, './usercontext.html'); ajax_dlink('banner', 'usermenu.html'); < /script > and that of course gets executed by the "activate_javascript()" function... neat, huh? :) btw - watch out for using the timeout-based ajax_dlink_refresh() function: it's a bit weird, it's not perfect, and that's probably because i need to call clearTimeout() from the AJAX POSTing function as well and then restart the timer... oh well :) function createHttpRequest(){ if(window.ActiveXObject){ try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { return null; } } } else if(window.XMLHttpRequest){ return new XMLHttpRequest(); } else { return null; } }=''; } } } /** * activate_javascript(str) * * looks for any script and runs it (using eval) * */ function activate_javascript(targetnode) { var scriptnodes = targetnode.getElementsByTagName('script') var LC; for (LC = 0; LC < scriptnodes.length; LC++) { var sn = scriptnodes[LC]; var nd = document.getElementById('centercontent'); if (sn.src) { ajax_eval(sn.src); } else { eval(sn.innerHTML); } } } /** * ajax_eval(url) * * @param url load and activate url * @returns readyState */ function ajax_eval(url) { var xhtoj = createHttpRequest() xhtoj.open("GET", url , true ); xhtoj.onreadystatechange = function() { if ((xhtoj.readyState==4) && (xhtoj.status == 200) ) { str = xhtoj.responseText; eval(str); } } xhtoj.send("") } /** * ajax_dlink_refresh(oj,url) * * @param id id of element for insert * @param url load url * @param timeout refresh timeout period, ms * @returns readyState */ /* use these to overrun an existing timeout, so that we don't end up with several of them! */ var running_timeout = 0; var timeout_idname; var timeout_url; function ajax_dlink_refresh(idname, url, timeout) { timeout_idname = idname; timeout_url = url; redo_timeout = timeout; if (running_timeout) return; setTimeout("do_ajax_dlink_refresh()", timeout); running_timeout = 1; } function do_ajax_dlink_refresh() { if (ajax_dlink(timeout_idname, timeout_url) == 0) { running_timeout = 0; return; } running_timeout = 0; ajax_dlink_refresh(timeout_idname, timeout_url, redo_timeout); } /** * ajax_dlink(oj,url) * * @param id id of element for insert * @param url load url * @returns readyState */ function ajax_dlink(idname,url) { clearTimeout(); /* really important - get into a mess otherwise */ var xhtoj = createHttpRequest() xhtoj.open("GET", url , true ); xhtoj.send(""); var jsnode = 0;); if (jsnode) { jsnode.innerHTML=str; activate_javascript(jsnode); /* remove all hrefs from onlick links */ set_hrefs(); return 1; } } } return 0; } /** * chk_browser() * * @param browserName browser name */ function chk_browser(browserName) { var ua = navigator.userAgent switch (browserName) { case 'konqueror' : return ua.indexOf("Konqueror") != -1 ; break ; case 'safari' : return ua.indexOf("Safari") != -1 ; break ; dafault : return null ; break ; } } /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <mo@goice.co.jp> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */ /* * Interfaces: * utf8 = utf16to8(utf16); * utf16 = utf16to8(utf8); */ function utf16to8(str) { var out, i, len, c; out = ""; len = str.length; for(i = 0; i < len; i++) { c = str.charCodeAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { out += str.charAt(i); } else if (c > 0x07FF) { out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } else { out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } } return out; } function utf8to16(str) { var out, i, len, c; var char2, char3; out = ""; len = str.length; i = 0; while(i < len) { c = str.charCodeAt(i++); switch(c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += str.charAt(i-1); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = str.charCodeAt(i++); char3 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out; } function ajax_post(idname, file, fobj) { var str = getFormValues(fobj, null); var xhtoj = createHttpRequest(); var jsnode = document.getElementById(idname); xhtoj.open( "POST", file, true ); xhtoj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhtoj.setRequestHeader("Content-length", str.length); xhtoj.setRequestHeader("Connection", "close"); xhtoj.send(str);); jsnode.innerHTML = str; activate_javascript(jsnode); /* remove all hrefs from onlick links */ set_hrefs(); } } } function getFormValues(fobj) { var str = ""; var val = ""; var cmd = ""; var valFunc = null; for (var i = 0;i < fobj.elements.length; i++) { switch (fobj.elements[i].type) { case "checkbox": case "radio": { if (fobj.elements[i].checked) { str += fobj.elements[i].name + "=" + fobj.elements[i].value + "&"; } else { str += fobj.elements[i].name + "=&"; } break; } case "text": case "hiddentext": case "hidden": case "password": case "textarea": case "button": if(valFunc) { //use single quotes for argument so that the value of //fobj.elements[i].value is treated as a string not a literal cmd = valFunc + "(" + 'fobj.elements[i].value' + ")"; val = eval(cmd) } str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&"; break; case "select-one": str += fobj.elements[i].name + "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&"; break; } } str = str.substr(0,(str.length - 1)); return str; } and htmltemplate looks a _hell_ of a lot better than anything i've previously encountered. you indicate what you want to "tag", by using the syntax "node=somename" and then you can reference anything with somename as a python variable. the syntax could use a little work. e.g. to access (and replace) the inner-html, you do template.somename.content = "the new content", and to add (or delete?) an attribute, you do template.somename.atts['href'] = "" with proper overloading, this could be template.somename = "the new content" and template.somename['href'] = "". and yes you can do template.somename = "the new content" - in the template class you overload __setattr__ i believe. the way that HTMLTemplate works is _very_ obscure. i love the convenience behind the HTMLdict concept, so here's a simple wrapper which provides the same functionality - for HTMLTemplate: from HTMLTemplate import Template class HTMLdict2(dict): def __init__(self, fname=None, content=None): dict.__init__(self) if fname: f = open(fname, "r") content = f.read() f.close() self.t = Template(self.render, content) def render(self, node, kvs): for (k, val) in kvs.items(): a = getattr(node, k) if isinstance(val, type([])): a.repeat(self.render, val) else: a.content = val def __str__(self): return self.t.render(self) def test(): <h2 node="con:title">section title</h2> <p node="con:desc">section description</p> </div> """ x = HTMLdict2(content=html) d = [{'title': 'title1', 'desc': 'desc1'}] x['section'] = d print str(x) test embedded greeting card (1600x1200pix) from Jones Farm, West Trenton NJ. look at her through this lens. what you see ain't what you get. the author calls this "advanced ajax". basically it's very similar to the ajax.js i posted, above. the key thing that i can notice (and understand, with 1mins' scanning) is that it copes with select-multiple on HTTP POST. also it looks like it has some auto-refresh stuff, whoopeee. a slashdot article which highlights why PHP and MySQL are so horrendous: maintenance. although the author on his blog mentions that PHP is "bad" because it encourages people to mix-code-with-markup, he then goes on to recommend Zope - without then advocating that people avoid ZPT/TAL's mix-code-with-markup features, or dtml's mix-code-and-namespaces-with-markup. lucky he doesn't know about mod_python's "PSP" in order to recommend that, then :) i've just started adding in support for no javascript, with a view to "if things go wrong with ajax..." :) the principle is quite straightforward, and has two aspects. the first is to "construct" the web page, from multiple functions, or to set up ajax calls to "populate" the web page; the second is to "remember" previous AJAX calls and to add them to the "populating" bit; or to reconstruct the page again using the new and the key to doing this is to subdivide the web site into sections using < div < div id="banner /> etc. "remembering" the history basically revolves around "recording", on a per-div-id-basis, the last location where an AJAX call overwrote the DOM model. to that end, it is necessary to record the href which was clicked on and associate it with the div "id" - using the div "id" as a key into a dictionary and recording the entire href clicked on as the key. the trick is to distinguish between those AJAX calls which are to be "remembered" and those which are not - at the server-end. i do this by adding in an extra parameter onto the href - "&source=centercontent". BEFORE the python function which constructs the response page is returned, this argument is REMOVED, then the rest of the URL is recorded under the divid (in this example, centercontent) in a dictionary. also, i don't set up links to web pages by shoving in an < a into the HTML template - that's boring :) what i do is pass a list of dictionaries containing the link information to a function, which creates the actual a href - _including_ automatically adding "&source=xxxx" and _including_ setting it up to do the javascript "onclick=ajax_dlink('./thewebpage?source=xxxx','xxxx')" stuff. i haven't quite got round to it yet but in "non-ajax" mode, there will be only one target page - the index page. and the link-targets will get "munged" so that what _was_ the target page (e.g. "./profile?user=fred" in the menu) will become an argument passed to the index page (e.g. "./index?source=xxxx&actualtarget=profile%2Euser%3Cfred" - i don't really know yet. ultimately, i should also be able to add in a "frames" mode, where i construct framesets, too. at that point, when i have it all working, i'll try to get it all documented and package it up because it's pretty cool :) mod_python introduction article very good article explaining how to set up apache, mod_python, mysql - and recommending the use of sqlobject and explaining it. code fragment examples, config file examples - all in one. hurrah. AAAAAGH! NOOOOOOOOO! :) google search for "ajax mistakes" shows up a whole stack of useful articles. correct link damn xxxxing advogato seriously needs some arse-kicking. oh. and an edit mode. and it may not be a bad thing. Natural simplying process. Mandatory evaculation means ' if you walk freely in that zone, authority may put you behind the bar.' Here's latest snap shot. Water under the Washington Crossing bridge. Last time when i walked on the bridge sidewalk, water might be more than 20 feet below... more ajax stuff - very good. what on _earth_ are you wittering about? :) hardly can gather any strength for anything. heartless to link my name with 'wittering'. NJ Politics is the funniest and cruelest. 'Everybody wants to be gay. Everybody wants to be happy." Former governor James McGreavy has a book out. He lives in my old neighborhood, hillside historical Queen City now. hmm, there appears to be a lot of ruby-ajax-integration - haven't found _anything_ like it for python. django looks!
http://www.advogato.org/article/882.html
crawl-001
refinedweb
5,517
62.98
Social Coding/Hosting a Project at GitHub Contents. When you move your project to Eclipse, all existing related GitHub repositories must be moved into the corresponding GitHub organization. As part of the intellectual property (IP) due diligence process, each repository's history must be collapsed into a single commit that will be used as the project's initial contribution. The complete history will remain in the repository, but it will be obscured to a separate namespace. - Tag your "initial contribution" commit as eclipse_initial - Note that the committers listed in your project proposal are permitted to continue working and creating new commits after this process has started. They must follow the Eclipse Foundation's intellectual property due diligence rules from the moment we start the move process. The first step is to assign ownership of the repository to the Eclipse Foundation's Webmaster. Use the GitHub web interface to transfer ownership of each project repository to eclipsewebmaster. For each repository, first locate and click the "Settings"; scroll down to the "Danger Zone". Click "Transfer" in the "Transfer Ownership" block. As instructed, type the name of the repository, and enter eclipsewebmaster as the new owner. Collapsing History As part of the process of preparing your repository, the Eclipse Webmaster will collapse the history of the project into a single commit. The starting point is the commit identified by the eclipse_initial tag. The state of the repository represented by that commit is collapsed into a single commit that is then given the eclipse_initial tag. That single commit will then be the starting point for all development by the project team following the move to Eclipse. This means that exactly one branch will "survive" the move; be sure to either merge other branches before the move, or get used to the thought of not having them. The existing commits will remain in the repository, but they will not be easily reachable. For more information, please see Migrating a GitHub Repository. Processing Repositories After the project is created, the Eclipse Webmaster will start the provisioning process. After provisioning is complete, the history of the repository--including all existing commits, branches, and tags--will persist in the repository, but will not be easily accessible (i.e. an average user who clones the repository will not pull in these commits). All of the history will be replaced by a single commit. The Eclipse Webmaster will tell you via email when provisioning is complete. At that point in time, extract the initial contribution commit (tagged eclipse_initial as a ZIP file for use as the project's initial contribution. Project committers can continue to create new commits. From this point forward, committers are expected to follow the Eclipse IP Due Diligence Rules. As committers complete their paperwork and their accounts are provisioned, they will gain the ability to push/merge those commits into the GitHub-based repository. Committers can work in the repository as normal (e.g. they can create branches). The Eclipse IP Team will review your initial contribution. At some point, the IP team will inform you that the project code has been approved for "Parallel IP Check-in". This is a cue for the Webmaster to start maintaining a mirror of the project repositories on Eclipse Foundation servers. This approval has no direct impact on project developers. As the IP team works through the due diligence process they may uncover issues that need to be addressed. Be prepared to work with the Eclipse Webmaster to mitigate these issues. In some cases, mitigation may require some "surgery" on the Git repository (e.g. if GPL-licensed code is discovered, it must be completely removed from the accessible history of the repository). Some time later, the IP Team will grant full approval. This is a notification to you and the community that initial contribution has completed the due diligence process. Congratulations!.
http://wiki.eclipse.org/index.php?title=Social_Coding/Hosting_a_Project_at_GitHub&oldid=356512
CC-MAIN-2015-18
refinedweb
643
55.13
Closed Bug 730888 Opened 10 years ago Closed 10 years ago Crash [@ JSString::is Linear] Categories (Core :: JavaScript Engine, defect) Tracking () People (Reporter: decoder, Assigned: bhackett1024) References Details (Keywords: crash, regression, testcase, Whiteboard: js-triage-needed) Attachments (1 file) The following test crashes on mozilla-central revision 2dc40eb83023 (options -m -n): (function() { for (var i = 0; i < 64; ++i) { var name; switch (this) { case 0: name = 'firstAttr'; break; case 1: name = 'secondAttr'; case 2: name = 'thirdAttr'; break; } switch (name) { case 'firstAttr': assertEq(result, 'value'); break; } } })(); Backtrace: Program received signal SIGSEGV, Segmentation fault. 0x0000000000442e8c in JSString::isLinear (this=0x0) at /srv/repos/mozilla-central/js/src/vm/String.h:316 316 return (d.lengthAndFlags & LINEAR_MASK) == LINEAR_FLAGS; (gdb) bt #0 0x0000000000442e8c in JSString::isLinear (this=0x0) at /srv/repos/mozilla-central/js/src/vm/String.h:316 #1 0x0000000000443232 in JSString::ensureLinear (this=0x0, cx=0xb62b40) at /srv/repos/mozilla-central/js/src/vm/String.h:794 #2 0x0000000000787540 in js::mjit::stubs::LookupSwitch (f=..., pc=0xb6859f "\001") at /srv/repos/mozilla-central/js/src/methodjit/StubCalls.cpp:1517 #3 0x00007ffff7f3c464 in ?? () #4 0x00007ffff7f3c078 in ?? () #5 0x0000000000000000 in ?? () Bisect: The first bad revision is: changeset: 87569:8ab9fea628bd parent: 87565:f077e2e7e38d user: Brian Hackett date: Thu Feb 23 13:01:27 2012 -0800 summary: Efficiency improvements in ScriptAnalysis::analyzeSSA, bug 725920. r=dvander I'm locking this because I also have a very close testcase that causes an infer failure (where bisect also points to this changeset), so I cannot be sure that this is harmless. (In reply to Christian Holler (:decoder) from comment #0) > I'm locking this because I also have a very close testcase that causes an > infer failure (where bisect also points to this changeset), so I cannot be > sure that this is harmless.). This crash looks null deref-ish on the surface. the other testcase may be more interesting Assignee: general → bhackett1024 Keywords: regression (In reply to Daniel Veditz [:dveditz] from comment #1) >). I usually keep these bugs queued and retest them once the other bug is fixed to avoid missing any of them. > This crash looks null deref-ish on the surface. the other testcase may be > more interesting I'll post the other one if this one doesn't help bhackett to locate the problem. Since the other is an infer failure, it won't tell you much about the security impact either. Bug 725920 added two optimizations to SSA analysis, one for consolidating arrays of pending values for switch statements and one for avoiding excess crawling of these pending arrays for all branches. The former breaks some SSA invariants here that the offsets for phi nodes corresponds to the place they were actually formed (leading to cycles where not all values are accounted for). This patch just backs that optimization out --- the second one is cleaner and more general, and the former shouldn't make a difference for performance in either asymptotic behavior or constant factors. Attachment #601965 - Flags: review?(dvander) Status: NEW → RESOLVED Closed: 10 years ago Resolution: --- → FIXED Status: RESOLVED → VERIFIED Group: core-security
https://bugzilla.mozilla.org/show_bug.cgi?id=730888
CC-MAIN-2022-21
refinedweb
511
52.8
SetSchemaMetadata¶ The following provides usage information for the Apache Kafka® SMT org.apache.kafka.connect.transforms.SetSchemaMetadata. Description¶ Set the schema name, version or both on the record’s key ( org.apache.kafka.connect.transforms.SetSchemaMetadata$Key) or value ( org.apache.kafka.connect.transforms.SetSchemaMetadata$Value) schema. This SMT can be used to set the schema name, version, or both on Connect records. Since the schema name includes the namespace, a common SetSchemaMetadata SMT use case is to change the name and namespace of the schemas used in Apache Kafka® record keys and values. Use cases: Source connectors generate records with schemas defined by the connector, and often generate the names and versions of key and value schemas based upon source-specific information. For example, a database source connector might use the name of the table from which rows are read in the schema names. If these generated schema names do not adhere to the naming convention you need, you can use this SMT to override the generated names of the key and/or value schemas in the source records produced by the source connector. Sink connectors that consume records from Kafka topics may the names of the schemas to indicate how the connector maps the Kafka records into the external system. If the names of the schemas used in the record keys and values don’t result in the desired mapping, you can use this SMT to change the name of the key and/or value schemas in the consumed source records, before those records are processed by the sink connector. Example¶ This configuration snippet shows how to use SetSchemaMetadata to set a schema name and version. "transforms": "SetSchemaMetadata", "transforms.SetSchemaMetadata.type": "org.apache.kafka.connect.transforms.SetSchemaMetadata$Value", "transforms.SetSchemaMetadata.schema.name": "order-value" "transforms.SetSchemaMetadata.schema.version": "2" Example: See. The example uses SetSchemaMetadata to allow a connector to set the namespace in the schema..
https://docs.confluent.io/platform/6.2.0/connect/transforms/setschemametadata.html
CC-MAIN-2021-31
refinedweb
318
52.49
Opened 9 years ago Closed 9 years ago #5008 closed (duplicate) in mysql backend the test for MySQLdb version fail Description On my platform: import MySQLdb as Database Database.version_info (1, 2, 2, 'final', 0) so the test in db/backends/mysql/base.py version = Database.version_info if (version < (1,2,1) or (version[:3] == (1, 2, 1) and (len(version) < 5 or version[3] != 'final' or version[4] < 2))): raise ImportError, "MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.version fail and raise an error, but I think the version of MySQLdb is right Paolo Patruno Change History (1) comment:1 Changed 9 years ago by Note: See TracTickets for help on using tickets. Are you on Fedora? This looks to be a duplicate of #4743
https://code.djangoproject.com/ticket/5008
CC-MAIN-2017-04
refinedweb
131
75.5
this is something I've been cracking my brain over but can't seem to find a decent solution for. I've done a number of searches but can't seem to come up with anything useful either. Here's the situation: I have an array of integer numbers. I need to add up a number of those integers to match a specific value. So, say for example that I have the following array: my @array = (6, 18, 12, 2, 49); I'd need some sort of method to add up x of the elements to make up number y. So for example if I were to need 2 of the integers to add up to 30, I'd need it to return that elements 1 and 2 match the description. Normally if I knew in advance that I'd only need 2 integers I'd use 2 nested foreach loops, but in this case both the x amount of integers that need to be added up as well as the final number y that needs to result from the search are variable, so I'm definitely lost here. Is there a module that could work this black magic for me? On a sidenote I also need to mention that I require all matches. After checking each of the replies and browsing through the various pieces of information available on the whole knapsack problem, first allow me to express my earnest gratitude for all the great advice everyone has spent their time giving me. Keeping in mind the specifics of my particular situation I decided to take little bits and pieces from everywhere and came up with the following: package Algorithm::Knapsack::Fixed; use strict; use warnings; use Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(calculate); sub calculate { my($target, $number, $arrayref) = @_; my @counters = (0..($number - 1)); my @array = @{$arrayref}; my @results; my $endpoint = $#array - $#counters; #sort the array in descending order but remember what the original o +rder was so we can reverse the sort # before we give back the results. If for example we find that items + 123 and 456 of the sorted array # match, we'd return $order[123] and $order[456] my @order = sort { $array[$b] <=> $array[$a] } @0 .. $#array; @array = @array[@order]; while(1) { my $sum = 0; $sum += $array[$counters[0]]; for(1..$#counters) { $sum += $array[$counters[$_]]; if(($sum > $target) && ($_ < $#counters)) { &_increment($_, \@counters, \@array); last; } } if($sum == $target) { #we've got a matching combination! push(@results, [@order[@counters]]); } if(($counters[0] == $endpoint) || (($array[$counters[0]] * ($#coun +ters + 1)) < $target)) { return @results; } if($sum < $target) { &_increment(($#counters - 1), \@counters, \@array); } &_increment($#counters, \@counters, \@array); } } sub _increment { my($counter, $countersref, $arrayref) = @_; $countersref->[$counter]++; while(($countersref->[$counter] > $#$arrayref - ($#$countersref - $c +ounter)) && ($counter > 0)) { $counter--; $countersref->[$counter]++; } if($counter < $#$countersref) { foreach my $counter2 (($counter + 1)..$#$countersref) { $countersref->[$counter2] = $countersref->[$counter] + $counte +r2 - $counter; } } } 1; [download] As to your question, I'd do it with a recursive routine; in outline: sub find { my ($want, $n, $elems) = @_; return if $n == 0; return if $want <= 0; for (0..$#$elems) { my $e = $elems->[$_]; if ($n == 1) { return $e if $e == $want; } else { my @f = find($want-$e, $n-1, [@$elems less $e]); return ($e, @f) if @f; } } return; } # get 57 from 2 numbers in the set @answer = find(57, 2, [1,3,7,11]); [download] Dave. --[ e d @ h a l l e y . c c ] sub searchLoop { - pass in: - target number (y) - number of elements desired (x) - the array (array) - y offset number (offset, starts at 0) - sort array in descending numerical order and store that into a tempo +rary array that you can mess with. - remove entries in the temp array that are larger than y - foreach ( unshift a value off temp array into z) remaining entry: - if z = y, print z+offset as a solution (or return it if you only n +eed one solution) - run searchLoop(y-z, x-1, temp (with the z element removed), offset ++z) } [download] See: Subset Sum Problem This is most likely only relevant if your set is very large. There is an algorithm to solve it in polynomial time that trades off non-polynomial high memory usage for fast processing time. See: Polynomial Time Dynamic Programming Solution -Andrew. --Solo -- You said you wanted to be around when I made a mistake; well, this could be it, sweetheart. -- You said you wanted to be around when I made a mistake; well, this could be it, sweetheart. Math::Combinatorics helps with generating the combinations. sub _{@_>2&&$_[0]>0?(($_[2]==$_[1]&&$_[0]==1?[$_[2]]:()),&_($_[0],$_[1 +],@_[3..$#_]),map[$_[2],@$_],&_($_[0]-1,$_[1]-$_[2],@_[3..$#_])):()} [download] use strict; use warnings; my @array = (6, 18, 12, 2, 49); addup(2, 30, 0, [sort {$b <=> $a} @array]); sub addup { my ($num, $val, $offset, $p, @set) = @_; if ($num == 1) { for ($offset..$#{$p}) { last if @$p[$_] < $val; print join ' ', @set, $val, "\n" if @$p[$_] == $val; } } else { for ($offset..($#{$p}-$num+1)) { next if @$p[$_] > $val - $num + 1; last if @$p[$_] < int ($val / $num); addup($num-1, $val-@$p[$_], $_+1, $p, @set, @.
http://www.perlmonks.org/?node_id=478387
CC-MAIN-2016-30
refinedweb
875
53.44
The term “string” refers to a collection of Unicode characters. A string is a collection of characters that can include both alphanumeric and special characters. We will learn about substring in Python and how it works in this article: What is a substring in Python? In Python, a substring is a sequence of characters contained a string within another string. In Python, it’s also known as string slicing. Substringing a string in Python can be done in a variety of ways. Thus, it’s commonly referred to as slicing.’ In this demo, we will follow the following template. string[begin: end: step] Where, - begin – The index at which the substring begins. The substring has the character at this index. If begin isn’t specified, it’s considered to be 0. - end: The substring’s finishing index. The substring does not include the character at this index. If end is omitted, or if the supplied value is more than the string length, it is presumed to be equal to the string length by default. - step: After the current character, there has to be an inclusion of every ‘step’ character. 1 is the default value. If the step value isn’t specified, it’s considered to be 1. - Get all characters from the beginning index to end-1 using the template string[begin:end]. - Get all characters from the beginning of the string to end-1 using string[:end]. - string[start:]: Get all characters from the string’s index start to the end. - Get all characters from start to end-1, ignoring every step character. string[start:end:step]: Get all characters from begin to end-1, ignoring every step character. Examples: string = "Codeunderscored" print(string[0:5]) Note that print(string[:5]) yields the same output as print(string[:5]) (string[0:5]) From the third character in the string, create a four-character substring. string = "Codeunderscored" print(string[2:6]) Would you please keep in mind that the start or end index could be negative? When you use a negative index, you begin counting from the end of the string rather than the beginning (i.e., from right to left). The last character of the string is represented by index -1, the second to last character by index -2, etc. Get the string’s last character. string = "Codeunderscored" print(string[-1]) Get the string’s last five characters string = "Codeunderscored" print(string[-5:]) Obtain a substring that contains all characters with the exception of the last four and the first. string = "Codeunderscored" print(string[1:-4]) Additional examples str = "Codeunderscored" print str[-5:-2] # prints 'eCa' print str[-1:-2] # prints '' (empty string) Get all the other characters in a string. string = "Codeunderscored" print(string[::2]) Check if a string contains a substring In our quest of checking the presence of a substring in a string, we’ll use the in operator. test_data = "Life comes in all dimensions, and you have to do is make alternative plans by being busy doing something." 'Life' in test_data 'plant' in test_data Why does indexing indicate an index out-of-range error while slicing does not? index_error = 'Life' index_error[5] Try to return the value at index 5 with index error[5]. However, if the value at index 5 is not available, an error will be displayed. The sequence of values is returned by slicing. As a result, if the value at index[5] is missing, Python will not throw an exception. Always use slicing if you are unsure of the length of text data. Using list comprehension to retrieve all substrings # Get all substrings of string using list comprehension and string slicing s= 'PYTHON' str=[s[i: j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)] print (str) Output: ['P', 'PY', 'PYT', 'PYTH', 'PYTHO', 'PYTHON', 'Y', 'YT', 'YTH', 'YTHO', 'YTHON', 'T', 'TH', 'THO', 'THON', 'H', 'HO', 'HON', 'O', 'ON', 'N'] Using the itertools.combinations() technique to retrieve all substrings # Get all substrings of string using list comprehension and string slicing s= 'PYTHON' str=[s[i: j] for i in range(len(s)) print (str) Output: ['P', 'PY', 'PYT', 'PYTH', 'PYTHO', 'PYTHON', 'Y', 'YT', 'YTH', 'YTHO', 'YTHON', 'T', 'TH', 'THO', 'THON', 'H', 'HO', 'HON', 'O', 'ON', 'N'] Check to see if a substring exists within another string. Putting in the operator #Check if the string is present within another string using in operator original_string= 'This is to demonstrated substring functionality in python.' print("This" in original_string) print("Not present" in original_string) Output: True False If a string contains a particular substring, the in operator returns true; otherwise, it returns false. Using the find method Check if string is present within another string using find method s= 'This is to check for a substring instance in python.' print(s.find("check")) print(s.find("Absent")) Output: 11 -1 If a substring exists within another string, the Find method will print the index; otherwise, if a string does not exist, it will return -1. Determine if a string contains a substring The operator for in The in operator is the simplest way to see if a Python string contains a substring. In Python, the operator used in the verification of membership in data structures is in. It gives you a Boolean value (either True or False). In Python, we can use the in operator to see if a string contains a substring by invoking it on the superstring: fullstring = "Codeunderscored" substring = "scored" if get_substring in originalstring: print("Found!") else: print("Not found!") This operator is a shortcut for executing an object’s contains method, and it can also be used to see if an item in a list exists. It’s worth mentioning that it’s not null-safe. Thus an exception would be thrown if our fullstring pointed to None: TypeError: argument of type ‘NoneType’ is not iterable To avoid this, first determine whether it points to None or not: fullstring = None substring = "scored" if fullstring != None and substring in fullstring: print("Found!") else: print("Not found!") The String.index() Method String.index() is a method that returns the index of a string. The index() function of the String type in Python can be used to get the starting index of the initial cause of a substring within a given string. A ValueError exception is thrown if the substring is not found, which can be managed with a try-except-else block: fullstring = "Codeunderscored" substring = "scored" try: fullstring.index(substring) except ValueError: print("Not found!") else: print("Found!") This approach is handy if you need to know the substring’s position within the whole text rather than merely its existence. String.find() is a method that allows you to find something in a string. The String type contains another method called to find that is more convenient to use than index() because it doesn’t require any exception handling. If find() fails to discover a match, it gives -1; otherwise, it returns the substring’s left-most index in the bigger string. fullstring = "Codeunderscored" substring = "scored" if fullstring.find(substring) != -1: print("Found!") else: print("Not found!") This approach should be preferred over index() if you want to avoid having to catch mistakes. Regular Expressions (Regular Expressions) (RegEx) Regular expressions allow you to check strings for pattern matching in a more flexible (but more sophisticated) method. A built-in module supports regular expressions in Python called re. Search() is part of the functions in the module called re – we can use to match a substring pattern: from re import search fullstring = "Codeunderscored" substring = "scored " if search(substring, fullstring): print "Found!" else: print "Not found!" If you need a more complex matching function, such as case insensitive matching, this way is best. Otherwise, for simple substring matching, the complexities and slower speed of regex should be avoided. How to get the count of times that a substring exists in a string You may count the number of times a term appears in a document using the find() and replace() methods. Please see the code below for further information. text_data_test = " Life comes in all dimensions and you have to do is make alternative plans by being busy doing something." count = 0 while 'life' in text_data_test: text_data_test = text_data_test.lower().replace('life','',1) count+=1 f'occurrence of word life is {count}' The word life appears 3 times if the lower() function is removed. Because replace() is case-sensitive. Also, change the replace() function’s inputs to see what happens. The index of a string’s repeated substring The find() method can be used to find all the substring indexes in a text or string. text_data_test = " Life comes in all dimensions and you have to do is make alternative plans by being busy doing something." index_list = [] flag = 0 count = 0 word_length = len('life') while 'life' in text_data_test: return_index = text_data_test.lower().find('life') print(return_index) if return_index == -1: break if len(index_list) == 0: index_list.append(return_index) else: index_list.append(return_index + word_length * count) text_data_test = text_data_test.lower().replace('life',"",1) print(text_data_test) count += 1 There is no built-in method in Python that returns the index of all repeated substrings in a string. As a result, we’ll have to construct a new one. How to replace Substrings The replace() method can be used to substitute a word or a collection of words. text_data = "Life is what happens when you're busy making other plans." text_data.replace('other','no') text_data.replace('making other','with') Get the last substring of a sentence, regardless of its length Using the code below, you can get the last component of the string. It will also function with sentences of various lengths. test_data1 = " Life comes in all dimensions and you have to do is make alternative plans by being busy doing something." test_data2 = "Today is a beautiful day." for i in [test_data1, test_data2]: print(i.split()[-1]) Using a word or a character, split a string into substrings Imagine you have a business requirement that the application break a string into substrings if a busy word appears in it. You can do so by using the code below. text_data = "Life is what happens when you're busy making other plans." if 'busy' in text_data: print(text_data.split('busy')) A single character can also be used to separate the string. text_data = " Life comes in all dimensions and you have to do is make alternative plans by being busy doing something." if '.' in text_data: print(text_data.split('.')) Example 1: # code to demonstrate to create a substring from a string # Initialising string ini_string = 'xbzefdgstb' # printing initial string and character print ("initial_strings : ", ini_string) # creating substring from start of string # define length upto which substring required sstring_strt = ini_string[:2] sstring_end = ini_string[3:] # printing result print ("print resultant substring from start", sstring_strt) print ("print resultant substring from end", sstring_end) Example 2: We’ll explore how to make a string by extracting characters from a specific positional gap in this example. # code to demonstrate to create a substring from string # Initialising string ini_string = 'xbzefdgstb' # printing initial string and character print ("initial_strings : ", ini_string) # creating substring by taking element # after certain position gap # define length upto which substring required sstring_alt = ini_string[::2] sstring_gap2 = ini_string[::3] # printing result print ("print resultant substring from start", sstring_alt) print ("print resultant substring from end", sstring_gap2) Example 3: We’ll look at both taking a string from the middle and taking a string with a positional space between characters in this example. Python3 code to demonstrate how to create a substring from a string # Python3 code to demonstrate to create a substring from string # Initialising string ini_string = 'xbzefdgstb' # printing initial string and character print ("initial_strings : ", ini_string) # creating substring by taking element # after certain position gap # in defined length sstring = ini_string[2:7:2] # printing result print ("print resultant substring", sstring) Conclusion A substring is a subsection of a longer string. You can use the slicing syntax to get a substring. In addition, slicing allows you to choose a character range to retrieve. A third argument can be used to skip over specific characters in a range.
https://www.codeunderscored.com/python-substring/
CC-MAIN-2022-21
refinedweb
2,013
62.27
object SalaryComputation { trait Source { type E val salaried: List[E] val salCalculator: (E => Double) } class Context { val payees = new ArrayBuffer[Source] def addSource[T](p: List[T], salCalc: (T => Double)) = { payees += new Source { type E = T val salaried = p val salCalculator = salCalc } } } def compute = { val emps = List[Employee]( //.. ) val cemps = List[Contractor]( //.. ) val c = new Context() c.addSource(emps, (e: Employee) => (e.monthlyBasic + e.allowance - e.monthlyBasic * 0.3)) c.addSource(cemps, (e: Contractor) => (e.hourlyRate * 8 * 20) * 0.7) c.payees.map(p => p.salaried.map(p.salCalculator(_))).foreach(println) } } and the workers are modeled as case classes .. case class Employee(id: Int, name: String, monthlyBasic: Int, allowance: Int) case class Contractor(id: Int, name: String, hourlyRate: Int) case class DailyWorker(id: Int, name: String, dailyRate: Int, overtimeRate: Int) The salary computation part has a separate Sourcecomponent which abstracts the data source and salary computation strategy for one particular class of worker. I can have multiple classes of workers being fed into the salary computation component through multiple instances of the Sourcecomponent. And this aggregation is managed as the Contextof the computation. Have a look at the compute method that adds up Sources into the context and builds up the collection for total computation of salaries. In the above implementation, the trait Sourceabstracts the type of the worker over the collection for which salary will be computed and the salary computation strategy. And both of them are injected when new instances of Sourceare being created in method addSource(). The client interface to the abstraction (in method compute) looks nice and DRY and it works as per expectation. But what about Existential Types ? In one of the recent releases, Scala has introduced existential types, which offers hiding (pack) of concrete types from the user and allows them to manipulate objects using a given name (unpack) and bounds. Keeping aside all type theoretic foundations behind existential types, I found it equally convenient to implement the above model using existential types instead of abstract type members. Here it goes .. object SalaryComputation { case class Source[E](salaried: List[E], salCalculator: (E => Double)) class Context { val payees = new ArrayBuffer[Source[T] forSome { type T }] def addSource[T](p: List[T], salCalc: (T => Double)) = { payees += new Source[T](p, salCalc) } } def compute = { val emps = List[Employee]( //.. ) val cnts = List[Contractor]( //.. ) val c = new Context() c.addSource(emps, (e: Employee) => (e.monthlyBasic + e.allowance - e.monthlyBasic * 0.3)) c.addSource(cnts, (e: Contractor) => (e.hourlyRate * 8 * 20) * 0.7) def calc[T](c: Source[T]) = { c.salaried.map(c.salCalculator(_)) } c.payees.map(calc(_)).foreach(println(_)) } } The Scala book by Artima mentions that existential types have been introduced in Scala mainly for interoperability between Scala and Java's wild card types and raw types. But as I found above, they offer all benefits of type abstraction as abstract type members. Ignoring the stylistic issues, is there any reason to choose one approach over the other in the above implementations ? 4 comments: My gosh, how do you find time to write so much about Scala? Do you use it a _lot_ at work? Hi, the Artima book shows how to use type members to enforce static constraints such as, when animals eat food, cows are only allowed to eat grass (btw: the book also has a very convincing currency example) do you think you can also elegantly impose such static constraints using existential types? Luc Debasish, See what M. Odersky says in a comment on this blog post: Cheers @german: Yeah .. I have seen in many places that generally abstract type members are recommended over existentials. But yet to find any convincing arguments for that. The artima book also mentions that existentials are mainly targetted for interoperating with Java generics. However, I have seen some use cases where I think existentials will make a better cut.
http://debasishg.blogspot.com/2008/05/choosing-between-abstract-type-members.html
CC-MAIN-2017-43
refinedweb
643
55.74
Cursors Cursors represent SQL statements and their results. The connection object provides your application with a cursor via the cursor( ) method: cursor = conn.cursor( ); This cursor is the center of your Python database access. Through the execute( ) method, you send SQL to the database and process any results. The simplest form of database access is, of course, a simple insert: conn = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = conn.cursor( ); cursor.execute("INSERT INTO test (test_id, test_char) VALUES (1, 'test')"); print "Affected rows: ", cursor.rowcount; In this example, the application inserts a new row into the database using the cursor generated by the MySQL connection. It then verifies the insert by printing out the number of rows affected. For inserts, this value should always be 1. Query processing is a little more complex. Again, you use the execute( ) method to send SQL to the database. Instead of checking the affected rows, however, you grab the results from the cursor using one of many fetch methods. Example 10-1 shows a Python program processing a simple query. import MySQLdb; connection = None; try: connection = MySQLdb.connect(host="carthage", user="user", passwd="pass", db="test"); cursor = connection.cursor( ); cursor.execute("SELECT test_id, test_val FROM test ORDER BY test_id"); for row in cursor.fetchall( ): print "Key: ", row[0]; print "Value: ", row[1]; connection.close( ); except: ... Get Managing & Using MySQL, 2nd Edition now with O’Reilly online learning. O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
https://www.oreilly.com/library/view/managing-using/0596002114/ch10s01s02.html
CC-MAIN-2021-04
refinedweb
253
51.55
. Spocket From $0.00 / month Find Dropshipping products from thousands of reliable suppliers in US/Europe/Canada/Asia. Shopify sourcing products, fast-shipping Spreadr App $5.00 / month Import products from Amazon to your Shopify store. Earn commissions via Amazon Affiliate Program or run your dropshipping business.. Aliexpress Dropshipping From $5.00 / month import desired products on various Aliexpress, ebay,overstock,dhgate and many more to your store with ease Pillow Profits Fulfillment $29.99 / month The premier Shopify fulfillment app for selling high-quality custom printed footwear and more!. Printy6 ( Snaprinting) - Print on Demand for Ecommerce and Artist Free Free Online Cusomization Service With Big Profit! Start Selling Your Exclusive Designs Within 10 min! MODALYST From $0.00 / month Dropship millions of trendy, affordable products with fast shipping to your store, including our curated market of US/European suppliers. MXED - Sell Official Pop Culture Merch Custom Sell officially licensed products within your Shopify store. Products from StarWars, Marvel, Harry Potter,etc. Shipped from the USA in 3 day Viralstyle Fulfillment Free The Easiest Way to Create & Sell Custom Products on Shopify. Enjoy Fully Automated Order Fulfillment and Tracking with Viralstyle. Collective Fab From $29.00 / month Add thousands of fashion & beauty dropship products to your store with just a few clicks. Orders are shipped directly to your customers. Teescape Fulfillment Custom Design products and automatically add them to your store, with high-quality printing, fast shipping, and Low Prices!. RageOn Connect Free Design your own merch or choose from 1000s of existing products from 100s of famous brands & artists. Expand your catalog w/ RageOn Connect! Inventory Source Custom Fully Integrate with ANY Dropship Supplier or choose from our 150+ Supplier Directory to auto-upload products and sync inventory. Expressfy $14.95 – $24.95 / month Easily import products from AliExpress directly into your Shopify store, all in just a few clicks! Pixels - Print On Demand Drop Shipping from 15 Global Fulfillment Centers Custom Add hundreds of print-on-demand products to your store and ship to buyers all over the world from our 15 global manufacturing centers. BigBuy EU Dropshipping Free – $29.99 / month Automatically synchronize your inventory with the BigBuy wholesaler dropshipping service.
https://apps.shopify.com/categories/product-sourcing?sortby=popular
CC-MAIN-2018-22
refinedweb
364
50.12
\(\Large\texttt{CF1286E Fedya the Potter Strikes Back }\) It is expected that the theoretical complexity is \ (\ mathcal O(n\alpha(n)) \) and theoretically the table calculation is suspended, but it seems that it is actually not better than the submission of some \ (\ mathcal O(n\log n) \). thinking For the answer that we need to maintain dynamically, first classify all contributing intervals \ ([L, R] \) and make them the contribution of points \ (R \). It is found that it is difficult to directly calculate the contribution of points \ (i \) every time, and consider inheriting the contribution of \ (i - 1 \). In order to facilitate understanding, the concept of suffix tree is introduced here. For points \ (i - 1 \) and \ (i \), their depth on the suffix tree must meet \ (dep_{i} \le dep_{i - 1} + 1 \), that is, adding one character at a time will only increase one border at most, and its length is \ (1 \). Then we consider how to inherit the contribution of \ (i - 1 \) to \ (I \). All points from the point \ (I \) on the suffix tree to the root node must be inherited from all points from the point \ (i - 1 \) on the suffix tree to the root node (except for the border with the length of \ (1 \). That is, we classify all left end points in the interval \ ([L, i] \) in which the point \ (I \) contributes as a set \ (s_, I \), Then \ (S_i \in S_{i - 1} \cup \{i \} \), so we just delete all unsatisfied \ (L \) by force and inherit them directly in \ (S_{i - 1} \), and the maximum total number of deletions is \ (\ mathcal O(n) \). We use the monotone stack to maintain the \ (w_i \) with increasing suffix, because only these elements contribute. In this process, we insert all the current \ (L \in S_i \) into the position that belongs to its contribution \ (w_i \). For inserting new elements \ (w_i \), if it is necessary to merge and delete the top elements of the stack, we can use and query to point them to \ (I \), That is, move the element originally contributed to the top of the stack to \ (I \). For the deletion operation, it is similar to other problem solutions. Maintain an ancestor where the first subsequent character on the suffix tree is different from its own subsequent character. Just jump and delete it violently. code #include <bits/stdc++.h> using namespace std; #define PB push_back // #define int long long #define LL long long #define siz(a) ((int)((a).size())) #define rep(i, a, b) for (int i = (a); i <= (b); ++i) #define per(i, a, b) for (int i = (a); i >= (b); --i) const int N = 6e5; const int M = 100000; const int mod = 1e9 + 7; const int inf = 1e9; int a, nxt[N + 5], w[N + 5], fa[N + 5], top, siz[N + 5], sk[N + 5], lst[N + 5], sz[N + 5]; __int128 ans, tmp; char s[N + 5]; int f(int n) { return fa[n] == n ? n : fa[n] = f(fa[n]); } void merge(int &p1, int &p2) { tmp -= 1ll * w[p2] * siz[p2]; tmp += 1ll * w[p1] * siz[p2]; if(sz[p1] < sz[p2]) swap(p1, p2); w[p1] = min(w[p1], w[p2]); fa[p2] = p1; siz[p1] += siz[p2]; sz[p1] += sz[p2]; } void out(__int128 x){ static int buf[255], len; if(!x) return cout << "0\n", void(); while(x) buf[++len] = x % 10, x /= 10; while(len) cout << (char) (buf[len--] + '0'); cout << "\n"; } signed main() { // freopen("in1.in", "r", stdin); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> a; int j = 0, mx = (1ll << 30) - 1; rep(i, 1, a) { cin >> s[i] >> w[i]; w[i] = (w[i] ^ (ans & mx)); s[i] = (ans + s[i] - 'a') % 26 + 'a'; sk[++top] = i; fa[i] = i; sz[i] = 1; while(top > 1 && w[sk[top]] <= w[sk[top - 1]]) { swap(sk[top], sk[top - 1]); merge(sk[top - 1], sk[top]); --top; } if(i > 1) { lst[i - 1] = ((s[i] == s[j + 1]) ? lst[j] : j); for(; j && s[j + 1] != s[i]; j = nxt[j]) { --siz[f(i - j)]; tmp -= w[f(i - j)]; } for(int k = lst[j]; k; ) { if(s[k + 1] == s[i]) { k = lst[k]; continue; } --siz[f(i - k)]; tmp -= w[f(i - k)]; k = nxt[k]; } if(s[j + 1] == s[i]) ++j; nxt[i] = j; if(s[1] == s[i]) { ++siz[f(i)]; tmp += w[f(i)]; } } ans += tmp + w[f(sk[1])]; out(ans); } return 0; }
https://programmer.ink/think/cf1286e-fedya-the-potter-strikes-back.html
CC-MAIN-2022-05
refinedweb
744
61.09
Earlier this year I was fiddling around with the new J2SE network ProxySelector APIs as part of a small demo-project. Sadly, the project just wouldn't stay small and I didn't have time for something big. So after a few days it disappeared into one of the many corners of my laptop's hard disk, where it's been quietly moldering away. One part of the old demo was a small GUI for collecting network proxy host names and port numbers. I'd used JFormattedTextFields for the latter. You might think that doing so would have been trivial, since port numbers are just integers between 0 and 65534 and JFormattedTextField is very, well, flexible. It turns out to have been not so trivial and at the time I was inspired to write a blog-sized article about exactly what I'd done. That article would have remained buried with everything else from the project if it hadn't been for some interesting JFormattedTextField threads on the javadesktop.org JDNC forum that cropped up recently. The problem that inspired the JDNC JFormattedTextField thread had to do with decimals (like 123.45). Since I'd spent some time in the trenches with a similar problem, I thought it might be fun to exhume my old article and toss it on the pyre. So here it is. Warning: if you're looking for the material about JFormattedTextField you can skip the first couple of paragraphs. I've left the first couple of paragraphs the way they were out of respect for the dead. Plus, I'm too lazy to edit them out. Before writing more than a few lines of code I considered structuring the ProxyPanel component conventionally: with careful separation of model and view, and with great flexibility for all dimensions of both. The model would be a Java Bean that included all of the data required to completely specify the usual set of networking proxies along with all of the secondary data like overrides and user names and passwords. The bean's API would be specified as an interface, so that the ProxyPanel could operate directly on application data, and an abstract class would provide a simple backing store for the data along with all of the change listener machinery required to keep the GUI view in sync. The view would be equally overdesigned. It would be configurable, to accommodate applications that wanted a compact or subsetted presentation. And just before I awoke from my second system syndrome induced reveries, I imagined providing an XML schema that could be used to completely configure and (cue the Mormon Tabernacle choir) even localize the GUI. This was supposed to be a tiny project aimed at highlighting the new ProxySelector APIs and providing a small coding diversion for yours truly. So, after I'd calmed down, I decided to write a simple GUI that wasn't terribly configurable and that lacked a pluggable model. That's right: no model/view separation here. If there are MVC gods, I'm sure I'll be in for some smiting. And if the gods can't be bothered, then I'm confident that my more dogmatic brethren will take up the slack. Please don't send your self-righteous segregationist rantings about the merits of MVC to me. I know, I know. My first cut at structuring the code for the four pairs of proxy host/port fields that correspond to the bulk of the GUI was to create a little internal class that defined the GUI for just one proxy, in terms of four components: public class ProxyPanel extends JPanel { private ProxyUI httpUI; private ProxyUI httpsUI; // ProxyPanel constructor initializes httpUI etc ... private static class ProxyUI { private final JLabel hostLabel; private final JTextField hostField; private final JLabel portLabel; private final JFormattedTextField portField; ProxyUI (ProxyPanel panel, String hostTitle, String host, String portTitle, int port) { // create labels, fields, and update the GridBagLayout } String getHostName() { return hostField.getText(); } // ... } } The ProxyPanel created four ProxyUI instances and squirreled them away in four private ProxyPanel ivars. The ProxyUI class did encapsulate the details of how one proxy was presented to the user. On the down side, had to assume that the ProxyPanel had a GridBagLayout (no encapsulation there) and it felt gratuitously complicated. One lesson I learned as part of building this first revision of ProxyPanel was how to configure a JFormattedTextField that accepted either a integer between 0 and 65534 or an empty string. The latter indicated that the user hadn't provided a valid value. It seemed like it would a little less surprising for users to map no-value or invalid values to a blank than to insert a valid default value like 0. JFormattedTextFields are eminently configurable and if you'd like to get acquainted with the API I'd recommend the Java Tutorial. The specific problem I was trying to solve isn't covered there however with a little help from the local cognoscenti I was able to work things out. The Swing class that takes care of converting to and from strings as well as validating same, is called a formatter and the subclass needed for numbers is called NumberFormatter. A separate java.text class called DecimalFormat is delegated the job of doing the actual string conversions and it provides its own myriad of options for specifying exactly how our decimal is to be presented. Fortunately in this case we don't need to avail ourselves of much of that, in fact we're going to defeat DecimalFormat's very capable features for rendering numbers in a locale specific way. What we need is just a geek friendly 16 bit unsigned integer. Or a blank. Here's the code for our JFormattedTextField instance. We override NumberFormatter's stringToValue method to map "" (empty string) to null. The ProxyPanel.getPort() method that reads this field will map null to -1, to indicate that the user hasn't provided a valid value. DecimalFormat df = new DecimalFormat("#####"); NumberFormatter nf = new NumberFormatter(df) { public String valueToString(Object iv) throws ParseException { if ((iv == null) || (((Integer)iv).intValue() == -1)) { return ""; } else { return super.valueToString(iv); } } public Object stringToValue(String text) throws ParseException { if ("".equals(text)) { return null; } return super.stringToValue(text); } }; nf.setMinimum(0); nf.setMaximum(65534); nf.setValueClass(Integer.class); portField = new JFormattedTextField(nf); portField.setColumns(5); It occurred to me that perhaps an IntegerTextField would be worthwhile. That way one could write: IntegerTextField inf = new IntegerTextField(); itf.setMinimum(0); itf.setMaximum(65534); itf.setEmptyOK(true); itf.setEmptyValue(-1); // new feature, "" => -1 itf.setValue(0); I don't think that's a vast improvement however developers might have an easier time sorting out how to create an IntegerTextField than assembling the right combination of DecimalFormat, NumberFormatter, and FormattedTextField. Of course, having gone so far as to create IntegerTextField we'd want similar classes for currency values, real numbers, dates, and so on. Some of this is already covered by JSpinner although spinners are better suited to cycling through relatively small sets of values. It's been a long time since I wrote all of that. Looking back I'd have to say that a set of classes, like IntegerTextField, would certainly make life more straightforward for Swing developers. Hopefully the SwingLabs project will take up the cause and maybe in the future a collection of battle-hardened special purpose text fields will find their way into the JDK. If they do, I'll use them. Hi, Really I was waiting a wonderfull FormattedTextField, with things solved for the basic types like int, double, Date. I had my own simple Documents to obtain in some way the same result. Now it arrive, since it's arrived I'm trying to find how people who give as java, swing and a lot of wonderfull frameworks could have mis the point so much. Every Time a try to use this component I get a lot of trouble, it is not intuitive, an take care if you want to manage FocusEvents arround it, really disapointing, my old documents are back, and the new methods for handling Document features are really much more powerful and understanble tha this awfull Component. If this was a vote pool, I'll say: Take it out, write it again, pleeeeeeeeease !!!!!!!! Posted by: tonioc on August 27, 2005 at 11:08 AM Twenty-eight months later... These incredibly useful components are still missing from Swing. :-( Posted by: fredswartz on December 07, 2007 at 03:22 AM
http://weblogs.java.net/blog/hansmuller/archive/2005/08/using_swings_jf.html
crawl-002
refinedweb
1,415
52.19
The hooks API is a wonderful idea. There are some slick patterns involved that push the React development to a more functional approach. I'm interested in trying that new API and decided to use it for my latest project. However, after a couple of days, it looked like I can't build my app only with hooks. I needed something else. And that's mainly because each hook works on a local component level. I can't really transfer state or exchange reducers between the components. That's why I created Jolly Roger. It has similar helpers but works on a global app level. Sharing state Let's have a look at the following example: import react, { useEffect, useState } from 'react'; const App = function () { const [ time, setTime ] = useState(new Date()); useEffect(() => { setInterval(() => setTime(new Date()), 1000); }, []) return ( ... ); } It's a component that has a local state called time. Once we mount it we trigger an interval callback and change the state every second. Now imagine that we want to use the value of time in other components - Clock and a Watch. There are somewhere deeper in our React tree and we can't just pass the time around: function Clock() { const [ time ] = useState(<?>); return <p>Clock: { time.toTimeString() }</p>; } function Watch() { const [ time ] = useState(<?>); return <p>Watch: { time.toTimeString() }</p>; } That's not really possible because the idea of the useState hook is to create a local component state. So time is available only for the App but not Clock and Watch. This is the first problem that Jolly Roger solves. It gives you a mechanism to share state between components. function Clock() { const [ time ] = roger.useState('time'); return <p>Clock: { time.toTimeString() }</p>; } function Watch() { const [ time ] = roger.useState('time'); return <p>Watch: { time.toTimeString() }</p>; } const App = function () { const [ time, setTime ] = roger.useState('time', new Date()); useEffect(() => { setInterval(() => setTime(new Date()), 1000); }, []) return ( <Fragment> <Clock /> <Watch /> </Fragment> ); } Here is a online demo. The API is almost the same except that we have to give the state a name. In this case that is the first argument of the Roger's useState equal to time. We have to give it a name because we need an identifier to access it from within the other components. Using a reducer Now when we have a global state we may define a reducer for it. You know that nice function that accepts your current state and an action and returns the new version of the state in immutable fashion. Let's build on top of the previous example and say that we will set the time manually. We are going to dispatch an action giving the new time value and the reducer has to update the state. roger.useReducer('time', { yohoho(currentTime, payload) { console.log('Last update at ' + currentTime); console.log('New ' + payload.now); return payload.now; } }); Again the important bit here is the name time because that's how Roger knows which slice of the application state to manipulate. In here we are creating an action with a name yohoho that receives the current time and some payload. In this example we don't want to do anything else but simply set a new time so we just return what's in the now field. We will also create a new component that will trigger this action: function SetNewTime() { const { yohoho } = roger.useContext(); return ( <button onClick={ () => yohoho({ now: new Date() }) }> click me </button> ); } Here is a online demo to play with. What is useContext we'll see in the next section. Using the context Because Roger works as a global singleton it can store some stuff for you. By default the actions that we define in our useReducer calls are automatically stored there. As we saw in the previous section the yohoho method is used by getting it from the Roger's context. We can do that with the help of the useContext method. Let's continue with our little time app and get the time from an external API via a fetch call. In this case we may create a function in the Roger's context that does the async request for us and fires the yohoho action. roger.context({ async getTime(url, { yohoho }) { const result = await fetch(url); const data = await result.json(); yohoho({ now: new Date(data.now)}) } }); Every context method accepts two arguments. The first one is reserved for anything that needs to be injected as a dependency and the second one is always the Roger's context itself. In our case getTime has one dependency and that's the endpoint URL. We need the yohoho action which is defined in our useReducer call. We get the data and dispatch the action. This updates the application state and makes the component re-render. Here is the same <SetNewTime> component using the new getTime helper: function SetNewTime() { const [ inProgress, setProgress ] = useState(false); const { getTime } = roger.useContext(); const onClick = async () => { setProgress(true); await getTime(''); setProgress(false); } return ( <button onClick={ onClick } disabled={ inProgress }> { inProgress ? 'getting the time' : 'click me' } </button> ); } Notice that Jolly Roger plays absolutely fine with the native React hooks. Like we did here we are setting an inProgress flag to indicate that there is a request in progress. Check out how it works here. You like it? If you like what you are seeing you may be interested in checking the repository of the library. There is the full API described. Also here is the Jolly Roger visualized.
http://outset.ws/blog/article/jolly-roger-2kb-micro-framework-react-hooks-api
CC-MAIN-2019-51
refinedweb
912
66.84
Can You Trust Your JVM Diagnostic Tools? - Nathaniel Carpenter - 3 years ago - Views: Transcription 1 Can You Trust Your JVM Diagnostic Tools? Isaac Sjoblom, Tim S. Snyder, and Elena Machkasova Computer Science Discipline University of Minnesota Morris Morris, MN Abstract Programmers may use Java diagnostic tools to determine the efficiency of their programs, to find bottlenecks, to study program behavior, or for many other reasons. Some of the common behavior, running the HotSpot JVM with an option for logging its internal compilation and optimization process. 2 1 Introduction Java programming language is executed by an interpreter known as the Java Virtual Machine (JVM). Modern JVMs are equipped with sophisticated tools for dynamic program optimization that profile and optimize the program as it is being executed. In this complex setup, monitoring a program by trying to examine its run-time behavior becomes quite challenging. The reason for this is that the monitoring tool and the JVM that is running and optimizing the program all share the same resources (CPU, cache, etc). This may create an observer effect : the change in the program behavior when it is being executed together with a monitoring tool, whether embedded into the JVM itself or an external one. In this project we are interested in studying Java program behavior caused by a certain inheritance pattern related to generic types that we refer to as bound narrowing. Programs with bound narrowing that are very similar to each other exhibit different behavior in terms of their run time. While trying to explain the differences, we tried various Java diagnostics tools, both stand-alone (such as HPROF profiler) and those embedded into the HotSpot TM VM. In particular, we explored a log compilation option available in the HotSpot JVM. This option keeps a detailed log of optimizations performed at the run time. We present the observations about the accuracy and usefulness of the monitoring tools, using bound narrowing examples as a case study. We show that most of the programs are stable with respect to the monitoring tools considered in this paper, i.e. relative times in a group of programs remain the same regardless of the tools (although constant differences in times for the entire groups have been observed). However, some programs are unstable, i.e. their behavior patterns change depending on whether they run in the JVM under default conditions or with a monitoring tool. In fact, some programs behave differently when executed repeatedly in the JVM with the log compilation option. Since this option produces a detailed log of both successful optimizations and failed attempts, we were able to determine what causes the differences in behavior based on these logs. 2 Java Virtual Machine and Diagnostic Tools 2.1 Java Compilation Model Unlike statically compiled languages, in which a program is optimized and compiled into machine code in the same step, Java has a two-phase compilation model. First, the program is compiled by a static compiler, such as Javac, into bytecode for portability. Second, the bytecodes are executed on any system that has a Java execution environment, referred to as the Java Virtual Machine (JVM). The JVM that comes standard with the Java Development Kit (JDK) is called HotSpot TM VM. Most modern JVMs, including HotSpot, are equipped with a Just-in-time compiler (JIT) that performs optimizations as the program is being run and may convert a portion or all of a program s bytecode to native code on the fly. This process is called dynamic compilation. Two common examples of JIT optimizations are constant propagation and inlining. Constant propagation is when references to a constant in a program are replaced with the constant s value. Inlining is when the JIT replaces method calls with all of the method in- 1 3 structions. This removes the method call, and therefore method look up, and allows for further optimizations to take place. Inlining would be similar to copying a whole method and pasting over the call to that method. 2.2 HotSpot Server Just-In-Time (JIT) Compiler The HotSpot JVM features two modes, client and server that differ in their JIT compilers. The server mode provides more optimizations than the client mode and as a result may have faster run times than client for longer programs. However, the optimizations may be more time-consuming than those applied by the client mode [6]. The server mode is intended for server-side applications. Client mode is the default for HotSpot on 32-bit architecture. It provides faster application startup and requires less memory than server. It is intended for client-side Java programs, such as applets, and is currently not supported for 64-bit architecture [3]. In this paper we are only considering the server mode. HotSpot JVM provides multithreading support. Multithreading is the parallel execution of a program through various processes, effectively executed by the hardware but may be handled by the virtual machine. When handled by the hardware, the processes are divided between the systems processors. However, our system has one processor to limit variations during dynamic compilation as much as possible. A feature of this JVM is preemptive multithreading based on native threads; that is, that threads defined in a program are handled by the JVM and passed to the operating system for support. We observe that this extends to multithreading JIT compilation, that is, optimizations in JIT compilation may take place in different threads. 2.3 Profilers, HPROF A profiler is a piece of software that observes and interacts with a program to gather information about its execution, such as data on how often methods get called. HPROF is a specific profiler that can run in two different modes, sampling mode and method counting mode [2]. Sampling mode will run by finding out what the stack is like at certain time intervals to get an estimate for how often methods are being called and where they are on the stack most. Method counting mode, on the other hand, will count how often methods get called by putting in at least one line of code that creates a counter in the method that increments on each call. This approach is called bytecode injection. Method counting mode causes a drastic increase in run time due to an overhead of counting. In addition inlining is disabled because of bytecode injection. This is a type of observer effect : observing a program by means of a profiler changes its behavior [1]. 2.4 Internal JVM Diagnostics Internal JVM diagnostic tools were created by the JVM developers to provide themselves access to various internal JVM information. These tools were not developed for Java programmers, which may be the reason that the internal JVM diagnostic tools are somewhat under-documented and not guaranteed to work for every JVM distribution [5]. 2 4 HashMap::putAll (133 bytes) 15 NarrowedIS::put (13 bytes) 16 NarrowedIS::put (38 bytes) 1% 90 (133 bytes) 17 HashMap::entrySet0 (28 bytes) 18 HashMap$EntrySet::iterator (8 bytes) 19 HashMap::newEntryIterator (10 bytes) HashMap::putAll (133 bytes) 15 NarrowedIS::put (13 bytes) 16 NarrowedIS::put (38 bytes) 17 HashMap::entrySet0 (28 bytes) 18 HashMap$EntrySet::iterator (8 bytes) 19 HashMap::newEntryIterator (10 bytes)... Figure 1: Showing different results for print compilation for two runs of the same program (only a fragment shown). Two of the relevant diagnostic tools we were using are Print Compilation and Log Compilation. They are both flags provided by the JVM. On the command line the flags look like this [5]: -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation When the print compilation flag is turned on, a message is printed whenever JIT translates a method into machine code. This flag provides some information about the JIT behavior, but its output format does not have a clear publicly available documentation and the results can be confusing. An example of this is the field size of method in bytes where the number associated with this field is, as evidence suggests, a somewhat arbitrary number to approximate the size of the method but does not have a clear definition. A method is often compiled to native code more than once, with different byte sizes. An additional complication arises from the fact that output of print compilation differs for multiple runs of the same program, even if the runs take the same time, as demonstrated in Figure 1. In Figure 1 we show a partial print compilation output for two runs of the same program that resulted in the same running times. We see that between lines 16 and 17 of the output of the first run there is a reference to HashMap::putAll that does not appear in the second run s output. The log compilation flag turns on logging of the compilation process: when and in what order program code is translated into bytecode, optimized and translated into native code where applicable. It also records the information about threads of the JIT compiler and which tasks they perform. When the log compilation flag is turned on, a second flag, unlock 3 5 diagnostics, must also be turned on. The log is written as a large XML file recording every action of the JIT, with timestamps. This option produces accurate detailed information for analyzing program behavior. However, we have observed that using these flags leads to changes in the behavior of some programs, most likely due to recording information forced by unlocking the JVM diagnostics See section 5 for more details. 3 Effects of Bound Narrowing 3.1 Generic Types in Java Generic types are a feature of Java that allows writing program code that is parameterized over types. For example, generic types allow creation of a Stack class that that allows instances of Stack to be constructed with any object such as strings or integers, but will not allow mixing strings and integers in the same instance of Stack. In this case String or Integer class are referred to as type parameters for the generic Stack class. An example of generic types is the following class: public class HashMap<K, V> HashMap has two type parameters, a key type K and a value type V. An example of the instantiation of HashMap would be: HashMap<K,V> myhashmap = new HashMap<Integer,String>(); Here, we instantiate HashMap with an Integer for a key and a String for a value. This limits the instance of this class myhashmap to only be used with an Integer for a key and a String for a value. There can also be type bounds placed on generic types. A type bound is a class or interface that limits the generic parameters to that class or subtypes of that class or interface. public class ComparableHashMap<K extends Comparable, V extends Comparable> This ensures that the key and the value are of types that implement Comparable interface. Implementations of HashMap allow for construction of an instance involving any class for the key or the value. ComparableHashMap has a more strict implementation where the construction of an instance demands a Comparable or a subtype of Comparable for the key and value. Generic types may be subtypes of other generic types. Commonly the type bound of a subtype is the same as the type bound of its supertype. However, Java allows for the subtype to have a more restrictive bound than its supertype; also, a non-generic class may inherit from a generic class or interface by hard-wiring a specific type for a type parameter. We refer to these inheritance patterns as bound narrowing. An example of bound narrowing where a non-generic class is inheriting from a generic class is the following: public class NarrowedHashMap extends HashMap <Integer, String> 4 6 Here, NarrowedHashMap inherits from the class HashMap where the key and value are specifically Integer and String, respectively. 3.2 Delays Associated with Bound Narrowing In our previous research, we found that bound narrowing causes substantial runtime inefficiencies when the JIT is disabled. When bound narrowing is present, the system has to verify that objects passed to a method of a more specific (narrowed) container by a call to a method of its more general supertype are of the correct type. When the JIT is not allowed to perform the necessary optimizations such as inlining, described above, these type checks have to be performed every time an object is placed into a container. We have found that some of these delays will go away in runs under default HotSpot JVM conditions (with the JIT optimizations on) while others remain. In the current research, we are continuing to study bound narrowing, specifically when the delays remain and why [7]. 3.3 Test Cases The code that we have been testing is based on the HashMap class in the Java collections library. We chose this code base because of a specific class called PrinterStateReasons that is a part of the javax package. The reason that PrinterStateReasons is important to us is because it is a narrowed version of the generic HashMap and is a real-life example of bound narrowing. Below, we are showing only relevant fragments of code. public final class PrinterStateReasons extends HashMap<PrinterStateReason, Severity> The bound here is on the way down from HashMap because the PrinterStateReasons class has a more specific bound than the generic HashMap. PrinterStateReason is a class that provides information about a printer s current state while Severity provides information on how severe that state is. Our version of this code uses Integer and String instead since PrinterStateReason and Severity have a limited number of instances. Our test code accesses the class being tested via an interface, Map, with a key and a value both bounded to Object. We have a class, HashMap, that implements this interface that is still completely generic. These classes are copies of the standard Java collection packages and PrinterStateReasons with our own methods added as needed. public class HashMap<K,V> extends Map <K, V> Our test classes, which are the four subclasses in the table below, all extend HashMap and are based off of the PrinterStateReasons class. Each of these has a different bound combination as seen in the table below. Name Notation Key Value NarrowedIS NIS Integer String GenericKeyIS GKIS Object String GenericValueIS GVIS Integer Object GenericKeyValueIS GKVIS Object Object 5 7 We define four versions of the testing code, one per each of the test classes above, that test our code base by repeatedly calling a method in order to determine its running time. Our tests start with the generic Map interface instantiated as one of our four classes. We then call a method on the interface and the call gets passed down to the specific class. The narrowing happens on the arguments passed from the method in Map to the method in our specific class. The check happens in those classes because in Map the arguments are bound to Object while the narrowed classes are bound to either Integer or String. Note that the type check may be optimized away by the JIT (see Section 3.2). Our test cases, the methods that we are calling in our test classes, for the most part, use a pair of methods that perform an item-by-item search through the HashMap to try to find either a key or value equal to what we pass in. An example of this is the containsvalue method shown below. This is just one of many different methods that we have tested. public boolean containsvalue(v value) { Entry[] tab = table; for (int i = 0; i < tab.length; i++) for (Entry e = tab[i]; e!= null; e = e.next) if (value.equals(e.value)) return true; return false; } This method is a copy of the method in HashMap which we duplicated for studying purposes. The table variable is the array of type Entry that HashMap uses to store its data. Between the four classes of ours, two (NIS and GKIS) have the String type bound for V, and the other two have the Object type bound. Consequently the type of the parameter value in the bytecode is String in NIS and GKIS and Object in GVIS and GKVIS. Map<Integer, String> map = new GKVIS<Integer, String>(); initmap(size, keys, values, map); boolean result = true; double timestart = System.currentTimeMillis() / ; for (int i = 0; i < outerloops; i++) { for (int j = 0; j < 10000; j++) { result &= map.containsvalue(values[j % size]); } } double timeend = System.currentTimeMillis() / ; if (result) { System.out.println(timeEnd - timestart); } initmap() will add items to our Map from our set of keys and values until we reach the size that we pass in. The given arrays have only four distinct elements (repeatedly added to the HashMap as needed) to eliminate the need for garbage collection and thus to guarantee that the running times are not affected by it. We record the start time before we run our 6 8 tests, and then record it again right before the program finishes. The result variable (a boolean) alternates between true and false in the loop and is used after the loop (with the value true since the loop runs an even number of times). We use this dummy variable result so that the JIT compiler does not optimize the method calls away entirely since the JVM compiler will eliminate method calls as useless code if there is no side-effect from the call. In order to obtain running times on the order of seconds, we loop over method calls a large number of times (200,000,000 in examples in this paper). This allows us to accurately measure the differences in time between the test classes. We separate the iteration into doubly nested for loops for easier control of the number loops (the outer loop counter is set as a flag for the test runs). 3.4 Other Test Cases The other methods in HashMap hierarchy that we tested are listed below: IS-put-inl is the same method as put in HashMap, with the test method for it manually inlined into the classes that we are testing, such as NIS, GKIS, etc. The reason for manually inlining the testing method was to explore a particular way of parameter passing in the program. IS-contains-v-inl is the same method as IS-contains-v, with the test method inlined in the same way as IS-put-inl. II-contains-v-inl is the same method IS-contains-v except the type of value is Integer instead of String and its testing method is inlined in the same way as IS-put-inl. 4 Effects and Accuracy of Java Monitoring Tools 4.1 Pattern Classification for Test Cases and Program Stability In our tests we have come across different patterns of time differences between the four test classes, three of which come up in the tests that we describe in this paper. First, there is a no significant difference pattern which is a run where the four classes all run in the same times (we consider differences under 0.4 sec to be non-significant, although most cases in this category are much tighter, often within 0.1 sec). Second, there is the bound narrowing pattern that manifests the bound narrowing delay described in Section 3.2, where the runs with the narrowed value (NIS and GKIS) are slower than the generic runs ( GVIS and GKVIS). The final pattern is what we call the value pattern. The value pattern is where the narrowed value classes are faster than the generic classes. In these runs the JIT successfully optimizes away the bound narrowing delay and then takes advantage of knowing the exact class that the equals method in containsvalue (and in similar methods) is called on. 7 9 The exact target class information allows JIT to inline the method, leading to faster runs for the narrowed tests 1. Our goal is to determine why some runs display a specific pattern. We also discovered that some test cases act differently under different testing conditions, for instance displaying the bound narrowing pattern under the default conditions and the value pattern when tested with HPROF. We refer to runs that exhibit the same pattern for all testing methods (i.e. the default mode of testing, HPROF, Print Compilation and Log Compilation) as stable, and to those that have different patterns as unstable. An unstable test case may also have two different behaviors in the same mode of testing in different tries. In our experience this may happen in Log Compilation tests. In the remainder of the section we show results for some stable and some unstable runs for different ways of testing and discuss the result. All tests are run on the same machine in /tmp to ensure that network problems do not interfere with the tests. Below are the machine and the JVM specifications: AMD AthlonTM 64 Processor MB DDR RAM Fedora Core 7 Kernel: fc7 SMP i686 Java Version: Sun JDK Time Binary: GNU time 1.7 We use the taskset command to pin the JVM process (and all of its subprocesses) to one CPU. 4.2 Results for Default Conditions. In this section we show the results of running the four test cases described in Sections 3.3 and 3.4 under the default conditions in the server mode of the HotSpot JVM. Figure 2 shows the graph for containsvalue corresponding to the data in the table. The graph exhibits the bound narrowing pattern. Due to lack of space we are not showing the graphs for the other three test cases and just summarize all four results in the table: Name NIS GKIS GVIS GKVIS Pattern contains-v BN put-inl BN contains-v-inl Value NII GKII GVII GKVII contains-v-inl No-diff The first column is the name of the test case: containsvalue is the test class explained in Section 3.3, and the other four runs are described in Section 3.4. We make 200,000,000 method calls for each method being tested in each of the four test classes. The numbers 1 In tests that call equals method on a key and not on a value we also found a key pattern which is the same as the value pattern, but it is sped up on runs with a narrowed key (NIS and GVIS) instead of a narrowed value. Due to space limitations we are not describing these tests in the paper. 8 10 CPU Time (sec.) NIS 2GKIS 3GVIS 4GKVIS Server: IS contains v inl , JVM Figure 2: containsvalue, default HotSpot conditions: bound narrowing pattern. are the averages of program running times, in seconds, for 20 repetitions of each test class. The last column shows which pattern the test case follows: BN stands for the bound narrowing pattern, Value stands for the value pattern and No-diff means that there were no significant difference between the four runs. 4.3 Results for HPROF in Method Sampling Mode Figure 3 shows the results of running the IS-contains-v test case with the HPROF profiler in the sampling mode (described in Section 2.3). Not surprisingly, the running time is more that twice that of the original s. This is due to the overhead of collecting the stack sampling information as the program is running. Quite surprisingly, however, the test exhibits the value pattern: the code versions specialized in the value run faster than those with a generic value. This contrasts the bound narrowing pattern of this test under the default conditions. The difference in pattern can clearly be characterized as an observer effect. However, this observer effect is surprising for two reasons. Firstly, unlike the counter mode of HPROF, the sampling mode does not perform bytecode injection. The sampling of the program stack is performed independently from the program itself. Although it requires stopping the program every once in a while to record the contents of the stack, this only adds a constant factor to the program running time and should not affect the relative running times of the four different versions. The second reason this result is unexpected is that most of our test cases (including all three of the comparison runs) are stable with respect to HPROF, i.e. they preserve their default pattern 2 The table below summarizes the results for all four 2 We observed a similar instability in a test similar to IS-contains-v, not shown due to lack of space. 9 11 CPU Time (sec.) NIS 2GKIS 3GVIS 4GKVIS Server: IS contains v inl , JVM with HPROF in sampling mode Figure 3: containsvalue, HPROF in Method Sampling: value pattern test cases. The measurements are determined exactly the same as for the default conditions, except each run is repeated 5 times, not 20. Name NIS GKIS GVIS GKVIS Pattern contains-v Value put-inl BN contains-v-inl Value NII GKII GVII GKVII contains-v-inl No-diff 4.4 Results for Print Compilation and Log Compilation Flags Print compilation results do not change the running time for any of the test cases we have tried, and therefore we are not including its results. Log compilation, however, leads to interesting results for IS-contains-v, see Figure4. Some of the results exhibit bound narrowing pattern, and some have value pattern. These results confirm the fact that IS-contains-v is unstable. They also provide us with compilation logs for both of the patterns that allow us to study the differences in JIT behavior between the bound narrowing and the value pattern of the same program. Section 5 shows the important fragments of the logs and provides discussion. Note that the other three runs are stable, i.e. preserve the default pattern, as shown in the table below. The averages are for five runs per test class. 10 12 CPU Time (sec.) NIS 2GKIS 3GVIS 4GKVIS Server: IS contains v inl , JVM with LogCompilation Figure 4: containsvalue, Log Compilation: split between bound narrowing and value patterns Name NIS GKIS GVIS GKVIS Pattern contains-v 2: : : : Unstable put-inl BN contains-v-inl Value NII GKII GVII GKVII contains-v-inl No-diff 5 Analysis of Compilation Logs and Implications 5.1 Compilation Logs We have provided a sample of two of the logs obtained by the Log Compilation tests of IS-contains-v for the NIS run: one faster run at seconds and one slower run at seconds. We are only showing fragments of the logs for space and clarity reasons since the logs themselves are large XML files. The first of these is a run that exhibited the value pattern and the second exhibited the bound narrowing pattern. For more in depth explanations of the log compilation terms, see [4]. FASTER RUN: First Thread: <klass id="511" name="java/lang/object" flags="1"/> <method id="609" holder="533" name="equals" return="486" 11 13 <call method="609" count="4188" prof_factor="1" inline="1"/> <method id="610" holder="533" name="equals" return="486" arguments="511" flags="1" bytes="88" iicount="6612"/> <call method="610" count="4189" prof_factor="1" inline="1"/> Second Thread: <task compile_id="1" compile_kind="osr" method="testnarrowedis main ([Ljava/lang/String;)V" bytes="2330" count="1" backedge_count="14564" iicount="1" osr_bci="942" stamp="0.125"> <method id="715" holder="533" name="equals" return="486" arguments="511" flags="1" bytes="88" iicount="6612"/> <call method="715" count="4189" prof_factor="1" inline="1"/> SLOWER RUN: <task compile_id="1" compile_kind="osr" method="testnarrowedis main ([Ljava/lang/String;)V" bytes="2330" count="10000" backedge_count="5803" iicount="1" osr_bci="942" stamp="0.131"> <klass id="511" name="java/lang/object" flags="1"/> <method id="707" holder="603" name="containsvalue" return="486" arguments="511" flags="4161" bytes="9" compile_id="2" compiler="c2" level="2" iicount="10000"/> <dependency type="unique_concrete_method" ctxk="603" x="707"/> <call method="707" count="35620" prof_factor="1" inline="1"/> <inline_fail reason="already compiled into a big method"/> The abbreviation osr, as seen in the samples, is short for on-stack replacement. On-stack replacement is the process of replacing a method with its more optimized version directly on the program stack as the program is being executed. Log Compilation shows that the JIT runs two separate threads that start at the same time. Our observations show that there is no significance to a particular operation taking place in the first or the second thread. However, we have found that second thread will typically have the optimizations for faster runs. The iicount and backedge count are for how many times the method in question gets called, but they do not seem to be very important. The key is whether or not the test case gets inlined into the calling context successfully. The first run, the faster of the two and showing the value pattern, inlines containsvalue into main first, and it later inlines equals into containsvalue. The second run, the slower of the two and showing the bound narrowing pattern, does things the opposite way, inlining equals into containsvalue first. However, when it tries to inline containsvalue into main, it fails with the reason of already compiled into a big method. This fail reason means that containsvalue was too large after it was inlined with equals to be inlined into main. In this specific test, main was the calling context (see the second code fragment in Section 3.3) of containsvalue. 12 14 The logs for the tests we ran fall under one of three different categories. If, as is the case for IS-put-inl the narrowed test classes fail to inline into the calling context, we get the bound narrowing pattern. IS-put-inl is a more complicated method, and we do not have complete analysis of its compilation log at this point. We observed that in the case of IS-contains-v-inl the narrowed test classes succeed in inlining the testing method into the calling context, but the generic ones fail. This corresponds to the value pattern (the narrowed classes are faster than the generic ones). Finally, when all four of the classes succeed in inlining into the calling context, we get the no significant difference pattern which is the case for II-contains-v-inl. 5.2 Analysis of Compilation Logs and Hypotheses In our analysis of the compilation logs, we have come up with a hypothesis to explain the three different patterns that we have seen. No significant difference shows up if the compilation log has both the narrowed and generic classes succeed in inlining the test case into its calling context. The value pattern shows up if the inlining of the generic classes fails and the inlining of the narrowed succeeds. Bound narrowing shows up if narrowed classes fail to inline the tested method into the calling context, regardless of whether the generic classes succeeds or fails to inline the test case. We have found that if generic fails to inline and narrowed fails, then it shows bound narrowing. We have reason to believe that if generic succeeds inlining then the bound narrowing will be more extreme. In addition, we have observed that test runs with an Integer bound for a value (rather than the String, as in most of our examples) are stable and fall into value pattern or no significant difference, except on put runs. We believe that the reason for this is because the method size of equals in Integer is smaller which make the inlining of the method work irregardless of order. The exception being put because the methods for those runs are larger and fail to inline. 6 Conclusions and Future Work The table below shows the summary of comparing different diagnostic methods: Diagnostic Method Time Change Pattern Change Information Amount Print Compilation no time change no pattern change some hprof(sampling) approximately doubles times can change patterns moderate amount hprof(counting) drastic increase significantly inaccurate Log Compilation no significant change can change the pattern detailed, accurate Print compilation is the method with the least impact, but it does not produce enough information to be able to detect important optimizations, in particular inlining. As shown in [1], HPROF in the method counter mode creates a drastic time increase and may disable inlining, therefore it is not useful for our purposes. The sampling mode of HPROF increases the running times by a moderate amount. However, it may change the behavior of unstable 13 15 programs. Finally, log compilation produces helpful information, but may also change the behavior of unstable programs. We observed that unstable programs may produce different running times in repeated runs with log compilation. We were able to analyze the logs for two runs with the log compilation option that resulted in two different running times. The logs gave us an insight into the behavior related to the bound narrowing inheritance. We were able to identify a sequence of optimizations that leads to failure to inline the method under testing. We developed a hypothesis for explaining the distinction in patterns for our current set of tests. Future work includes analysis of more compilation logs with the goal of generalizing the patterns to other tests, such as those that use put methods which we currently cannot explain. We also plan to check the dependency of this approach on the maximum method size for inlining by setting the JVM flag that controls this parameter. Another promising direction to explore is multithreading in JIT: we can set the number of threads and thus get an indirect control over thread scheduling. Finally, we plan to identify code patterns that lead to program instability. It may be wise to advise programmers to avoid these patterns. References [1] MACHKASOVA, E., ARHELGER, K., AND TRINCIANTE, F. The observer effect of profiling on dynamic java optimizations. In OOPSLA Companion (2009), pp [2] O HAIR, K. HPROF: A Heap/CPU Profiling Tool in J2SE 5.0, [3] ORACLE TECHNOLOGY NETWORK. Frequently Asked Questions About the Java HotSpot VM. [4] ORACLE TECHNOLOGY NETWORK. HotSpot Glossary of Terms. [5] ORACLE TECHNOLOGY NETWORK. Java hotspot vm options. ORACLE. [6] SUN DEVELOPER NETWORK. The java hotspot performance engine architecture. Sun Microsystem (2007). [7] TRINCIANTE, F., SJOBLOM, I., AND MACHKASOVA, E. Choosing efficient inheritance patterns for java generics. In MICS 2010 (2010), pp, Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,. 1. Overview of the Java Language 1. Overview of the Java Language What Is the Java Technology? Java technology is: A programming language A development environment An application environment A deployment environment It is similar in syntax Java Coding Practices for Improved Application Performance 1 Java Coding Practices for Improved Application Performance Lloyd Hagemo Senior Director Application Infrastructure Management Group Candle Corporation In the beginning, Java became the language of the Habanero Extreme Scale Software Research Project Habanero Extreme Scale Software Research Project Comp215: Java Method Dispatch Zoran Budimlić (Rice University) Always remember that you are absolutely unique. Just like everyone else. - Margaret Mead Java and Real Time Storage Applications Java and Real Time Storage Applications Gary Mueller Janet Borzuchowski 1 Flavors of Java for Embedded Systems Software Java Virtual Machine(JVM) Compiled Java Hardware Java Virtual Machine Java Virtual Java Garbage Collection Basics Java Garbage Collection Basics Overview Purpose This tutorial covers the basics of how Garbage Collection works with the Hotspot JVM. Once you have learned how the garbage collector functions, learn how Online Recruitment System 1. INTRODUCTION 1. INTRODUCTION This project Online Recruitment System is an online website in which jobseekers can register themselves online and apply for job and attend the exam. Online Recruitment System provides NetBeans Profiler is an NetBeans Profiler Exploring the NetBeans Profiler From Installation to a Practical Profiling Example* Gregg Sporar* NetBeans Profiler is an optional feature of the NetBeans IDE. It is a powerful tool Jonathan Worthington Scarborough Linux User Group Jonathan Worthington Scarborough Linux User Group Introduction What does a Virtual Machine do? Hides away the details of the hardware platform and operating system. Defines a common set of instructions. Envox CDP 7.0 Performance Comparison of VoiceXML and Envox Scripts Envox CDP 7.0 Performance Comparison of and Envox Scripts Goal and Conclusion The focus of the testing was to compare the performance of and ENS applications. It was found that and ENS applications have, Tuning WebSphere Application Server ND 7.0. Royal Cyber Inc. Tuning WebSphere Application Server ND 7.0 Royal Cyber Inc. JVM related problems Application server stops responding Server crash Hung process Out of memory condition Performance degradation Check if the Garbage Collection in the Java HotSpot Virtual Machine Printed from Garbage Collection in the Java HotSpot Virtual Machine Gain a better understanding of how garbage collection in the Java HotSpot 11.1 inspectit. 11.1. inspectit 11.1. inspectit Figure 11.1. Overview on the inspectit components [Siegl and Bouillet 2011] 11.1 inspectit The inspectit monitoring tool (website:) has been developed by NovaTec. Multi-core Programming System Overview Multi-core Programming System Overview Based on slides from Intel Software College and Multi-Core Programming increasing performance through software multi-threading by Shameem Akhter and Jason Roberts, School of Informatics, University of Edinburgh CS1Bh Lecture Note 7 Compilation I: Java Byte Code High-level programming languages are compiled to equivalent low-level programs which are executed on a given machine. The process of compiling a program Cloud Computing. Up until now Cloud Computing Lecture 11 Virtualization 2011-2012 Up until now Introduction. Definition of Cloud Computing Grid Computing Content Distribution Networks Map Reduce Cycle-Sharing 1 Process Virtual Machines Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding Compiling Object Oriented Languages What is an Object-Oriented Programming Language? Last time Dynamic compilation Today Introduction to compiling object oriented languages What are the issues? Objects Debugging Java Applications Debugging Java Applications Table of Contents Starting a Debugging Session...2 Debugger Windows...4 Attaching the Debugger to a Running Application...5 Starting the Debugger Outside of the Project's Main Tool - 1: Health Center Tool - 1: Health Center Joseph Amrith Raj 2 Tool - 1: Health Center Table of Contents WebSphere Application Server Troubleshooting... Error! Bookmark not defined. About Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage Outline 1 Computer Architecture hardware components programming environments 2 Getting Started with Python installing Python executing Python code 3 Number Systems decimal and binary notations running Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java Instrumentation Software Profiling Instrumentation Software Profiling Software Profiling Instrumentation of a program so that data related to runtime performance (e.g execution time, memory usage) is gathered for one or more pieces of the System Structures. Services Interface Structure System Structures Services Interface Structure Operating system services (1) Operating system services (2) Functions that are helpful to the user User interface Command line interpreter Batch interface Monitoring, Tracing, Debugging (Under Construction) Monitoring, Tracing, Debugging (Under Construction) I was already tempted to drop this topic from my lecture on operating systems when I found Stephan Siemen's article "Top Speed" in Linux World 10/2003. The Hotspot Java Virtual Machine: Memory and Architecture International Journal of Allied Practice, Research and Review Website: (ISSN 2350-1294) The Hotspot Java Virtual Machine: Memory and Architecture Prof. Tejinder Singh Assistant Professor, Java Programming Fundamentals Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few 2 Introduction to Java. Introduction to Programming 1 1 2 Introduction to Java Introduction to Programming 1 1 Objectives At the end of the lesson, the student should be able to: Describe the features of Java technology such as the Java virtual machine, garbage Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is Performance Monitoring API for Java Enterprise Applications Performance Monitoring API for Java Enterprise Applications Purpose Perfmon4j has been successfully deployed in hundreds of production java systems over the last 5 years. It has proven to be a highly Virtual Machines. 1 Virtual Machines A virtual machine (VM) is a "completely isolated guest operating system installation within a normal host operating system". Modern virtual machines are implemented with either software Chapter 3: Operating-System Structures. Common System Components Chapter 3: Operating-System Structures System Components Operating System Services System Calls System Programs System Structure Virtual Machines System Design and Implementation System Generation 3? Full and Para Virtualization Full and Para Virtualization Dr. Sanjay P. Ahuja, Ph.D. 2010-14 FIS Distinguished Professor of Computer Science School of Computing, UNF x86 Hardware Virtualization The x86 architecture offers four levels ATSBA: Advanced Technologies Supporting Business Areas. Programming with Java. 1 Overview and Introduction ATSBA: Advanced Technologies Supporting Business Areas Programming with Java 1 Overview and Introduction 1 1 Overview and Introduction 1 Overview and Introduction 1.1 Programming and Programming Languages Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction enterprise professional expertise distilled Oracle JRockit The Definitive Guide Develop and manage robust Java applications with Oracle's high-performance Java Virtual Machine Marcus Hirt Marcus Lagergren PUBLISHING enterprise professional expertise Performance Improvement In Java Application Performance Improvement In Java Application Megha Fulfagar Accenture Delivery Center for Technology in India Accenture, its logo, and High Performance Delivered are trademarks of Accenture. Agenda Performance 1/20/2016 INTRODUCTION INTRODUCTION 1 Programming languages have common concepts that are seen in all languages This course will discuss and illustrate these common concepts: Syntax Names Types Semantics Memory Management We Analysis of VDI Storage Performance During Bootstorm Analysis of VDI Storage Performance During Bootstorm Introduction Virtual desktops are gaining popularity as a more cost effective and more easily serviceable solution. The most resource-dependent process & Liferay Portal Performance. Benchmark Study of Liferay Portal Enterprise Edition Liferay Portal Performance Benchmark Study of Liferay Portal Enterprise Edition Table of Contents Executive Summary... 3 Test Scenarios... 4 Benchmark Configuration and Methodology... 5 Environment Configuration... Programming Languages Programming Languages In the beginning To use a computer, you needed to know how to program it. Today People no longer need to know how to program in order to use the computer. To see how this was accomplished, a... The Design of the Inferno Virtual Machine. Introduction The Design of the Inferno Virtual Machine Phil Winterbottom Rob Pike Bell Labs, Lucent Technologies {philw, rob}@plan9.bell-labs.com Introduction Virtual Machine are topical Oracle 2 2011 Oracle Corporation Proprietary and Confidential The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture Last Class: OS and Computer Architecture System bus Network card CPU, memory, I/O devices, network card, system bus Lecture 3, page 1 Last Class: OS and Computer Architecture OS Service Protection Interrupts Developing Embedded Software in Java Part 1: Technology and Architecture Developing Embedded Software in Java Part 1: Technology and Architecture by Michael Barr Embedded Systems Conference Europe The Netherlands November 16-18, 1999 Course #300 Sun s introduction of the Java How accurately do Java profilers predict runtime performance bottlenecks? How accurately do Java profilers predict runtime performance bottlenecks? Master Software Engineering How accurately do Java profilers predict runtime performance bottlenecks? Peter Klijn: Student number What Is Specific in Load Testing? What Is Specific in Load Testing? Testing of multi-user applications under realistic and stress loads is really the only way to ensure appropriate performance and reliability in production. Load testing Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors Effective Java Programming. efficient software development Effective Java Programming efficient software development Structure efficient software development what is efficiency? development process profiling during development what determines the performance of Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short An Easier Way for Cross-Platform Data Acquisition Application Development An Easier Way for Cross-Platform Data Acquisition Application Development For industrial automation and measurement system developers, software technology continues making rapid progress. Software engineers General Introduction Managed Runtime Technology: General Introduction Xiao-Feng Li (xiaofeng.li@gmail.com) 2012-10-10 Agenda Virtual machines Managed runtime systems EE and MM (JIT and GC) Summary 10/10/2012 Managed Runtime C# and Other Languages C# and Other Languages Rob Miles Department of Computer Science Why do we have lots of Programming Languages? Different developer audiences Different application areas/target platforms Graphics, AI,, Video Performance in Java Video Performance in Java Mark Claypool, Tom Coates, Shawn Hooley, Eric Shea and Chris Spellacy ABSTRACT The tremendous growth in both Java and multimedia present an opportunity for cross-platform multimedia Characterizing Java Virtual Machine for More Efficient Processor Power Management. Abstract Characterizing Java Virtual Machine for More Efficient Processor Power Management Marcelo S. Quijano, Lide Duan Department of Electrical and Computer Engineering University of Texas at San Antonio hrk594@my.utsa.edu, 2 Programs: Instructions in the Computer 2 2 Programs: Instructions in the Computer Figure 2. illustrates the first few processing steps taken as a simple CPU executes a program. The CPU for this example is assumed to have a program counter (PC), C Compiler Targeting the Java Virtual Machine C Compiler Targeting the Java Virtual Machine Jack Pien Senior Honors Thesis (Advisor: Javed A. Aslam) Dartmouth College Computer Science Technical Report PCS-TR98-334 May 30, 1998 Abstract One CS 209 Programming in Java #1 CS 209 Programming in Java #1 Introduction Spring, 2006 Instructor: J.G. Neal 1 Topics CS 209 Target Audience CS 209 Course Goals CS 209 Syllabus - See handout Java Features, History, Environment Java Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
http://docplayer.net/15308300-Can-you-trust-your-jvm-diagnostic-tools.html
CC-MAIN-2019-04
refinedweb
7,819
50.87
In many applications, ESP8266 WiFi modules can replace Arduino by adding Wi-Fi connectivity at a lower cost. At the launch of ESP8266 (in 2014), the preferred programming language was Lua (we can always program in this language!). Quickly, the vast majority of Arduino libraries have been adapted to run on the ESP8266. Today it is as easy to program an ESP8266 module as an Arduino in C++. We will discover in this tutorial how to install the necessary libraries on the Arduino IDE, and discover through simple examples the basics of the programming of the ESP8266. Install boards and libraries for ESP8266 modules on the Arduino IDE Launch the Arduino IDE and open the preferences from the File menu. On macOS, go to the Arduino menu then Preferences … Click on the icon indicated by the red arrow on the photo below. In the input field, paste the following internet address and validate This will indicate to the Arduino IDE that it must go to the arduino.esp8266.com site in order to recover other compatible development boards. Now go to the Tools menu and then boards Type and finally board Manager In the search field, type esp8266 to find the new board to install. If the board do not appear, check in the preferences that the URL is correct. also check the internet connection. Click on Install. The installation lasts only a few minutes. When the installation is complete, close the board manager and open the Tools menu again. In the board Type submenu, you now have a new section called ESP8266 Modules. The main manufacturers who contribute the most to the community (Adafruit, ESPresso, Olimex, Sparkfun, WeMos …) are on the menu. For other modules, simply choose Generic ESP8266 Module. To display the examples installed with ESP826 development board, if you just have to choose from the list then go to the File -> Examples. Before going further, note on the ESP-01 The ESP-01 is a more limited version of the ESP8266. It only has 2 GPIOs. The module has a smaller flash memory (512KB to 1MB). The programming is identical but “more painful” because it is necessary to put the module in a particular mode before being able to upload the program (Bootload mode). This is not a suitable module for learning and starting with the ESP8266. If however you need information, you will find several tutorials on the blog by doing a search with the keyword ESP-01 in the search field located in the upper right corner of the page. Differences between Arduino and ESP8266 pin tracking The ESP8266 has 9 digital I / Os instead of 14 for the Arduino Uno. While on the Arduino Uno there are only 6 outputs that support PWM mode (3, 5, 6, 9, 10 and 11), all outputs of the ESP8266 can generate a PWM signal. In summary (1) Connected to the GND pin at power up to put the ESP into bootload mode. This mode allows you to re-install the original firmware or load an Arduino program. On some board, WeMos d1 mini for example, this operation is supported by the board manager. This operation is therefore useless, the upload is transparent. Typically, manufacturers publish a pinout that indicates the equivalent pin on an Arduino Uno. Here, for example, the pins of a WeMos d1 mini. This connection diagram is valid for all ESP-12x-based boards. Attention to the GPIO which works at a voltage of 3.3V Special feature of the ESP8266 compared to the Arduino Uno (this is no longer the case for the Genuino 101 and new Intel Curie-based boards), the GPIO operates at a voltage of 3.3V. It will therefore in some cases adapt your editing. For this, there are voltage dividers (5V to 3.3V) or vice versa (3.3V to 5V). How to program the ESP8266 with the Arduino IDE? Hardware and test circuit Here is a small editing to make with an ESP8266 (here a WeMos d1 mini) and an LED that will allow you to test the various codes proposed in this tutorial. For the record, here is a table summarizing the typical supply voltage according to the color and the diameter of the LED. Classic programming The first thing to know when starting with an ESP8266 module is that it can be programmed exactly like an Arduino. Unlike the less powerful ATTiny microcontrollers, the SoC of the ESP8266 is able to execute all C ++ commands of the Arduino code. The only condition to respect is to use the library adapted for this last one as soon as one wants to use the WiFi (following paragraph). Open the Arduino IDE and paste this code into a new project before uploading it. What does this program do? - An integer variable (int) indicates which output the LED is connected to - In the setup() loop, we indicate that the pin (here 16) is an output (OUTPUT) - The loop() loop runs to infinity. At each passage - We put the output (16) at the low level (LOW), that is to say that the output voltage is zero (no current) - We wait 1 second. The delay is indicated in milliseconds (1000ms = 1s) - The output (16) is set high (HIGH), that is, the output voltage is 5V (the current flows) - We wait 2 seconds - And so on int led = 16; void setup() { pinMode(led, OUTPUT); // Initialise la broche "led" comme une sortie - Initialize the "LED" pin as an output } // Cette boucle s'exécute à l'infini // the loop function runs over and over again forever void loop() { digitalWrite(led, LOW); // Eteint la Led - Turn the LED OFF delay(1000); // Attendre 1 seconde - Wait for a second digitalWrite(led, HIGH); // Allume la Led - Turn the LED off by making the voltage HIGH delay(2000); // Pause de 2 secondes - Wait 2 secondes } Now, replace in output 16 by the equivalent identification of ESP8266, namely D0, which gives int led = D0; As you can see, the program works identically. Web Server Programming: connect the ESP8266 to the WiFi network Web Server programming allows you to add a Web interface (written in HTML and javascript) to an ESP8266 project. It is also possible with an Arduino but it makes sense with an ESP8266 which natively has a WiFi connection. Let’s go back to the previous code and add the two necessary libraries #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> We will create two variables to define the SSID (identifier of the WiFi network) and the password before creating an object that will contain the Web server (C ++ object) const char* ssid = "xxxx"; // WiFi ssd const char* password = "xxxxxxxxx"; // WiFi password ESP8266WebServer server(80); // create a web server. listing standard http 80 port The code of the setup function does the following - Serial.begin(115200) opens the serial port at 115200 baud - WiFi.begin(ssid, password) the ESP8266 connects to the WiFi network The while loop writes a dot on the serial port every 500ms until the ESP8266 is connected to the WiFi WiFi.status() != WL_CONNECTED (very bad idea when running on battery elsewhere, but that is just to understand the operation) - Serial.println (WiFi.localIP()) writes on the serial port the IP address assigned by the internet box or the router to the ESP8266 server.on ("/", [] () { server.send (200, "text / plain", "Home"); // Add an entry point, a web page }); We add an entry point, ie an internet address (URL) on which we will display for the moment a simple text server.on ("/ parametres", [] () { server.send (200, "text / plain", "A page of parameters"); }); A second page that could be a parameter page - server.begin() finally, we start the web server All that remains is to ask the ESP8266 to listen to the requests and to display the corresponding pages. For that we add the server.handleClient() command in the loop () function. Past the complete code into a new project and upload it to the WeMos. #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char* ssid = "xxxx"; // WiFi ssd const char* password = "xxxxxxxxx"; // WiFi password ESP8266WebServer server(80); // create a web server. listing standard http 80 port int led = D0; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(""); // on attend d'etre connecte au WiFi avant de continuer while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // on affiche l'adresse IP attribuee pour le serveur DSN Serial.println(""); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // on definit les points d'entree (les URL a saisir dans le navigateur web) et on affiche un simple texte server.on("/", [](){ server.send(200, "text/plain", "Page d'accueil"); }); server.on("/parametres", [](){ server.send(200, "text/plain", "A parameter page"); }); //, la fonction handleClient traite les requetes server.handleClient(); digitalWrite(led, LOW); // Eteint la Led - Turn the LED OFF delay(1000); // Attendre 1 seconde - Wait for a second digitalWrite(led, HIGH); // Allume la Led - Turn the LED off by making the voltage HIGH delay(1000); // Pause de 2 secondes - Wait 2 secondes } Open the serial monitor to retrieve the IP address of the ESP8266 on the local network. Now open a web browser and enter the IP address or IP_ESP8266/parametres. And now, in a few lines of code, you just connect the ESP8266 to the local network (and internet at the same time). You can access a web interface from any computer or smartphone. By doing a port forwarding on your internet box or router, you can even access the interface outside of your home with a 3G / 4G connection. Web Server Programming: drive the GPIO from the internet! We will now see how to add commands to drive the GPIO from an interface. There are several methods to generate the HTML code of the interface that will be sent to the web browser. Here, we will simply create a string that will contain the HTML code. Everything is explained in detail in this tutorial. Each line is explained in the code. What you must remember : - HTML code is built by assembling strings - It is possible to integrate the variable content. Here the state of the output D0contained in the chain etatD0. - Each state change is sent to the web server running on the ESP8266 using a form in the form of an HTTP POST request. - Here, the update is triggered manually by pressing a button (submit) String getPage(){ String page = "<html lang=fr-FR><head><meta http-"; page += "<title>ESP8266 Web Server Demo -</title>"; page += "<style> body { background-color: #fffff; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }</style>"; page += "</head><body><h1>ESP8266 Web Server Demo</h1>"; page += "<h3>GPIO</h3>"; page += "<form action='/' method='POST'>"; page += "<ul><li>D0 (etat: "; page += etatD0; page += ") "; page += "<INPUT type='radio' name='D0' value='1'>ON"; page += "<INPUT type='radio' name='D0' value='0'>OFF</li></ul>"; page += "<INPUT type='submit' value='Actualiser'>"; page += "<br><br><p><a hrf=''></p>"; page += "</body></html>"; return page; } Now, we change in the setup the entry point to the home page. We connect the entry point “/” to the handleRoot function. server.on ( "/", handleRoot ); When the main page (“/”) is displayed or the web server receives a POST request (GPIO refresh), the handleRoot function is called. The server.hasArg function allows you to connect actions. Here, if the query contains the argument (hasArg), then we must change the state of the GPIO. We execute the handleSubmit function, otherwise we refresh the page. void handleRoot(){ if ( server.hasArg("D0") ) { handleSubmit(); } else { server.send ( 200, "text/html", getPage() ); } } The handleSubmit function retrieves the value of the “D0” argument with the server.arg function and then it is enough to test the value of this one to realize the good treatment. Be careful, it’s a string of characters. We must test like this == “1” and not == 1. We take this opportunity to store the state of the output in the variable etatD0."); } } Paste the following complete code by changing WiFi ID and password. #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char* ssid = "XXXX"; // Identifiant WiFi const char* password = "XXXXXXXX"; // Mot de passe WiFi ESP8266WebServer server(80); // On instancie un serveur qui ecoute sur le port 80 int led = D0; String etatD0 = "Off"; String getPage(){ String page = "<html lang=fr-FR><head><meta http-"; // C'est du code HTML, la page s'auto-actualise page += "<title>ESP8266 Web Server Demo -</title>"; // Titre de la barre du navigateur page += "<style> body { background-color: #fffff; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }</style>"; // style de la page page += "</head><body><h1>ESP8266 Web Server Demo</h1>"; // Titre de la page (H1) page += "<h3>GPIO</h3>"; // Sous-titre (H3) page += "<form action='/' method='POST'>"; // Le formulaire sera envoye avec une requete de type POST page += "<ul><li>D0 (etat: "; // Premiere ligne de la liste (ul) avec D0 page += etatD0; // on concatene la chaine contenant l'etat de la sortie page += ") "; page += "<INPUT type='radio' name='D0' value='1'>ON"; // Bouton pour activer D0 page += "<INPUT type='radio' name='D0' value='0'>OFF</li></ul>"; // et le desactiver page += "<INPUT type='submit' value='Actualiser'>"; // Bouton d'actualisation page += "<br><br><p><a hrf=''></p>"; page += "</body></html>"; return page; } void handleRoot(){ if ( server.hasArg("D0") ) { handleSubmit(); } else { server.send ( 200, "text/html", getPage() ); } }"); } } void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(""); // on attend d'etre connecte au WiFi avant de continuer while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // on affiche l'adresse IP qui nous a ete attribuee Serial.println(""); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // on definit les points d'entree (les URL a saisir dans le navigateur web) et on affiche un simple texte server.on ( "/", handleRoot ); //, on appelle handleClient pour que les requetes soient traitees server.handleClient(); } Here is the interface obtained Now that it’s clearer, you can go a step further in the details of ESP8266’s Web Server programming by reading this article. You can achieve this type of interface by following this project of weather station in 5 steps. All ESP8266 Web Server Programming TutorialsWeb Server (Communication + Interface) - ESP8266, retrieve time from a time server (NTP), elapsed time since last Reset, store time in SPIFFS [Update] 28 June 2017 - ESP8266. How to use WiFiManager library to manage WiFi connections 26 June 2017 - Driving the ESP8266 GPIO (Web Server) from Jeedom to TCP / IP Wireless – Part 2 14 April 2017 - Driving the GPIO of the ESP8266 (Web Server) from Domoticz to TCP/IP Wireless – Part 2 31 March 2017 - ESP8266. How to connect to the WiFi network (ESP8266WiFi and ESP8266WiFiMulti) 22 March 2017 - ESP8266 (Web Server – Part 5): how to use Google Charts to display gauges and charts 20 March 2017 - ESP8266 (Web Server): Fast development of HTML + js with Node.js and Pug 15 March 2017 - ESP8266 (Web Server – Part 4): ArduinoJson, load, save files (SPIFFS) 13 March 2017 - ESP8266 (Web Server – Part 2): Interaction between Arduino code and HTML interface 27 February 2017 - ESP8266 (Web Server – Part 1): Store the web interface in the SPIFFS area (HTML, CSS, JS) 22 February 2017 - Bootstrap (Web Server ESP8266): use the Bootswatch themes 15 February 2017 - How to create a beautiful Web Interface for projects ESP8266 / ESP32 with Bootstrap 13 February 2017 - ESP8266. Understand the Arduino code of a web server with HTML interface 10 February 2017 Web Client Programming: The Web Client programming makes it possible to communicate an ESP8266 module with another server, another ESP8266, a mobile application … Here are some examples of applications: - Transmit measurements (temperature, humidity, particle rate, atmospheric pressure, brightness, noise …) - Transmit states (door or window opening detector, contactor …) Here are several articles on the subject with examples of application to communicate the ESP8266 with Jeedom or Domoticz (remote display)Web Client (Communication) - Temperature measurement with several DS18B20 probes, Arduino code compatible ESP8266 and ESP32, publication on Domoticz in HTTP 8 December 2017 - ESP8266. How to use WiFiManager library to manage WiFi connections 26 June 2017 - ESP8266 (Web Client): Sending Data to Jeedom in TCP / IP Wireless (JSON API) – Part 1 7 April 2017 - ESP8266 (Web Client): Sending Data to Domoticz in TCP/IP Wireless (API/JSON) – Part 1 24 March 2017 Frequently Asked Questions (FAQ) What hardware to buy to start with the ESP8266? To get started with the ESP8266 modules, you will need the same hardware as for an Arduino Uno. You can buy a basic kit including a breadboard, a Dupond jumper set and a regulated 5V / 3.3V power supply. If you start with the micro-controllers and the ESP8266, I recommend the Wemos d1 mini or the Wemos D1 R2 (a board in the same format as the Arduino Uno). These two boards are very economical and are perfectly managed from the Arduino IDE. It is very rare to install the CH341 driver on macOS, Linux or Windows. On which platforms is the Arduino IDE available? The Arduino IDE is available on all operating systems (Windows, MacOS, Linux, ARM Linux). Whatever your environment, you can develop your ESP8266 projects with the Arduino IDE. Go to the Arduino feature website to get the right installer for your computer or mini-PC. Can I program an ESP8266 on a Mac? Yes, the Arduino IDE is available on macOS as well. Since the Espressif SDK is written in python, it is possible to program the ESP8266 modules as on a Windows PC. Can the ESP8266 be programmed from Linux ARM? Yes, if you have a Raspberry Pi or an equivalent mini-PC running Linux ARM (an Orange Pi for example), it is quite possible to use the Arduino IDE. How to develop without programming with the ESP Easy Firmware If you’re new to micro-controllers and everything you’ve read before has scared you a little bit, no problem. The ESP Easy project is for you! ESP Easy is an interface that allows to develop probes or actuators by simple configuration. The interface is in English but everything is explained in these tutorials. Which model of ESP8266 to choose to start? Development boards based on ESP-12x (WeMos d1 Mini, Geekcreit …) are best for beginners. The upload is handled completely transparently by the ESP8266 SDK from the Arduino IDE. You can use the price comparator to find the best deal on the internet. Can I use NodeMCU or MicroPython development boards? Yes absolutely. These are other firmwares. NodeMCU is used to execute Lua code. As soon as the first upload, the firmware will be replaced by the Arduino code. You can re-install the firmware NodeMCU (follow this tutorial for that) or MicroPython later. If the MicroPython tempts you, here are some articles to start: - What is the ESP-WROOM-32 model? The ESP-WROOM-32 module is the successor code name of the ESP8266, the ESP32. It is more powerful, less greedy, more secure, more pro (CAN bus), it also provides support for Bluetooth in addition to WiFi. The price of ESP32 development boards has fallen sharply in recent months. They are now almost the same price. To find out more, go to the ESP32 category of DIY Projects. Here, the Lolin32 Lite from Wemos.cc Some books to start in C / C ++ Arduino programming uses notions of C/C ++ object programming. There are very good introductory books and tutorials on the web to go beyond the concepts discussed here. - That was really helpful! Thanks a lot of such a great effort! I have a short question: Can I store the data in the serial monitor from ESP using the WiFi connection and link it to MATLAB? Thank you very much. I don’t have any Matlab licence, so I can’t test anythings. I think that’s no problem. I imagine that on the ESP8266, you have to send the measurements with the command Serial.println(you_data). On Matlab, there are several commands to open the serial port and read data (in ascii for example) . fopen / fgetl / fclose. Hi, Very intersting! I have another quesiton; can I upload the program it self using WiFi after connecting the Arduino with my home router. I mean let’s say, I will connect my ESP with WiFi and then I put somewhere where it’s difficult to connect it through USB again, at this stage can I send a new code through WiFi or not? Great. To recover data in python, I advise you to communicate in HTTP or Websocket. You can do more elaborate things. For example since the pyhon code send settings, start or stop the publication of data. You can get inspired by these tutorials Websockets HTTP You can also use the awesome project johnny-five if you know the javascript. Then to connect your code to Matlab – In Pyhon – Nodejs That’s it, I hope you have everything you need for your project or your studies. Have a nice week end BIG THANK FOR YOU! You’re welcome. I did not do much. You still have everything to do. Good luck and do not hesitate to explain your project when it is finished. He looks very interesting. See you soon. Have a nice week end Hi. Yes it possible. All is explain in this post Have a good week end Amazing! Last question; can I check or see the serial monitor remotly through WiFi ? And finally import data from this monitor to Matlab or Python or any post process software? All two steps are being made wirelessly?
https://diyprojects.io/program-esp8266-arduino-ide-libraries-gpio-web-server-web-client/
CC-MAIN-2021-49
refinedweb
3,577
62.17
The journey continues. This time, I am looking at AES-CBC. Consider the scenario where we have an encryption oracle such that outputs ciphertexts , where denotes concatenation. The oracle uses PKCS7 padding and encrypts with fixed but unknown key and IV. The CBC-mode of operation is defined as follows: Embodied in Python code, the oracle is from Crypto.Cipher import AES import base64 import random plaintext = b'''This is an encrypted message.''' key = None cprefix = None iv = None def randbytes(k): return open('/dev/urandom').read(k) def pkcs7pad(s,blksize=16): missing = abs(len(s) - (len(s)/blksize+1) * blksize) return s+(chr(missing)*missing) def encryption_oracle(s): global key global iv if key is None: key = randbytes(16) if iv is None: iv = randbytes(16) cipher = AES.new(key, AES.MODE_CBC, IV=iv) s = pkcs7pad(bytes(s) + plaintext, 16) return cipher.encrypt(s) So, for instance, when querying the oracle with , we obtain the encryption of We note the following: - If the input is a fixed string, say, , with length 15 bytes (blocklength-1), we will include exactly one byte from the (unknown) plaintext . This block will be independent of the subsequent unknown plaintext bytes. For the sake of simplicity, assume that . - So, if we query the oracle for all 256 strings , where runs over all possible bytes, we can compute a look-up table. - We may then look at our first encryption and, using the look-up table from before, see which that satisfies the first block of . This determines the first byte of . - This may repeated in several steps, until we find all bytes in the first block. Let us return to the IV issue implicitly stated earlier. We do not know the IV, but does that really matter? No! The IV will be constant in the first block and, thus, the input string fed into it. Now, as long as we can control the IV in the coming block (keep it constant), it has no effect on the result. - Using the same padding methodology as before, we may now compute the bytes of the coming block, but looking at the next block. Again, with Python as our weapon of choice, we impale the decryption problem as follows def attack(blocksize, known): index = len(known) / blocksize prefix = 'a'*(blocksize-len(known)%blocksize-1) lookup = {} for char in range(0, 256): lookup[encryption_oracle(prefix+known+chr(char))[index*16:index*16+16]] = chr(char) substring = encryption_oracle(prefix)[16*index:16*index+16] if lookup.has_key(substring): return lookup[substring] else: return None Running this until we obtain a None-flag, i.e., plain = '' while attack(16, plain) != None: plain += attack(16, plain) print 'Found plaintext:\n', plain we obtain the sought plaintext ! Advertisements 2 thoughts on “Byte-wise decryption of AES-CBC” Cool! If I’m not mistaken this would also work for AES-ECB, right? Yes, there is a trivial reduction to ECB (by setting IV=0x0 in each round). In fact, the ECB attack is one of the Matasano challenges which I completed a couple of days ago. I was somewhat surprised that this (CBC) was not mentioned there (or maybe I missed it), so therefore I decided to write it down.
https://grocid.net/2016/05/01/byte-wise-decryption-of-aes-cbc/
CC-MAIN-2017-17
refinedweb
538
64.2
can you tell me a another way to check the winner with connected checkers and i make in the move method if your destination is the opponent decrement the number of checkers of the opponent can you tell me a another way to check the winner with connected checkers and i make in the move method if your destination is the opponent decrement the number of checkers of the opponent sorry how can i post my code formatting and what code can i posted the testing or my code no will be 4 squares but the game Board is constant 8*8 my problem with the recursion method can you check it . i made another boolean array to check if this piece is counted turn it into true. ??!! No it supposed to check the 8 squares everywhere in 2D array not only in the middle --- Update --- ?? in method isGameOver i made a loop on boolean array to catch the first piece count around region in 8 direction . can you tell me another idea to count the around region to count the connected... Lines of Action is a two player strategy board game where each player aims to connect all his/her checkers into one group. The board is a standard 88 chessboard. The game starts with each player... i don't know how to use the debugging there is an infinite loop i can't find it. --- Update --- loop has no end --- Update --- any one help plz sorry it is an blue arrow appears when i run my tests using Junit please any one help me with fixing an blue arrow appears while running my project tests --- Update --- can you help me Norm can you check the test class ? --- Update --- h get the values from the user how can i assign values to h? the value null null null ......and so on 19 null value --- Update --- ? [ instance.setSkills(skills); Champion target = new Champion("Annie", attributes, 500, 400); instance.useSkill(target, 0, true); assertEquals("Target should lose health as expected", 383,... can u write it down to understand in which class? --- Update --- ? i don't know --- Update --- please can you tell me what i have to do to fix it, sorry? h is a hashmap with key(strings) and value(boolean) --- Update --- ? public void setBasic(boolean ba){ h.put("Basic", ba); } you mean the variable basic There is no variable with a null value on line 30. check it plz all the errors in test class --- Update --- java.lang.NullPointerException at eg.edu.guc.lol.game.champions.Skill.setBasic(Skill.java:30) at... this the test class import java.util.HashMap; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import eg.edu.guc.lol.game.champions.Champion; what's wrong plz? Norm --- Update --- this the test class import java.util.HashMap; t } [/code]
http://www.javaprogrammingforums.com/search.php?s=3bd1edb0d414090e652349c57c31db0f&searchid=203389
CC-MAIN-2016-30
refinedweb
477
73.27
newLISPtm v.9.4.5 Release Notes August 5th, 2008 Versions 9.4.1 to 9.4.5 are corrective updates to the 9.4.0 release with minor additions in functionality in version 9.4.4. These additions are marked: (v9.4.4) in the following text. New API for hash-like dictionary access newLISP has always used names-paces to build dictionaries for associative memory access, but the API (application programming interface) was lengthy and the created dictionaries where not always safe for saving and reloading, because of overwritten system symbols. The new API is short and safe. Dictionaries created with the bayes-count function can be used as dictionaries with hash-like access and vice-versa. The new API allows for easy transformation of association lists into namespaces for hash-like access and and vice-versa converting association lists into namespaces. For details on this new API see the chapter Dictionaries and hash tables in the users manual. New Cilk API for multi processing The new Cilk API works with only three new functions: - spawn for starting the evaluation of a function in a child process. - sync for synchronizing data transfer from finished child processes. - abort for aborting s specific or all child processes. The new Cilk API takes advantage of todays multi-core CPUs as the operating system will distribute different processes on to different cores inside the processor. Even on single core processors the new API is useful wherever multiple processes in a program have to be coordinated and with data transfer in between them. An inlet function for event driven syncronization is also supported. The new API encapsulates exisiting functionality from the fork, wait-pid and share functions. This new API works on Mac OS X and Linux/UNIX, on Win32 it is only simulated to make source code portable. A general mechanism for reference passing Namespaces in newLISP always haven been passed by reference to user-defined functions, but only few bult-in newLISP primitives could handle data packaged in namespaces with default functors. Now any function in newLISP can handle strings and lists packaged this way. See the chapters default functor and Passing data by reference in the users manual for more information. More access to newLISP internals - read-expr hooks into the internal source reader to access expressions before evaluation. - prompt-event can fully customize the prompt in the interactive newLISP console. - command-line enables pre-processing of the command line and HTTP requests. One of newLISP's strengths is working with it interactively in a terminal. prompt-event and command-event allow a full integration of a OS shell and newLISP interactive mode. See the reference of the command-event function for an example. Improved newLISP-GS with MIDI support - Several bugfixes in the newLISP-GS editor. - MIDI support for internal sound synthesizer and external sound-banks. Other API changes and additions - The $idx system variable is now updated by all non-counting iterating functions including map. (v.9.4.4) - bind has a new optional flag to force evaluation of bound parameters. - env now removes an environment variable when set to an empty string (except Solaris, where it stays as an empty string). - if-not works like unless which will lose the else clause in a future version to be symmetrical to when. (v.9.4.4) - inc and dec now can operate on symbols containing nil assuming they contain 0 (zero). (v.9.4.4) - lookup can take an optional default expression to return when lookup failed. - randomize has been rewritten using a better algorithm. - new regex-comp allows pre-compilation of regular expressions. - Deprecated replace-assoc has been removed. Use set-assoc and pop-assoc instead. (v.9.4.4) - search has a new parameter to put the file pointer to either the beginning or end of the searched string. - series can take a lambda function instead of a multiplication factor. - sys-info now also returns the process id on Mac OS X and UNIX. - wait-pid has changed parameters for better control of child processes. Added and removed files - mysql.lsp The original MySQL v.4.0 module has been removed. Use either the mysql5.lsp or mysql51.lsp module for MySQL versions 5.0 and 5.1. - nanorc A configuration file for newLISP syntax highlighting in the GNU nano editor has been added to util directory in the source distribution and install directories. The file support syntaxhighlighting for newLISP .lsp, C .c and .h files and for HTML .html files. This modeless editor is installed bu default on Mac OS X, UBUNTU Linux and most other Unix installations. All known bugs have been fixed. For a detail of bug fixes see the CHANGES notes in the source distribution. §
http://www.newlisp.org/downloads/previous-release-notes/newLISP-9.4-Release.html
CC-MAIN-2014-10
refinedweb
793
58.48
Performance optimization in Python can be done by following difference methods. Learn more about this aspect of python programming here. Performance optimization in Python: Code profiling First and foremost you should be able to find the bottleneck of your script and note that no optimization can compensate for a poor choice in data structure or a flaw in your algorithm design. Secondly do not try to optimize too early in your coding process at the expense of readability/design/quality. Donald Knuth made the following statement on optimization: “We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%” To profile your code you have several tools: cProfile (or the slower profile) from the standard library, line_profiler and timeit. Each of them serve a different purpose. cProfile is a deterministic profiler: function call, function return, and exception events are monitored, and precise timings are made for the intervals between these events (up to 0.001s). The library documentation ([][1]) provides us with a simple use case import cProfile def f(x): return "42!" cProfile.run('f(12)') Or if you prefer to wrap parts of your existing code: import cProfile, pstats, StringIO pr = cProfile.Profile() pr.enable() … do something … … long … pr.disable() sortby = 'cumulative' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() print s.getvalue() This will create outputs looking like the table below, where you can quickly see where your program spends most of its time and identify the functions to optimize. 3 function calls in 0.000} The module line_profiler ([][1]) is useful to have a line by line analysis of your code. This is obviously not manageable for long scripts but is aimed at snippets. See the documentation for more details. The easiest way to get started is to use the kernprof script as explained one the package page, note that you will need to specify manually the function(s) to profile. $ kernprof -l script_to_profile.py kernprof will create an instance of LineProfiler and insert it into the builtins namespace with the name profile. It has been written to be used as a decorator, so in your script, you decorate the functions you want to profile with @profile. Finally timeit provides a simple way to test one liners or small expression both from the command line and the python shell. This module will answer question such as, is it faster to do a list comprehension or use the built-in list() when transforming a set into a list. Look for the setup keyword or -s option to add setup code. import timeit timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.8187260627746582 from a terminal python -m timeit '"-".join(str(n) for n in range(100))' 10000 loops, best of 3: 40.3 usec per loop
https://codingcompiler.com/performance-optimization-in-python/
CC-MAIN-2022-27
refinedweb
486
64.61
Text::Editor::Easy - A perl module to edit perl code with syntax highlighting and more. Version 0.49 There are IDE (or editors) that are currently in active development in perl : for instance, Padre and Kephra. Let's be confident that these projects bring us good designing tools that will be, at last, written in perl. Still, I would like a different IDE that what we can find now, and, as these IDE are still in development, perhaps they won't reach my needs once finished. There are now lots of dynamic langages, like perl. The potential of these dynamic langages is not fully used with a standard IDE and static programmation. I wish we could build a RAD tool (Rapid Application Development) which would generate "dynamic applications" : that is, applications that you can modify while they are running. This editor module will try to be the first part of this tremendous task. I want the editor to be programmer-oriented : you should be able to use it like a perl module from your perl programs. And I would also like the generated applications from the IDE to be programmer-oriented : the code of these applications should be accessible during execution and should be modifiable. Programmers should help themselves instead of constantly building "user-oriented" applications (a "programmer-oriented" application can still be used by a simple user). Have a look at if you want more explanations about that. This perl editor module comes with a perl editor program : 'Editor.pl' is an application that uses 'Text::Editor::Easy' instances to edit perl code. The module enables you to manipulate a highly multi-threaded graphical object. Several demos are provided with the program. To run them and have a glance at the capabilities of this module, launch the perl program "Editor.pl". See README file for installation instructions. The demos (10 demos to be tested from the "Editor.pl" program) will show you better examples of how to call this module. use Text::Editor::Easy; my $editor = Text::Editor::Easy->new; $editor->insert("Hello world\nSecond line\nlast line"); $editor->save("my_file.tst"); This module is object-oriented. Once an instance is created, numerous methods are accessible (maybe too much, for now !). New methods can be added on the fly with, why not, new threads associated with these new methods. Sometimes, you need to consume CPU to achieve your goal. But this shouldn't block the user who interactively use your graphical module : the interface of the module (especially, method "create_new_server") allows you to create threads as simply as you create a new variables. See module Text::Editor::Easy::Comm for the thread mecanism. Using threads, you can make 'real interactive' applications : a 'Cancel' button that works, for instance. All you have to do is to work in an interruptible way which is not possible in a mono-thread application. Thus, graphical applications (with interactive users) should always be multi-threaded. Threads are not only used for speed or interactivity. With private variables, they allow you to partition your code. So you don't have a large program with a huge amount of data to manage but a lot of little threads, specialized in a much simpler task with fewer variables to manage. The only remaining problem is how to communicate with all these "working together threads" : the Text::Editor::Easy::Comm provide the solution. All you have to do is define a new thread associated with your new methods. When the new methods are called (by any thread, the new created one or any other one), your new thread will be called automatically and the response will be automatically provided to the initial calling thread (in the context of the caller). Easy, isn't it ! Again, see module Text::Editor::Easy::Comm for the thread mecanism. The graphical part of the module is handled mainly by Text::Editor::Easy::Abstract. The "Abstract" name has been given because, even if I use Tk for now, there is no Tk calls in all the Abstract module. Tk calls are concentrated in Text::Editor::Easy::Graphic::Tk_Glue module : other "Graphic glue" modules are possible. I think of "Gtk", "Console", and why not "Qt" or "OpenGl" ? There is a limited communicating object (a "Text::Editor::Easy::Graphic") between the Abstract module and the glue module : this is the interface. This interface may change a little in order to allow other "Glue module" to be written, but, of course, all graphic glue modules will have to use the same interface. You can see the "Text::Editor::Easy" as a super graphical layer above other layers. I imagine a generator where you design an application in your preferred graphical user interface but the generated application could run (maybe in a limited way) in "Console mode". Constant re-use is the key to hyper-productivity. my $editor = Text::Editor::Easy->new( { 'file' => 'my_file.t3d', 'events' => { 'clic' => { 'sub' => 'my_clic_sub', }, } } ); This function creates and returns a Text::Editor::Easy instance. A Text::Editor::Easy instance is a scalar reference so that you can't do anything with it... except call any object method. This function accepts either no parameter or a hash reference which defines the options for the creation. Here are these options : If you want to define a special behavior in response to user events you have to write special code and reference this code so that it can be executed. You can reference this code during the instance creation. To have more information about 'Events', look at Text::Editor::Easy::Events. $editor->insert("Hello"); # Simple insert # Multi-lines insert with list context my @lines = $editor->insert("\n\nA non empty line\nAnother non empty line\n\n"); # Using options my $last_line = $editor->insert( "...adding data\nLast line", { 'line' => $lines[3], 'cursor' => 'at_start', } ); The insert method encapsulates horrible code for you (and believe me, my code is terrible !). It accepts one or 2 parameters : the first is the string to be inserted, the second, optional, is a hash reference that may change default behavior. The string can be a single character or several millions of them. Only, you should know that, from time to time, a carriage return (or line feed, or both : just "\n" in perl) should separate your string in reasonably short lines. Perl has no limit except your memory, but the Text::Editor::Easy module would slow down badly if it had to display lines of several thousands characters. By default, the insertion is made at the cursor position and the cursor position is updated to the last character of the string you have inserted. If the cursor is visible before the insertion, the cursor remains visible at the end of the insertion (maybe at the bottom of the screen). Note that insert method may replace text too if the "Inser" key have been pressed (or set) for the editor instance, but this happens only for the first line. This method returns Text::Editor::Easy::Line instance(s). In scalar context, only the last inserted line is returned. In list context, all inserted or changed lines are returned. If your string does not contain any "\n", then scalar and list context return the same thing as only one line is changed. You shouldn't use list context for huge string (the 'line' instance creation consumes memory and CPU). The hash reference, with its options, allows you to modify default behavior : Why have all these options been added to the basic 'insert' method ? Because an 'insert' call is all that : an insertion point is chosen, text is inserted in a precise way, cursor position is changed and, if text is long enough, your editor may look quite different. As all these things are done implicitly, it seems legitim that options let you define each step explicitly. By default, the insertion is made at the cursor position. You can change that using 'line' and 'pos' options. The 'line' option must specify a valid 'line' instance. The 'pos' option indicates the position of the insertion point in the line. You may use only one of these 2 options : Note that if you use an insertion point option (either 'pos' or 'line', or both), the cursor position is no more changed by default : it remains where it was before the insertion unless you specify a cursor position. 'replace' => 1, # will replace text (only in the first line) By default, the editor uses the current "insert" config to insert the text. The config is linked to the "Inser" key and if the user have pressed it. You can force your "insert" config using the 'replace' option. Set to 1 (or true), existing text will be replaced (only in the first line and according to the length of your first inserted line too). Set to 0 (or false), text will be inserted. This option tells where to set the cursor after the insertion has been made : 'cursor' => 'at_start', will set the cursor before the first character that has been inserted. In fact, this option souldn't move the cursor unless you have used an insertion point. 'cursor' => 'at_end', will set the cursor after the last character that has been inserted. This is the default behavior of insert method (only useful when you have changed the default insertion point). You can also use a reference of array with 2 values (the second is optionnal) to set the cursor position. 'cursor' => [ 'line_0', 3 ]; # will set the cursor at the position 3 in the first line modified by insert # 'line_' is followed by the number of the inserted line 'cursor' => [ 'line_2', 0 ]; # will position the cursor at the beginning of the 3rd inserted line 'cursor' => [ 'line_2' ]; # will position the cursor at the end of the 3rd inserted line 'cursor' => [ 'line_end', 0 ]; # will position the cursor at the beginning of the last inserted line 'cursor' => [ $line, $number ]; # will position the cursor in line $line (line instance), position $number (integer) Thanks to line_$number syntax, you can indicate cursor position on lines that do not exist before your call (because the call is creating them). You can still use an already existing line to set the cursor position (last example). In that case, you provide the 'line' instance in first position. With no second parameter, cursor will be set at the end of the line. Note that 'line_0' is not really useful as the first line always exists before insertion (it's either $editor->cursor->line or the insertion point you have chosen). 'display' => [ 'line_2', { 'at' => 20, 'from' => 'middle' } ]; # the reference line is the second inserted line 'display' => [ $editor->number(10) ]; # It's the line number 10 before the call ! Insertion can change this order... Display option is an integrated call to the display method. As for the 'cursor' option, you may use a line_$number syntax to give the reference line that will be used for the display. Otherwise, the syntax is the same as the original display method : as 2 parameters may be provided, the 'display' option of the insert method is an array reference. There is an 'assist' option that can call specific sub to make special action each time a particular text have been inserted (typically, adding other text...). But the interface of this option is not yet fixed. In the same way, there will be a way to inhibit the event management as, at present, there is one event generated by an insert (the 'change' event). Maybe 'assist' option will be replaced by a generalized event management... $editor->display( $editor->number(23), { 'at' => 'middle', 'from' => 'middle', } ); The display method needs at least one parameter : the 'line' instance or 'display' instance. The second, a hash reference, is optionnal. If your editor is not visible because it's under another one (see Text::Editor::Easy::Zone), you'll make it visible using "FOCUS" or "AT_TOP" methods. The display method is used to show the editor in a precise way. Displaying an editor doesn't mean much if you don't take a reference. The reference is the first parameter which is a line or a part of it with wrap mode enabled ('display'). When you have defined this reference, you can add options to precise where to put this reference in the screen. By default (with no second parameter), the top of the 'line' (or 'display) will be at the 'middle of the top', that is, it's top ordinate will be one quarter of the screen height. You can change where to display the reference line with 'at' and 'from' options. This option gives the ordinate (which is, by default, one quarter of the screen height). You can use 'top', 'bottom' or 'middle' values or an integer. The integer value will position the line precisely in the screen. But you should have receveid the number you give by another method rather than have chosen it yourself : this integer is the number of pixels from the top for graphical interface but will be the line number in console mode (in console mode, you can't be more precise than a line height). $editor->display( $editor->number(23), { 'at' => $my_ordinate } # $my_ordinate should be an integer (or 'bottom', 'middle' or 'top') ); As lines have a height, displaying a line at a precise ordinate doesn't tell what part of the line will be located at this ordinate. By default, it's the top of the line. For the 'from' option, you can use 'top', 'middle' and 'bottom'. Note that this option may change things a lot if the reference line is a multi-line : wrap mode and several displays for this line. By default, there may be adjustments. If the first line of the editor is under the top, or the last line over the bottom with sufficient lines to fill the screen, your precise positioning will be changed. You can avoid adjustments by setting the 'no_check' option to true. Set the focus to the editor. It will be placed on top of the screen to be visible and will have the 'focus'. Any pressed key will be redirected to it : if the cursor belongs to a line that is displayed, it should be visible. Place the editor on top of the screen to make it visible. No action is made if editor was already on top or had the focus. You can redirect standard prints and make special prints on debug files. There are 3 possible states for standard prints : A specific user action is just a user sub that is called each time a print matches some user conditions. By default, there is no redirection. With a complete analysis, a trace thread is created : this thread managed a small database (with SDBM_File) of all prints. A link is made between the exact position of the print in the redirection file and data (saved in other files) explaining the print : Moreover, with a complete analysis, all calls between threads are traced the same way : an other small database, managed by the same thread, saves information on each 'call_id'. If we use these 2 databases together, all prints can be traced in a 'multi-threaded' way. # Tracing from the very start : in a BEGIN bloc use Text::Editor::Easy { 'trace' => { 'print' => { # Interface to be written } } }; Another possibility when redirection is not so urgent : use Text::Editor::Easy; # Tracing from the start of the execution (no instruction between the use and the configure) Text::Editor::Easy->configure( { 'trace' => { 'print' => { # Configure method to be written } } } ); In the first case, the redirection is made in a BEGIN bloc (executed as soon as parsed) wheras in the second case, it's made during execution. Generally, whith the "use" syntax, after the name of the module to use, you put a list of words that will be imported in your name space. But if the list contains just one parameter and if this parameter is a hash, you can do more than just import names : you can configure lots of things in a BEGIN bloc. This might be useful to have 'prints' from further BEGIN blocs (other 'use' calls...) catched for further analysis... So, the 'configure' class method accepts a hash as single parameter. The 'configure' method can be called automatically with the 'use' syntax : the 'use' parameter is the same as the one in the configure method. For the 'trace mecanism', only the 'trace' key is used. The value of this key is another hash. This inside hash accepts 'print' and 'full' keys : In order to debug a special module, you can add 'special prints' on a special 'file handle'. Let's call this file a 'debug file'. This special file has the following properties : To sum up, a print on the 'debug file' makes one the following action : The interface is too light at present ('manage_debug_file' funtion) and should be set. Insert text at the end of the "Text::Editor::Easy" instance. Not yet finished (only one line can be inserted, now). Returns a Cursor object from a "Text::Editor::Easy" instance. See "Text::Editor::Easy::Cursor" for a list of methods available for the Cursor object. Delete one character. Used with "Text::Editor::Easy::Abstract". Should not be part of the interface... Allow the use of Line object with the "display" instance method : the internal reference of the Line object, an integer, is given to the display sub of "Text::Editor::Easy::Abstract". Line objects are scalar reference (for encapsulation), and they can't be recovered between threads after a dump of the structure (the substitution is done by the calling thread but the "display execution" is done by the graphical thread with the help of the "File_manager" thread). Delete one or more characters. Used with "Text::Editor::Easy::Abstract". Should not be part of the interface... In scalar context, this method returns the name of the file (without the path) if any (undef if the Text::Editor::Easy instance is a memory edition). In list context, returns the absolute path, the file name (without path), the relative path (to current path) and the name of the instance. Returns a Line object that represents the first line of the "Text::Editor::Easy" instance. Given the name of a Zone object and a number, this class method returns the instance of the Text::Editor::Easy object if it is found. Undef otherwise : Class method : returns the editor instance who had the focus when ctrl-f was pressed. Call to editor_visual_search : replacement of line object (scalar reference, memory adress specific to one thread) by the internal reference of the line (common for all threads). Class method. Returns a "Text::Editor::Easy" object whose file name is the parameter given. Class method. Returns a "Text::Editor::Easy" object whose name is the parameter given. Maybe destroy would be a better name... Sebastien Grommier, <sgrommier at free.fr> This module is moving fast. Bugs are not yet managed. Maybe you'd like to know that I started writing this Editor from scratch. I didn't take a single line to any existing editor. The very few editors I had a glance at were too tightly linked to a graphical user interface. Maybe you obtain faster execution results like that, but you do not recycle anything. I wanted an engine which you could plug to, a little like perl has been designed. The best support for this module is the "Editor.pl" program. Read the README file to install the module and launch the "Editor.pl" program. To be in an editor allows you to display information interactively. Full documentation will be accessible from here with version 1.0. In future versions, there will be a "video mode" : perl code to make the images and ogg files for the sound. These videos will cost almost nothing in space compared to actual compressed videos (the sound will be, indeed, the heaviest part of them). All softwares should include "help videos" like what I describe : it would prove that what you are about to use is easy to manipulate and it would give you a quick interactive glance of all the possibilities. But most softwares are awfully limited (or just don't have the ability) when you want to drive them from a private program (yet, interactively, it's often very pretty, but I don't mind : I want POWER !). In my ill productive point of view, most softwares should be written again... This is the reason why I'm designing the editor module and the editor program at the same time : the program asks for new needs, and the editor module grows according to these needs. When the editor program will be usable, the module should be powerful enough to be used by anybody, including the RAD tool and the applications generated by the RAD tool. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/~grommier/Text-Editor-Easy-0.49/lib/Text/Editor/Easy.pm
CC-MAIN-2014-42
refinedweb
3,485
61.67
Dim strConn As String = "Provider=SQLOLEDB.1;Password=xxxx;Persist Security Info=True;User ID=xxx;Initial Catalog=Your database name;Data Source=Your server Name" Dim strsql As String = "Your SQL Command" Dim myconn As New OleDbConnection(strConn) Dim myCommand As New OleDbDataAdapter(strsql, myconn) And don't forget to add Imports System.Data.OleDb Above your public class(On the top of the page ^^ hi every one,hop your fine and thanks for the above mentioned lessons i really need that,so could you plz make the books of these web devoloping with this lesson it will be very usefull . thank bashirrafi from afghanistan on of the most the fan of your site
https://www.daniweb.com/programming/web-development/threads/44879/how-to-connect-sql-database-in-asp-net-using-vb
CC-MAIN-2020-10
refinedweb
115
55.78
Created 12 May 2008 One of the things I hear a lot is that people really miss the Flash media components when they're diving into Flex. So why not use that component you love so much in your Flex projects? The Flex Component Kit for Flash CS3 has been out there for a while now and if you have all the latest updates to Flash, it's even part of your Flash CS3 authoring environment by default now. I have the feeling that people underestimate this feature and don't really appreciate the power of this yet. So I thought it was a good idea to create a little tutorial to show you how easy it is to make Flex components in Flash CS3 and in this case, how to use the Flash media components inside your Flex projects. So we're going to create a Flex component that holds the FLVPlayback component and write a little bit of ActionScript code to make it work in Flex. First, you need to check if your Flash CS3 authoring is up to date. If it is, your commands menu should look like this (see Figure 1): Figure 1.Your commands menu If your Commands menu looks different, make sure you click the "Updates…" option in the Help menu to get all the latest updates. Make a new Flash document and drag and drop the "FLVPlayback" component from the component panel to the stage (see Figure 2). Figure 2.The "FLVPlayback" component Make sure you specify an instance name for that component. I'm calling mine "MyPlayer" (see Figure 3). Figure 3.Instance name for the component Next, make a movieclip from that FLVPlayback component. I'm going to call mine "MyVideoPlayer" (see Figure 4). Figure 4.Make a movie clip from the FLVPlayback component When you've done that, go ahead and double-click the MyVideoPlayer movie clip. Create a new layer and draw a rectangle with the same size as your FLVPlayback component. Convert this into a movie clip and specify its instance name to "boundingBox". Once you use your component in Flex, it will not be visible. Flex will use this "boundingBox" movie clip to determine how big your component actually is. By default, the FLVPlayback component will also show a player skin. If your FLVPlayback component isn't previewing a player skin, you can select the skin you want to use in the parameters panel. In my case, I'm going to select SkinOverAllNoFullNoCaption as my player skin (see Figure 5). Figure 5.Select the skin you want to use in the parameters panel Also, check if the autoPlay parameter and the skinAutoHide parameter are set to "true".. Just copy and paste this code snippet to start with: package { import mx.flash.UIMovieClip; import flash.display.MovieClip; public dynamic class MyVideoPlayer extends UIMovieClip { public function MyVideoPlayer() { super(); } } } Go ahead and save that ActionScript file in the same folder as your FLA and name it "MyVideoPlayer.as". Now go back to your FLA and right-click the MyVideoPlayer movie clip in the Library panel and select "Linkage". You're actually going to link the class file that you just created to this movie clip (see Figure 6). Figure 6.Link the ActionScript class file to the movie clip When you check the "Export for ActionScript" box, your window should automatically look like this (see Figure 7): Figure 7.The Linkage Properties window To verify that you saved and named everything correctly, click the "Edit class definition" icon: This should bring you back to the ActionScript class. if it doesn't, make sure the name is correct and that you saved the ActionScript file in the same folder as your FLA file. Don't forget to click "OK" to save your linkage settings. Now have another look at the Class structure. As you can see, we're going to extend the UIMovieClip class. This class has all the methods a normal Flex component has. That means I can automatically use getters and setters like any other Flex components have. So the first function I'm going to create is a setter function to specify the video source file url. public function set source(MyVid:String):void{ MyPlayer.play(MyVid); } No rocket science here. I just tell the FLVPlayback component inside my movie clip to play the video file I will pass it. I also want to be able to size the component to whatever size I want. You could use the standard width and height setters but I'm not going to do that. I'm actually going to override these setters so I can set the width and height of the FLVPlayback component instead of the whole component. If I wouldn't do that, my player skin would become distorted and stretched. So go ahead and add these lines of code: override public function set width(w:Number):void{ MyPlayer.width = w; } override public function set height(h:Number):void{ MyPlayer.height = h; } Your class file should now look like this: package { import mx.flash.UIMovieClip; import flash.display.MovieClip; public dynamic class MyVideoPlayer extends UIMovieClip { public function MyVideoPlayer() { super(); } public function set source(MyVid:String):void{ MyPlayer.play(MyVid); } override public function set width(w:Number):void{ MyPlayer.width = w; } override public function set height(h:Number):void{ MyPlayer.height = h; } } } Now we are ready to "bake" our Flex component. Select the MyVideoPlayer movie clip in the library window and then select the "Convert Symbol to Flex Component" command in the Commands menu. Chances are Flash will give you a little popup window telling you that your frame rate doesn't match the default frame rate that Flex uses (see Figure 8). Figure 8. The frame rate popup window Just go ahead and click "OK". In the Output window, Flash will ask you to publish your file: Select File > Publish to create the SWC file for use in Flex. Obviously, this is what you want to do next. When you did that, Flash created a couple of files for you (see Figure 9): Figure 9. The files Flash created for you The SWC file is the one we will be using in Flex. Open up Flex Builder 3 and create a new project. The first thing we need to do is to add our component to the Flex library so it knows that this is now available. In Flex Builder 3 it's as easy as just copying the SWC file into the libs folder of your project. You can even drag it in there straight from your Finder or Explorer window. If you've done that, you also need to add the player skin you're using. This goes into the src folder. So go ahead and drag "SkinOverAllNoFullNoCaption.swf" to the src folder of your Flex project. Your project folder should now look like this (see Figure 10): Figure 10. Project folder structure Now open the main MXML file of your project. In my case it's called "FlashFlexMarriage.mxml". If your Flex Builder is in Design view, switch to Code view. When you start typing "MyVideoPlayer", you will see that Flex Builder now knows your component and gives you codecompletion for it. When you hit Enter, the "local" namespace will be added to the application descriptor and your component will be added. Now you can add the source of your FLV. <local:MyVideoPlayer Go ahead and run this project. Your video should start playing instantly. I think it would be nicer to see this video a bit bigger and because we added the width and height setters, we can do that without distorting our player skin. <local:MyVideoPlayer When you run it again, you'll see that the player skin is still proportioned in the same way. Where to go from here You have now successfully created a Flex component in Flash. Obviously, this is just an example and you can do so much more but I think this shows how powerful the combination of Flash and Flex can be. Visit the Flex Developer Center and Flash Developer Center for more developer resources.
https://www.adobe.com/devnet/flex/articles/video_flex.html
CC-MAIN-2017-39
refinedweb
1,358
72.26
PostGIS is a geospatial extension to PostgreSQL which gives a bunch of functions to handle geospatial data and queries, e.g. to find points of interest near a certain location, or storing a navigational route in your database. You can find the PostGIS documentation here. In this example, I’ll show how to create a location aware website using Ruby on Rails, PostgreSQL, and PostGIS. The application, when finished, will be able to store your current location – or a check-in – in the database, show all your check-ins on a map, and show check-ins nearby check-ins. This app is written in Rails 3.1 but it could just as well be written in another version. As of writing, the current version of the spatial_adapter gem has an issue in Rails 3.1 but we will create a workaround for this until it gets fixed. You can view the complete source code or see the final application in action. We will first create our geospatially enabled database. First check out out my post on installing PostgreSQL and PostGIS on Mac OS X. Create your database: $ createdb -h localhost my_checkins_development Install PostGIS in your database: $ cd /opt/local/share/postgresql90/contrib/postgis-1.5/ $ psql -d my_checkins_development -f postgis.sql -h localhost $ psql -d my_checkins_development -f spatial_ref_sys.sql -h localhost Your database is now ready for geospatial queries. Create your app: $ rails new my_checkins The spatial_adapter gem is a plugin that adds geospatial functionality to Rails when using a PostgreSQL and PostGIS. It uses GeoRuby for data types. Add this and the pg (Postgres) gem to your Gemfile: gem 'spatial_adapter' gem 'pg' Run bundle install: bundle install $ bundle install Setup your config/database.yml: development: adapter: postgresql database: my_checkins_development host: localhost And your app is geospatially enabled Let’s create some scaffold code to handle our check-ins: $ rails g scaffold checkin title:string location:point Take notice of the point data type – that’s a geospatial type. Before running your migrations, edit db/migrate/create_checkins.rb, replacing this: t.point :location with this: t.point :location, :geographic => true This tells your migration to add a geographic column that is set up to handle geographic coordinates, also known as latitudes and longitudes. Run your migrations: $ rake db:migrate We are now ready to store our check-ins. The Checkin model now contains a location field which is a data type of GeoRuby::SimpleFeatures::Point. This data type has properties of x and y. We will expose these as properties directly on the model. In app/models/checkin.rb: class Checkin < ActiveRecord::Base def latitude (self.location ||= Point.new).y end def latitude=(value) (self.location ||= Point.new).y = value end def longitude (self.location ||= Point.new).x end def longitude=(value) (self.location ||= Point.new).x = value end end Latitude and longitude are now exposed. In app/views/checkins/_form.html.erb, replace this: <div class="field"> <%= f.label :location %><br /> <%= f.text_field :location %> </div> With this: <div class="field"> <%= f.label :latitude %><br /> <%= f.text_field :latitude %> </div> <div class="field"> <%= f.label :longitude %><br /> <%= f.text_field :longitude %> </div> If it wasn’t for a little bug in spatial_adapter under Rails 3.1, we would now be able to save locations from our Rails app. However, what the bug does is that it cannot create records when the location field is set. It can update them so what we will do is to make sure it first creates the check-in with a location set to nil and then updates it with the correct location. Like this, in app/controllers/checkins_controller.rb in the create method, replace this: def create ... if @checkin.save ... def create ... if @checkin.valid? location = @checkin.location @checkin.location = nil @checkin.save! @checkin.location = location @checkin.save! ... And it should work. Try and fire up your server: $ rails s And go to in your browser. Next, in app/views/checkins/show.html.erb, replace this: <p> <b>Location:</b> <%= @checkin.location %> </p> <p> <b>Location:</b> <%= @checkin.latitude %>, <%= @checkin.longitude %> </p> And it will show the latitude and longitude you just entered. We would like to be able to create check-ins from our current location. Modern browsers exposes this functionality via a JavaScript API. Create app/assets/javascripts/checkins.js and add this: function findMe() { if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { document.getElementById('checkin_latitude').value = position.coords.latitude; document.getElementById('checkin_longitude').value = position.coords.longitude; }, function() { alert('We couldn\'t find your position.'); }); } else { alert('Your browser doesn\'t support geolocation.'); } } And a button in the top of app/views/checkins/_form.html.erb: <input type="button" value="Find me!" onclick="findMe();" /> Try it in your browser. If it gives you a JavaScript error saying the findMe method isn’t defined, try restarting your server to get the new javascript loaded. You should now be able to get your current location by clicking the Find me! button. Let’s create a method for finding nearby check-ins. PostGIS has a function named ST_DWithin which returns true if two locations are within a certain distance of each other. In app/models/checkin.rb, add the following to the top of the class: class Checkin < ActiveRecord::Base scope :nearby_to, lambda { |location, max_distance| where("ST_DWithin(location, ?, ?) AND id != ?", checkin.location, max_distance, checkin.id) } ... In app/controllers/checkins_controller.rb, add the following: def show @checkin = Checkin.find(params[:id]) @nearby_checkins = Checkin.nearby_to(@checkin, 1000) ... In app/views/checkins/show.html.erb, add the following just before the links in the bottom: <h2>Nearby check-ins</h2> <ul> <% @nearby_checkins.each do |checkin| %> <li><%= link_to checkin.title, checkin %></li> <% end %> </ul> It now shows all nearby checkins. Try adding a couple more based on your current location and see it in action. Wouldn’t it be nice to show all our check-in on a map? We will do this using the Google Maps API. In app/views/checkins/index.html.erb, clear out the table and list, and add the following: <script type="text/javascript" src=""></script> That loads the Google Maps JavaScript API functionality. Create a div for the map: <div id="map" style="width: 600px; height: 500px;"></div> And add the following script at the bottom: <script type="text/javascript"> // Create the map var map = new google.maps.Map(document.getElementById("map"), { mapTypeId: google.maps.MapTypeId.ROADMAP }); // Initialize the bounds container var bounds = new google.maps.LatLngBounds(); <% @checkins.each do |checkin| %> There’s our map Check it out at. Try creating some check-ins around the world to see the map expand. That’s a location aware app that stores check-ins based on our current location, shows nearby check-ins, and displays check-ins on a map. View the complete source code or see the final application in action. I'd love to hear your thoughts! Write a comment, Follow me on Twitter, or Subscribe to my.
http://www.codeproject.com/Articles/312398/Creating-a-location-aware-website-using-Ruby-on-Ra?fid=1677668&df=10000&mpp=10&sort=Position&spc=None&tid=4444296&noise=1&prof=True&view=Expanded
CC-MAIN-2016-30
refinedweb
1,153
51.44
04 July 2011 12:02 [Source: ICIS news] HONG KONG (ICIS)--China-based Hengli Petrochemical (?xml:namespace> “We are building two PTA units with a capacity of 2.2m tonnes/year each in The first PTA plant will start up in the second quarter of 2012, while the second plant will come on stream three months after the first plant begins production, Lin said. The company is a subsidiary of Chinese polyester major Hengli Group, which is planning to expand its existing polyester capacities to consume the fresh PTA supply, Lin added. Hengli Group is based in The Global PX-Polyester Chain Focus 2011 conference
http://www.icis.com/Articles/2011/07/04/9474636/chinas-hengli-group-builds-two-pta-plants-start-ups-set-in-12.html
CC-MAIN-2014-10
refinedweb
105
68.5
. This is a bit of a primer. It's mostly put it in because documentation is forced to have an example, even if it's intended as a stub article. If you already know unit-testing basics, feel free to skip forward to the remarks, where specific frameworks are mentioned. Unit testing is ensuring that a given module behaves as expected. In large-scale applications, ensuring the appropriate execution of modules in a vacuum is an integral part of ensuring application fidelity. Consider the following (trivial) pseudo-example: public class Example { public static void main (String args[]) { new Example(); } // Application-level test. public Example() { Consumer c = new Consumer(); System.out.println("VALUE = " + c.getVal()); } // Your Module. class Consumer { private Capitalizer c; public Consumer() { c = new Capitalizer(); } public String getVal() { return c.getVal(); } } // Another team's module. class Capitalizer { private DataReader dr; public Capitalizer() { dr = new DataReader(); } public String getVal() { return dr.readVal().toUpperCase(); } } // Another team's module. class DataReader { public String readVal() { // Refers to a file somewhere in your application deployment, or // perhaps retrieved over a deployment-specific network. File f; String s = "data"; // ... Read data from f into s ... return s; } } } So this example is trivial; DataReader gets the data from a file, passes it to the Capitalizer, which converts all the characters to upper-case, which then gets passed to the Consumer. But the DataReader is heavily-linked to our application environment, so we defer testing of this chain until we are ready to deploy a test release. Now, assume, somewhere along the way in a release, for reasons unknown, the getVal() method in Capitalizer changed from returning a toUpperCase() String to a toLowerCase() String: // Another team's module. class Capitalizer { ... public String getVal() { return dr.readVal().toLowerCase(); } } Clearly, this breaks expected behavior. But, because of the arduous processes involved with execution of the DataReader, we won't notice this until our next test deployment. So days/weeks/months go by with this bug sitting in our system, and then the product manager sees this, and instantly turns to you, the team leader associated with the Consumer. "Why is this happening? What did you guys change?" Obviously, you're clueless. You have no idea what's going on. You didn't change any code that should be touching this; why is it suddenly broken? Eventually, after discussion between the teams and collaboration, the issue is traced, and the problem solved. But, it begs the question; how could this have been prevented? There are two obvious things: Our reliance upon manual testing let this bug go by unnoticed far too long. We need a way to automate the process under which bugs are introduced instantly. Not 5 weeks from now. Not 5 days from now. Not 5 minutes from now. Right now. You have to appreciate that, in this example, I've expressed one very trivial bug that was introduced and unnoticed. In an industrial application, with dozens of modules constantly being updated, these can creep in all over the place. You fix something with one module, only to realize that the very behavior you "fixed" was relied upon in some manner elsewhere (either internally or externally). Without rigorous validation, things will creep into the system. It's possible that, if neglected far enough, this will result in so much extra work trying to fix changes (and then fixing those fixes, etc.), that a product will actually increase in remaining work as effort is put into it. You do not want to be in this situation. The second problem noted in our above example is the amount of time it took to trace the bug. The product manager pinged you when the testers noticed it, you investigated and found that the Capitalizer was returning seemingly bad data, you pinged the Capitalizer team with your findings, they investigated, etc. etc. etc. The same point I made above about the quantity and difficulty of this trivial example hold here. Obviously anyone reasonably well-versed with Java could find the introduced problem quickly. But it's often much, much more difficult to trace and communicate issues. Maybe the Capitalizer team provided you a JAR with no source. Maybe they're located on the other side of the world, and communication hours are very limited (perhaps to e-mails that get sent once daily). It can result in bugs taking weeks or longer to trace (and, again, there could be several of these for a given release). In order to mitigate against this, we want rigorous testing on as fine a level as possible (you also want coarse-grained testing to ensure modules interact properly, but that's not our focal point here). We want to rigorously specify how all outward-facing functionality (at minimum) operates, and tests for that functionality. Imagine if we had a test, specifically ensuring that the getVal() method of Capitalizer returned a capitalized string for a given input string. Furthermore, imagine that test was run before we even committed any code. The bug introduced into the system (that is, toUpperCase() being replaced with toLowerCase()) would cause no issues because the bug would never be introduced into the system. We would catch it in a test, the developer would (hopefully) realize their mistake, and an alternative solution would be reached as to how to introduce their intended effect. There's some omissions made here as to how to implement these tests, but those are covered in the framework-specific documentation (linked in the remarks). Hopefully, this serves as an example of why unit testing is important.
https://sodocumentation.net/java/topic/8155/unit-testing
CC-MAIN-2020-29
refinedweb
927
55.64
Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.. Average Rating: Based on 17 Ratings "5 stars" - by Anonymous on 29-DEC-2012 Reviewer Rating: I have been a software developer for many years. I started to study java 4 years ago, but due to life's circumstances I had to put off my studies and learn others technologies. This book helped me to brush up on my java skills in a short period of time. I wish the author published another book with more advanced topics. Report as Inappropriate "One of the best books ever for learning Java" - by chico1198 on 30-APR-2012 Reviewer Rating: Yakov has the pulse on how people actually learn - show them something, lead them through it, and then challenge them to push the envelope themselves: repeat chapter after chapter. As a former C++ developer, I could fly through each chapter and really learn the material. When I combined it with my other knowledge, I felt as if I was ready to take on the Java job market. The only con I could find in the book was that when the book entered the Java EE phase, the coverage was not quite as complete and the examples were not as challenging. However, this is a minor quibble as to use Java EE one will need to really dig in and go well beyond the book anyway. Thanks Yakov. You did a great job. You really helped me. Report as Inappropriate "Gaps keep this book down..." - by The Saj on 25-APR-2012 Reviewer Rating: Seriously, there is ABSOLUTELY nothing I hate more than examples that do not work. A beginner book needs above ALL else to have concise, complete, and functioning examples. A number of the examples in this book fail to provide the necessary info. 1. Abstract classes example uses Payable interface but has no example of a compatible Payable class. 2. Swing example where the author instructs the reader to add a button. JButton myButton = new JButton ("Click me"); add(myButton); The author claims "This code will work..." but it won't. Not unless you have additional knowledge. Coming from an AS3 background I knew enough to add: import javax.swing.JFButton; & myHello.add(myButton); But someone just stepping into the Java world (ie: someone that would read a 24 hour trainer) won't necessarily know this. What if JButton was packaged as: import javax.swing.components.JButton How would a new user know that's where to go. Sure, I am familiar with Eclipse and I know I can CNTRL-CLICK to open the class. But what about someone who has never used Eclipse, or is using another Java coding environment. The point being, is it becomes very frustrating when examples don't work. Every author should pay some neophyte to try every example in their book before publishing. Don't cut corners, don't take for granted, that knowledge you have, that another might not. Nothing discourages a new learner more than trying half a dozen examples and not being able to get any to work regardless of the code being typed perfectly. *** UPDATE: Seriously, just read a couple pages on ENUMERATORS which ends by informing you it is deprecated and to use ITERATORS instead. Seriously, when a brain is trying to absorb a bunch of information. Don't throw bad, old, deprecated info. This just confuses and overloads the learner. Instead the author should have expounded on ITERATORS than put a NOTE: ENUMERATORS operate in a similar fashion, but lack xxx ability. ENUMERATORS are considered deprecated however you may still encounter their use in older code. I DO NOT, DO NOT, DO NOT want to waste time reading a page only to find out everything I read was deprecated. *** That said there is good knowledge here. I just wish Yakov Fain would make a few updates/corrections to the online version at least. Report as Inappropriate "So-So" - by PaulL on 12-JUL-2011 Reviewer Rating: The book gives a great insight to how java programing works; however, the try-it sections are incomplete it seems. It is nearly impossible to understand what they are asking for and when you download the lessons from their website it doesn't match what the try-it wants. Report as Inappropriate "Wonderful!" - by Rupa Lahiri on 02-JUL-2011 Reviewer Rating: Its wonderful in covering several topics and explaining practical application of the concepts. Report as Inappropriate Top Level Categories: Information Technology & Software Development Sub-Categories: Information Technology & Software Development > Programming Programming > Java
http://my.safaribooksonline.com/book/programming/java/9780470889640?cid=201105-cnl-bk-java24
CC-MAIN-2013-20
refinedweb
769
54.93
Eclipse Community Forums - RDF feed Eclipse Community Forums Advising Build Units - "internal advice" <![CDATA[Hi, In b3 we want to support advice on build units using two different mechanisms: - advice provided inside a build unit (e.g. the way Buckminster CSPEX works) - advice externally injected (or decoration if you prefer that term). This post is about the first form - advise provided inside the build unit. In Buckminster, the advice is supported directly by the various readers. In b3, I think we should support buckminster's CSPEX as well as other mechanisms to provide advice (I am sure we are going to get a great xtext based way to express advice for instance). I have been thinking how this could be supported while keeping meta data translators free of this concern. The current model selects a meta data translator based on a resolver, and the namespace of the requested component. It seems natural to add a second extension mechanism that kicks in as a second step. A Buckminster advisor could operate on any IResolver that implements IEFSBasedAccess looking for the file /buckminster.cspex for instance. Basically, it is a "chained" resolver that gets a resolution as additional input. However, since all advice providers should be given a chance, there is a need to iterate - perhaps letting the first win (as two forms of internal advice at the same time (i.e. both a buckminster.cspex, and some newer form of adivce) seems a bit odd. Alternativly, all meta data translators are given a list of files / probes that indiciate the precense of advice - it would then be the meta data translators job to detect if the advice is present - and then hand over to the advisor. This would enable a non EFS based meta data translator to also use internal advice. Apart from that benefit, the solution is just less clean IMO. Thoughts? Handling injected advice is a topic on its own. - henrik]]> Henrik Lindberg 2009-09-22T23:24:12-00:00
http://www.eclipse.org/forums/feed.php?mode=m&th=182169&basic=1
CC-MAIN-2015-40
refinedweb
331
63.7
Download Ajile 1.2.1 at! This release includes the following changes: * New: iCab 3.0.3+, OmniWeb 5.6+, Opera 5+, and SeaMonkey 1.0+ support. * New: Firebug, YUI, & Mochikit log level (info, warn, error) support. * New: Added on-demand loading to SyntaxHighlighter's JScript Brush. * New: Ajile's re-initialization is now auto-detected and handled. * New: Ajile's version is now preserved even when removed from its file name. * New: Global undefined property support for pre-JavaScript 1.3 browsers. * Improved: Fixed script double-loading bug observed in IE browsers. * Improved: Fixed log output bug observed in the compressed release. * Improved: Updated IE detection to use JScript conditional compilation. * Improved: Ajile's runtime instance is now a lightweight object literal. * Improved: Ajile's runtime source is now DOM invisible. * Improved: Faster & more efficient directive fail-safes. * Improved: More robust Import & Include listener notification. * Improved: More robust & efficient Ajile.ShowLog(). * Improved: Performance boost via fail-fasts, variable caching, & less strings. * Improved: Updated Examples page content, layout & keyboard navigation.... read more Ajile 1.x will be available by January 1st! I've been busy working to improve stability and compatibility with as many browsers as possible. Improvements to be expected include: * Support for Opera 5+ * Faster initialization. * Faster and more robust logging. * Better IE detection and performance. * Other bug fixes. Stay tuned at:, a December release may be around the corner ;-) Download Ajile 0.9.9.2 at! This release includes the following changes: * Improved: IE support via refactored Ajile.Unload(). * Improved: Fixed logging typo caused by Ajile 0.9.9's refactoring. * Improved: Safari support via Namespace in SyntaxHighlighter. See the About section at and play with the Demos for a better understanding of the improvements in this release.... read more Download Ajile 0.9.9.1 at! This release includes the following changes: * Improved: Fixed MVC bug observed when "." is in a page's query string. * Improved: Fixed minor regression caused by Ajile 0.9.9's refactoring. * Improved: Code cleanup on Examples page. * Improved: Fixed errors in Directives & Options API documentation.... read more Download Ajile 0.9.9 at! This release includes the following changes: * Improved: Faster Import via code refactoring. * Improved: Fixed bug with versioned Imports and Includes. * Improved: Fixed bug with wildcard Includes. * Improved: Code cleanup and refactoring for improved performance. * Improved: Fixed debug log/Firebug compatibility issue. * Improved: Fixed Directives API documentation typos.... read more Download Ajile 0.9.8 at! This release includes the following changes: * New: Mozilla 0.9.1+ added to supported browsers list. * New: Cloaking now supported in IE 5.01+. * New: Now uses YUI Compressor for code compression (~25K). * New: Examples page now use SyntaxHighlighter 1.5.1 for code highlighting. * Improved: Ajile.Unload() now unloads empty com.iskitz.ajile namespace. * Improved: Ajile.Unload() now unloads all legacy directives. * Improved: Updated Ajile.Unload() description in API docs. * Improved: Naming conflict warning provides more alternatives. * Improved: Code cleanup and refactoring for better cross-browser support. * Improved: Examples page clean-up and LoadExample correction. * Improved: Restored Examples page support for Blazer 3.0 on Treo 600. * Improved: Fixed month error in debug log's date-time stamp.... read more Download Ajile 0.9.5 at! This release includes the following changes: * New: Include directive for importing without short-name access. * New: Now supports Camino 1.0+ browsers. * Improved: Cloaking now degrades gracefully for older browsers. * Improved: Cleaner log output with shorter timestamp & better grouping. * Improved: Added protection for improper instantiation of custom data types. * Improved: Better support for older browsers. * Improved: General code cleanup.... read more Download Ajile 0.9 at! This release includes the following changes: * New: Supports all Firefox, IE 4.01+, and Netscape 6.0.1+ browsers. * New: Ajile.Unload([ns|module]) for namespace & module unloading. * New: Now uses jsUnit as testing framework. * New: Debug log integration with Firebug, MochiKit, & YUI loggers. * Improved: Full API backwards compatibility to JSPackaging 1.0 using legacy option. * Improved: Stronger defense against external Object.prototype changes. * Improved: Simplified examples & updated Examples page with unobtrusive scripting. * Improved: Compressed using custom_rhino.jar. * Improved: Discontinued packer use; broke working code & incompatible with IE 4 & 5.... read more Ajile 0.9 will be available by August 1st! Stability will be the main focus, with improvements in: * Importing with override. * API backwards compatibility. * 3rd party log integration. * Runtime cloaking. * Object.prototype change defense. Stay tuned at:, a July release may just be possible! Download Ajile 0.7.9 at: This release includes the following changes: * New: legacy load-time option to control backwards compatibility. * New: Ajile.EnableLegacy() to control backwards compatibility. * New: Legacy support is disabled by default. * New: Added documentation for all load-time options. * Improved: Ajile.EnableOverride() now works as intended. * Improved: Added packed version to download; used Dean Edward's Packer. * Improved: Removed documentation for deprecated features.... read more Download Ajile 0.7.8 at: This release includes the following changes: * New: Safari support added. * Improved: Import handling of circular references. See the About section at ajile.iskitz.com and play with the Demos for a better understanding of the improvements in this release. Download it at Download Ajile 0.7.5 at: This release includes the following changes: * New: Active defense against external Object.prototype changes. * Improved: Treo 600 Blazer 3.0 browser support restored. * Improved: Import behavior stabilized for supported browsers. * Improved: Import more reliable for slow connections. * Improved: Import("some.namespace.*") leakage stopped. * Improved: More accurate Import & Load event logging. * Improved: General code cleanup & other minor fixes.... read more Ajile 0.7 includes the following changes: * New: refresh load-time option to manipulate script caching. * New: Ajile.EnableRefresh() to manipulate script caching. * Improved: More efficient & reliable Import for supported browsers. * Improved: More compatible cloaking for varied Import scenarios. * Improved: More accurate and informative debug logging. * Improved: Logging of Import listener notifications. * Improved: Logging of Namespace load-time options. * Improved: Removed status bar message. * Improved: General code cleanup and other minor fixes.... read more Get Ajile 0.6.5 at []. This release contains improvements to the import listener feature, the reintroduction of the shared auto-loader, and other improvements. View for the latest news and documentation.
https://sourceforge.net/p/ajile/news/
CC-MAIN-2018-22
refinedweb
1,025
55.3
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. Pycalverter - Python Calendar Converter. Any one know how to implement this tool? py . Please check the above two links. Hi, Copy the file calverter.py into your module In the file __init__.py import the file : import calverter In your code re-import calverter using the path of your module and type : cal = calverter.calverter() jd = cal.gregorian_to_jd(2014, 04 , 23) print jd print cal.jd_to_islamic(jd) The outopu will be : 2456770.5 (1435, 6, 22) I implemeted it for my module and it works well. Thanks for your reply Yug Faa. Shall i ask you a doubt? i created two char fields for both islamic date and gregorian date. When i enter islamic date on islamic date field, it should convert into geogorian & display in gregorian date field. How should i wrote python code for that? Please help me. Firstly fi this help you, please make it resolved, for the next problem the georgian date have to be a date field and for the islamic is char, you can use on_change feature or make the georgian field as function hi Yug Faa .. please check this py file. import calverter class convertor_convertor(osv.osv): _description = "converting dates" _name = "convertor" { cal = calverter.calverter() jd = cal.gregorian_to_jd(2014, 04 , 23) print jd print cal.jd_to_islamic(jd) } convertor_convertor() please tell me is this is the correct form of our code. hi i implement this code syntax error at cal = calverter.calverter() , How to solve this. can you paste you code in pastebin.com and post the link here ? but before can you make this question SOLVED ! no . I did n't make this here is the link. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/pycalverter-python-calendar-converter-any-one-know-how-to-implement-this-tool-50471
CC-MAIN-2018-13
refinedweb
329
70.6
I've been plugging away at a recent endeavor and have run into an issue with abstract classes. I have a class that, within it, has an ArrayList of an object. Said object is an abstract class. I have a few classes extending this abstract class and providing specialized functionality. Now, I need some way to get an object of a certain type, and I need some way to also remove an object of a certain type. That is, I need to be able to check my ArrayList for one of the extended classes, and then from there I can either return it or delete it depending on the method. All that sounds pretty mixed up, so I'll provide an example: public class ClassA { ArrayList<ClassB> objects = new ArrayList<ClassB>(); public ClassB getClassB(ClassB) { // iterate through objects ArrayList and find what I need } public void removeClassB(ClassB) { // iterate through objects ArrayList and delete what I need } } public abstract class ClassB { // abstract class stuff } public class ClassC extends ClassB { // ... } public class ClassD extends ClassB { // ... ClassC myClassC; myClassC = ClassA.getClassB(myClassC); // Here's where the issue is // ... ClassA.removeClassB(ClassC); } So, I have a class that's maintaining a list of abstracted classes. I need to be able to check the list to see if I have an instance of one of the abstracted classes. If anymore clarifying needs to be done, let me know. Any help would be appreciated! Thank you all ahead of time.
http://www.dreamincode.net/forums/topic/291666-abstract-class-confusion/
CC-MAIN-2016-26
refinedweb
245
72.66
Welcome to Gatsby (or GatbyJS), a powerful framework for static site generation that leverages GraphQL and React. Gatsby’s popularity increases as time goes on, and more and more people are starting to use it. One of the reasons for this is its ability to help you create a simple static website straightforward and quickly. You just whip out one of their Starter Kits, set up an account on Netlify, and boom, you have a website. I also used to set up websites that way. I saw an opportunity to create a blog instantly without much fuss and went for it. But a problem occurred later when I tried to add some complex logic to my blog. I didn’t really understand what was going on behind the scenes. What is Gatsby doing, and why does it seem so magical? For that reason, I decided to take a step back and build a Gatsby blog from scratch. In this post, I will share how to build a blog from a simple Gatsby starter kit and explain how Gatsby works behind the scenes. The post should bring clarity into how this opinionated framework for building static sites ticks, and how you can customize it to fit your needs. Required Tooling Before we begin, you will need to have a couple of things set up on your machine. Quickly check if you have Node.js with node --version in your terminal. You should be getting NPM with Node.js, but check that quickly with npm -- version . If both commands return a version, you are good to go. If not, you can follow the instructions on NPM’s website. Now that we’ve gotten that out of the way, we can install Gatsby CLI locally. Gatsby CLI is needed to call commands that will generate our repo, start our development server, and even build our blog’s production code. To install it, you can do the following: npm install -g gatsby-cli Quickly verify that Gatsby got installed with gatsby --version. After installing and checking everything we need to start our development, we can dive into it head first. Initializing The Repo To start the blog, we will use the simple hello-world start kit from Gatsby. This kit is a minimalistic one that does not give you much at first. We are doing this to understand Gatsby and its internals better. If you want to set up your website quickly, you can always opt-in for Gatsby’s other kits. Let us create our working directory: gatsby new my-new-blog After Gatsby CLI finishes installing everything, we can get into our blog’s directory with cd my-new-blog and start the server using gatsby develop. This command will set up a bunch of things for us and make our website available at. If you open it, you can see the usual “Hello world!”. Yay! Our blog lives and breathes. But what happened just now? Yes, we ran a couple of commands in our terminal and greeted the whole world on our new blog, but how did that happen? Let us start by looking into the src/pages/index.js file: import React from "react" export default function Home() { return <div>Hello world!</div> } A perfectly simple React component that just says hello to the world. When we run gatsby develop, it will recognize src/pages/index.js file and treat it as logic that is for our blog’s root page. Gatsby figures this out on its own, and that is why we see the “Hello world” text when we visit the index page. If you try to make some changes to this file, the server that is watching all the changes in our directory will update the website automatically. How neat! Having just one file and using Gatsby sounds like overkill (and it is). That’s why we will add things to our blog and explain the process along the way. Gatsby and GraphQL GraphQL is a language to query your API and get data you need, with a strong emphasis on doing it one request. Being able to collect a lot of data in one request means that you don’t have to do multiple round-trips to your server and back. Besides all of this, you need to define a schema from which you can base your queries. Gatsby smartly does this. To better understand how Gatsby and GraphQL work, let us first add some data to our website. The first thing you probably want to add is some general information about your blog. For example, a title and description of your website are useful to anyone visiting. Let’s define this data inside the gatsby-config.js file. We will use this file later for some other endeavors, but now, let’s make it like this: module.exports = { /* Your site config here */ siteMetadata: { title: 'My New Blog', description: 'This is my awesome blog I made from scratch!' }, plugins: [], } Now, let’s display this data to our users in the browser. If we go to the src/pages/index.js, we can add a simple GraphQL query to fetch the data we just added: import React from "react" import { graphql } from "gatsby" export default function Home({ data }) { const { title, description } = data.site.siteMetadata return ( <div> <h1>{title}</h1> <p>{description}</p> </div> ) } export const pageQuery = graphql` query MetadataQuery { site { siteMetadata { title description } } } ` At the bottom of the file, we will put the GraphQL query that will fetch the title and description we previously added to the gastby-config.js. GraphQL makes this data available, and Gatsby does the fetching. We don’t have to call the query explicitly. The fetching will be done for us in the build process. This efficient build process is why Gatsby is defined as “disgustingly fast,” since it does all the page data fetching before the data is loaded in the browser. Of course, you can write some extra fetching logic in your components, but those were not be loaded before by default. Gatsby will make this data available during the build process (when we run gatsby develop ) to the GraphQL by recognizing that there is some GraphQL logic inside the src/pages/index.js. Also, the siteMetadata object we added to the gatsby-config.js will be available to the GraphQL. If you want, you can see what else is available in the GraphiQL tool here:. This is available to you locally when you run the server. We successfully managed to pull in some data to our one-page blog, and we managed to figure out how Gatsby deals with data. But this is still not near a blog someone would read. We need to make it a bit friendly. Let’s add a picture of a cute dog and pave the way to add and read files in Gatsby. Managing Pictures To make our blog more engaging, we will add a picture. I will add a picture of a cute dog I found on the internet to a new directory: src/images. The final path should look like this: src/images/cute-dog.jpg. To show this image the Gatsby way, we need to install a Gatsby plugin. Plugins are helpful libraries that make our lives easier when building Gatsby websites, and there are a lot of useful ones you can browse here. The main idea is not to write your solution for usual tasks and features like SEO, RSS, offline support, and — you guessed it — images. The one we are going to use is called gatsby-source-filesystem. By the name of it, you can tell that it is related to files somehow. You are correct! This plugin will help us perform a query for that cute dog image using GraphQL. To install it, run this: npm install --save gatsby-source-filesystem Then, if you remember gatsby-config.js, we will use it to tell Gatsby that we have a plugin for it, like so: module.exports = { /* Your site config here */ siteMetadata: { title: "Myasd New Blog", description: "This is my awesome blog I made from scratch!", }, plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images/`, }, }, ], } Besides the data we added in the previous step, we now added the details about the gatsby-source-filesystem plugin. In the options, we specified the name of the source — “images” — and we specified the path where our images will sit. Defining a name is an important step, and you might wonder why we need to set this. Gatsby can read data from different sources — not just our file system. Another example of a source would be WordPress or Contentful. So, our filesystem is just one possibility where we could store our images or blog posts, and setting a name to “images” could help us distinguish different sources and handle them in another manner in the future. Anyways, after we added the plugin, if we look at the server we are running in our terminal, there should be the following message: warn develop process needs to be restarted to apply the changes to gatsby-config.js We need to restart the server for the new plugin to be picked up by Gatsby. Let’s restart our server. Gatsby is known to have issues with npm install, so if you get an error when you add gatsby-source-filesystem plugin, make sure to either rm -rf node_modules && npm install or npm install react react-dom gatsby. After the server starts, we can try to fetch the image in our src/pages/index.js file: import React from "react" import { graphql } from "gatsby" export default function Home({ data }) { const { title, description } = data.site.siteMetadata return ( <div> <h1>{title}</h1> <p>{description}</p> <img alt="Cute dog" src={data.image.publicURL} /> </div> ) } export const pageQuery = graphql` query MetadataQuery { site { siteMetadata { title description } } image: file(base: { eq: "cute-dog.jpg" }) { publicURL } } ` We expanded our GraphQL query to search for a file with the name “cute-dog.jpg”. We then told GraphQL to alias that file to image so we can reference it meaningfully later in the code. And lastly, in our code, we put a JSX image tag and referenced the image’s public URL there. And voilà, we got the image to show up on our page: What we built is nice and all, but we still don’t have any blog posts on our blog, so let’s add them in the next chapter. Handling Markdown Files Since the age of Jekyll, it became popular to write content using Markdown, a lightweight markup language. We will do the same for our blog. Let’s add our first blog post inside src/blog/my-first-post.md: --- title: Awesome Blog Post Title author: Nikola date: 2020-07-15 --- ## Introduction to my blog post Great content of my first blog At the top is the front matter that represents general info about the post. After this comes the content. Let’s not get wild here at the beginning and use simple content that we can build on later. Since we added the src/blog directory and we plan to store all our Markdown files there, let’s define this in our gatsby-config.js: plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images/`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `blog`, path: `${__dirname}/src/blog/`, }, }, ], Now we have 2 places that Gatsby should know about: src/images and src/blog. We could go ahead and use the similar query we used for getting the image, but let’s try out a plugin Gatsby offers called gatsby-transformer-remark. This plugin allows you to use Remark, a Markdown processor, and cut down on time spent parsing all of the Markdown files. You can install this plugin using: npm install --save gatsby-transformer-remark Put it inside gatsby-config.js: plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images/`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `blog`, path: `${__dirname}/src/blog/`, }, }, `gatsby-transformer-remark`, ], Now we restart the gatsby develop server. Perfect! To have our blog post show up, we will build a separate page for it in src/pages/blog.js: import React from "react" import { graphql } from "gatsby" export default function Blog({ data }) { const { posts } = data.blog return ( <div> <h1>My blog posts</h1> {posts.map(post => ( <article key={post.id}> <h2>post.frontmatter.title</h2> <small>{post.frontmatter.author}, {post.frontmatter.date}</small> <p>{post.excerpt}</p> </article> ))} </div> ) } export const pageQuery = graphql` query MyQuery { blog: allMarkdownRemark { posts: nodes { frontmatter { date(fromNow: true) title author } excerpt id } } } ` Here, we are querying for all Markdown files using allMarkdownRemark, which is available from the plugin we installed gatsby-transformer-remark. This allows us to directly fetch front matter that includes the date, title, and author. We can also pass in a parameter to date(fromNow: true), which displays relative time e.g. “5 days ago”. If it weren’t for the gatsby-transformer-remark, we would have to parse this ourselves somehow. Then, in the blog component, we list all the blog posts with their information to the user. Notice how we don’t have links to any blog posts, but we will add this later. Luckily, Gatsby will pick up all these changes and make a new page available at /blog. If we go to the /blog, we should see something like this: You can add another Markdown file inside src/blog, and it will automatically get picked up by Gatsby. Pretty cool! But how do I access a separate blog post on its own? Well, this is where things get tricky. Read on to find out how to do it. Creating Pages Dynamically To create links to all the blog posts, we need to tell Gatsby to create them for us. This section is where you should keep most of your attention because we now get to play with Gatsby internals. So far, we’ve installed plugins, added data, and wrote some Markdown and JSX, but now it’s time to get down and dirty. Playing Around With Nodes First, let’s get introduced to the term “Node” in Gatsby. As the Gatsby docs say, the “node” is the center of the Gatsby’s data system. Everything that we add in terms of data is represented as the node object in Gatsby. If you go back and look at the query we made to fetch all Markdown posts, you can see that we query for nodes. gatsby-source-filesystem “scans” the directories we tell it to, and creates nodes for each file in those directories. Then gatsby-markdown-remark comes, parses data inside the nodes, and adds extra fields to those node objects. Furthermore, Gatsby then concludes and comes up with a GraphQL schema for those nodes, based on their content. Wow, probably a lot of things to take in at once. I bet it will be easier if we see an example. Let us start by creating a slug for each of our blog posts. For example, since we added src/blog/my-first-post.md, we want to see that blog post when we visit /my-first-post. To do that, we will leverage createFilePath function that comes with gatsby-source-filesystem that will do this for us. Having just created a slug, we will also create a node we described in the section above. The best place to make a slug is the onCreateNode API that Gatsby exposes. Plugins and users like us can use onCreateNode to customize nodes or do other things when nodes get created or updated. Logic like this is put inside gatsby-node.js, a new file which we will create:, }) } } If you go ahead and restart the server, quickly open GraphiQL tool locally: () and query for slugs with this query: { allMarkdownRemark { edges { node { fields { slug } } } } } You should see slugs of those 2 Markdown blog posts we previously added: Pretty neat! We told Gatsby to expand each Markdown node with the field slug, which we can use to redirect users to our blog posts. But wait, if you try to visit /another-blog-post, you will get 404. Which is fine, because we didn’t create the actual pages, we just generated slugs. Follow the next section to learn how to do this. Programatically Spawning Pages Lucky for us, Gatsby exposes createPages API, which allows us to do just that. But, before we proceed with adding more logic to gatsby-node.js, we need to do something else. Since Gatsby pages use React, each page needs to have a React component that will render the data. For that purpose, we will create a component for our blog post, and put it in src/templates/blog-post.js: import React from "react" export default function BlogPost() { return <div>Hello blog post</div> } As you can see, it is a straightforward component that doesn’t utilize any of the data. We will change this later. We must have some kind of a React component to tell Gatsby to render our blog posts. With that, let us add some logic to gatsby-node.js to create the actual blog post pages: const path = require(`path`), }) } } exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions const result = await graphql(` query { allMarkdownRemark { edges { node { fields { slug } } } } } `) result.data.allMarkdownRemark.edges.forEach(({ node }) => { createPage({ path: node.fields.slug, component: path.resolve(`./src/templates/blog-post.js`), context: { // Data passed to context is available // in page queries as GraphQL variables. slug: node.fields.slug, }, }) }) } We added what seems to be a lot of code to our page creation logic. In short, this is what happens: - We query for all Markdown pages and get their slugs - Then, we go through all of them and call createPage In the createPage, we specify the path of the page, the component we just added src/templates/blog-post.js, and we pass in the context which we will explain in a jiff If you go ahead and restart your server and try to visit, you should see the simple “Hello blog post” text we added in our component before. Instead, we should see the content we put in our Markdown file. Let’s change our src/templates/blog-post.js to be like this: import React from "react" import { graphql } from "gatsby" export default function BlogPost({ data }) { const post = data.markdownRemark return ( <div> <h1>{post.frontmatter.title}</h1> <small>{post.frontmatter.date}</small> <div dangerouslySetInnerHTML={{ __html: post.html }} /> </div> ) } export const query = graphql` query BlogQuery($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title } } } ` Now we use the data in the Markdown files, as opposed to just showing “Hello blog post”. One thing to notice is that we use the $slug variable that we specified when creating the page in gatsby-node.js. Slug is also available as the props inside the BlogPost component. Using the slug we defined in createPage, we then query Markdown nodes for the matching node. Then, in the component, we use the fields we specified in the query to properly show the blog post. If you open the now, you should see your blog post in full light the way you defined it in the Markdown file. That was pretty intense, trying to create slugs and pages, and show the data inside the files. Congratulations for making it this far! As a cherry on top of the cake, let’s tie it all up by linking to those blog posts from our blog page. Finishing Up As you know, we created the /blog page, but we didn’t link to it from the home page. Let’s do it quickly with adding to the src/pages/index.js: <Link to="/blog">Read my blog</Link> Then, let’s link to each blog post from our blog page: import React from "react" import { graphql, Link } from "gatsby" export default function Blog({ data }) { const { posts } = data.blog return ( <div> <h1>My blog posts</h1> {posts.map(post => ( <article key={post.id}> <Link to={post.fields.slug}> <h2>{post.frontmatter.title}</h2> </Link> <small> {post.frontmatter.author}, {post.frontmatter.date} </small> <p>{post.excerpt}</p> </article> ))} </div> ) } export const pageQuery = graphql` query MyQuery { blog: allMarkdownRemark { posts: nodes { fields { slug } frontmatter { date(fromNow: true) title author } excerpt id } } } ` We imported the Link component from Gatsby that will handle the routing for us. Then, we query for the slug in the GraphQL query. We later use that slug to form a link to each blog post. And that’s it! You just built a simple blog made using Gatsby from scratch. Ideas To Try Out The blog post we built still looks far from finished, but it should be easy going from now on. You have all the fundamentals in place to expand the blog. Here are some ideas you can try: - Switch blog post paths to be from /blog/*(hint: editing pathvariable when we call createPage) - Show all posts from the homepage - Add some style to your blog - Deploy it and let the world know what you have to say! Conclusion Kudos for making it! If you came this far, you should have learned how to build a simple blog with an understanding of the internals of Gatbsy on a high level. The concepts of nodes and how Gatsby handles data should be a breeze for you now. Also, I hope that Gatsby’s magic is a bit demystified for you. All in all, Gatsby is a great tool to set up your static site quickly. There are many other tools and ways to go about it, but understanding the essence and what is going on behind the curtains is always a step in the right direction. I hope this knowledge sticks with you in the future and helps you build great websites. If you liked the post, consider sharing it with your friends and coworkers. Until next time, cheers!
http://blog.logrocket.com/creating-a-gatsby-blog-from-scratch/
CC-MAIN-2020-40
refinedweb
3,667
72.05
12-29-2011 07:42 AM Hi Friends, I am confusion with Preprocessor which was given by RIM in follow link, as they said i have done preprocessor concept for Different OS as follows, I have installed Eclipse with BlackBerry Java Plug-in Version: 1.3.0.201102031007-19 (which is having by defalult os if 6.0.0) so i don't have lower OS. if i want to write a code for both OS 5 and OS 6 how do i write. For Preprocessors, i have added manually BlackBerryOS5.0.0 to the Bulid path. in my code it is defines as , //#ifdef BlackBerrySDK6.0.0 import net.rim.device.api.gps.LocationInfo; //#endif When i installed in OS 6 Devices it runs successfully but when i installed in OS5 Devices it shows, net.rim.device.api.gps.location not found. Please help me here. Regards, K.Narasinga Rao. Solved! Go to Solution. 12-29-2011 06:18 PM 12-30-2011 12:38 AM Hi, I have already installed Blackberry OS 6.0 then how can i install downgrade version of the blackberry. If possible can you please provide me a link to it to download OS5.0 and install into Same Eclipse Folder path. K.Narasinga Rao. 12-30-2011 11:25 AM I went to the developer site, this is the link for the plugin: Look at "Eclipse updates" to be able to download the 5.0 SDK. Then you can change which SDK the project uses, it will automatically change the preprocessor to be 5.0. 01-01-2012 11:25 PM thank you, I will check and download the API 5.0 and respond with the result.. 01-02-2012 01:43 AM hi thanks for this help. I got the required SDK.
http://supportforums.blackberry.com/t5/Java-Development/Blackberry-Preprocessor-Help/m-p/1485801#M187111
crawl-003
refinedweb
300
76.72
!- Search Loader --> <!- /Search Loader --> When compiling with ifort 17 on Linux, I notice very different GLIBC dependencies than when compiling with icc. In particular, the following code program main write(*,*) 'Hello world!' end program main when compiled on my RHEL 6 system (GLIBC2.11) produces an executable that when examined with objdump -x shows dependencies on 0x0d696914 0x00 10 GLIBC_2.4 0x0d696913 0x00 08 GLIBC_2.3 0x0d696917 0x00 07 GLIBC_2.7 0x06969191 0x00 06 GLIBC_2.11 0x09691974 0x00 05 GLIBC_2.3.4 0x09691a75 0x00 02 GLIBC_2.2.5 On the other hand, an equivalent C program: #include <stdio.h> int main() { // call a function in another file printf("Hello world!\n"); return(0); } shows dependencies only on 0x0d696914 0x00 04 GLIBC_2.4 0x09691a75 0x00 03 GLIBC_2.2.5 0x09691974 0x00 02 GLIBC_2.3.4 Is there a way to eliminate the GLIBC2.11 dependency of the executable generated by ifort? Compiling with ifort -D_XOPEN_SOURCE=500 results in no complains but identical GLIBC dependencies. Bit late to comment here, but I just ran into the same problem. Ifort 2017 and newer have the __isoc99_sscanf symbol mentioned in their libifcore, and also __longjmp_chk in libirc. The first generates a GLIBC_2.7 dependency, the second ups this to GLIBC_2.11. I believe this means that ifort 2017 and newer can no longer be used to compile code for older systems such as RHEL/CentOS 5. To be fair, Intel also states in the release notes of ifort 2017 that they only support RHEL 6/7 (this was 5/6/7 in ifort 2016).
https://community.intel.com/t5/Intel-Fortran-Compiler/ifort-GLIBC-dependencies/td-p/1137155
CC-MAIN-2020-50
refinedweb
260
78.04
Cathy Dumas's Blog BISM documentation expressions ExpressionTextBox hostable editor hosted compiler imports designer least discoverable feature PDC09 SQL Server 2012 Tabular Model type browser Visual Basic women in technology Browse by Tags MSDN Blogs > Cathy Dumas's Blog > All Tags > hostable editor Tagged Content List Blog Post: Hostable editor keyboard shortcuts Cathy Dumas -... on 2 Mar 2010 Blog Post: Imports designer 101 Cathy Dumas - Oh, the imports designer . This innocuous looking piece of UI packs a lot of functionality in a little designer. You would think that this designer should be pretty straightforward. The original concept of this feature was that this would simply be the place to manage namespaces, much in the same way... on 18 Feb 2010 Blog Post: End-to-end expression editing feature deck Cathy Dumas - Hi, today I gave a talk to our support team about the expression editing feature. Since this is all public facing information, I thought I would post the deck. Some of this information is old hat to regular readers of this blog (especially the overview and programmability bits, which I ported straight... on 21 Jan 2010 Blog Post: Enter and Tab key handling in the ExpressionTextBox Cathy Dumas - The Enter and Tab keys work a bit differently in the ExpressionTextBox than in the big VB IDE. In the big IDE, Enter and Tab always insert their associated characters. If the IntelliSense completion list is up, Enter selects the item and inserts a new line. We noticed that big IDE behavior does not always... on 18 Jan 2010 Blog Post: Expression editing mechanics Cathy Dumas - This is what happens when you edit an expression in Visual Studio. To simplify things, pretend you started with a blank expression. Here’s what goes on behind the scenes: When you click on an ExpressionTextBox , an instance of the hostable editor is created. As you type, you will notice two things: You... on 9 Nov 2009 Blog Post: Design time expression editing 101 Cathy Dumas - Here... on 2 Nov 2009 Page 1 of 1 (6 items) © 2015 Microsoft Corporation. Trademarks Privacy & Cookies Report Abuse 5.6.426.415
http://blogs.msdn.com/b/cathyk/archive/tags/hostable+editor/
CC-MAIN-2015-32
refinedweb
354
61.46
PROFIL(2) BSD Programmer's Manual PROFIL(2) profil - control process profiling #include <unistd.h> int profil(char *samples, size_t size, u_long offset, u_int scale);. If the scale value is nonzero and the buffer samples contains an illegal address, profil() returns -1, profiling is terminated, and errno is set appropriately. Otherwise, profil() returns 0. /usr/lib/gcrt0.o profiling C run-time startup file gmon.out conventional name for profiling output file The following error may be reported: [EFAULT] The buffer samples contains an invalid address. gprof(1) This routine should be named profile(). The samples argument should really be a vector of type unsigned short. The format of the gmon.out file is undocumented..
http://www.mirbsd.org/htman/sparc/man2/profil.htm
CC-MAIN-2015-48
refinedweb
115
52.56
11 March 2009 09:00 [Source: ICIS news] By Mark Watts LONDON (ICIS news)--Borealis posted a net loss of €122m ($154m) in the fourth quarter of 2008, dropping from a €58m gain in the same period a year earlier due to plummeting demand, the Austria-based petrochemicals producer said on Wednesday. More than half the loss was due to inventory impairment at year-end, the company said. Borealis’ sales dropped 16% in the fourth quarter to €1.35bn, while it fell to an operating loss of €199m from a gain of €28m in the year earlier period. For the full year of 2008, the company posted a 55% drop in net profit to €239m. “Though the global recession has impacted our business, we have come through 2008 with some solid results,” said CEO Mark Garrett. “We expect 2009 to remain very difficult, probably more difficult than 2008 and we don’t really expect to see an improvement in demand in the world economy until 2010,” he told ICIS news. Borealis is facing the triple impact of the financial crisis, falling demand in key end-user markets and the effect of large-scale polyolefins plants coming on stream in the near-term. Demand from the automotive industry for polypropylene (PP) had remained flat this year and was not expected to improve, though Borealis, along with other major PP producers, had noted resilience in food packaging applications. The company plans to restrict capital spending as much as possible in 2009 and focus on its two major projects in ?xml:namespace> Garrett said expansion of the Borouge petrochemicals complex and its new 350,000 tonne/year low density polyethylene (LDPE) plant in "Outside those two investments we've been trying to preserve as much cash as we can to allow us to make those investments," said Garrett. "They're vital for our future," he added. "If we can complete them, with Borouge scheduled for mid-2010, we could catch the beginnings of improvement in the global economy." Borealis had been lucky that it managed to set up its financing and debt repayment schedules before the crisis hit, Garret said, “We have about €500m of committed back-lines which don’t mature for the most-part until 2013,” added CFO Daniel Shook. “We don’t have much debt maturing over the next several years, we’ve got a good liquidity position and will continue to work with our banks to makes sure that’s robust,” he added. Borealis’ interest-bearing debt increased by €453m in 2008 largely due to investment projects such as the LDPE plant in Stenungsund. Borealis has suspended its shareholders' dividend until business conditions improve. The company is jointly owned by ($1 = €0.79) To discuss issues facing the chemical industry go to ICIS connect.
http://www.icis.com/Articles/2009/03/11/9199125/borealis-posts-q4-net-loss-of-122m-as-demand-bottoms-out.html
CC-MAIN-2013-20
refinedweb
465
56.29
azkaban 0.1.9 Azkaban CLI Lightweight command line interface (CLI) for Azkaban: - Define jobs from a single python file. - Build projects and upload to Azkaban from the command line. Quickstart We first create a configuration file for our project. Let's call it jobs.py, although any name would work. Here's a simple example of how we could define a project with a single job and static file: from azkaban import Job, Project project = Project('foo') project.add_file('/path/to/bar.txt', 'bar.txt') project.add_job('bar', Job({'type': 'command', 'command': 'cat bar.txt'})) if __name__ == '__main__': project.main() The add_file method adds a file to the project archive (the second optional argument specifies the destination path inside the zip file). The add_job method will trigger the creation of a .job file. The first argument will be the file's name, the second is a Job instance (cf. Job options). Once we've saved our jobs file, the following. Running python jobs.py --help shows the list of options for each of the previous commands. Job options The Job class is a light wrapper which allows the creation of .job files using python dictionaries. It also provides a convenient way to handle options shared across multiple jobs: the constructor can take in multiple options dictionaries and the last definition of an option (i.e. later in the arguments) will take precedence over earlier ones. We can use this to efficiently share default options among jobs, for example: defaults = {'user.to.proxy': 'boo', 'retries': 0} jobs = [ Job({'type': 'noop'}), Job(defaults, {'type': 'noop'}), Job(defaults, {'type': 'command', 'command': 'ls'}), Job(defaults, {'type': 'command', 'command': 'ls -l', 'retries': 1}), ] All jobs except the first one will have their user.to.proxy property set. Note also that the last job overrides the retries property. Alternatively, if we really don't want to pass the defaults dictionary around, we can create a new Job subclass to do it for us: class BooJob(Job): def __init__(self, *options): super(BooJob, self).__init__(defaults, *options) More. Nested options Nested dictionaries can be used to group options concisely: # e.g. this job Job({ 'proxy.user': 'boo', 'proxy.keytab.location': '/path', 'param.input': 'foo', 'param.output': 'bar', }) # is equivalent to this one Job({ 'proxy': {'user': 'boo', 'keytab.location': '/path'}, 'param': {'input': 'foo', 'output': 'bar'}, }) Pig jobs Because pig jobs are so common, a PigJob class is provided which accepts a file path (to the pig script) as first constructor argument, optionally followed by job options. It then automatically sets the job type and adds the corresponding script file to the project. from azkaban import PigJob project.add_job('baz', PigJob('/.../baz.pig', {'dependencies': 'bar'})) Using a custom pig type is as simple as changing the PigJob.type class variable. Merging projects If you have multiple projects, you can merge them together to create a single project. The merge is done in place on the project the method is called on. The first project will retain its original name. from azkaban import Job, Project project1 = Project('foo') project1.add_file('/path/to/bar.txt', 'bar.txt') project1.add_job('bar', Job({'type': 'command', 'command': 'cat bar.txt'})) project2 = Project('qux') project2.add_file('/path/to/baz.txt', 'baz.txt') project2.add_job('baz', Job({'type': 'command', 'command': 'cat baz.txt'})) # project1 will now contain baz.txt and the baz job from project2 project), ... - Downloads (All Versions): - 1441 downloads in the last day - 5389 downloads in the last week - 15240 downloads in the last month - Author: Matthieu Monsch - License: MIT - Categories - Package Index Owner: mtth - DOAP record: azkaban-0.1.9.xml
https://pypi.python.org/pypi/azkaban/0.1.9
CC-MAIN-2014-10
refinedweb
599
59.6
#include <item_cmpfunc.h> Convert and cache a constant. When given item is a constant and its type differs from comparison type then cache its value to avoid type conversion of this constant on each evaluation. In this case the value is cached and the reference to the cache is returned. Original value is returned otherwise. Checks whether compare_datetime() can be used to compare items. SYNOPSIS Arg_comparator::can_compare_as_dates() left, right [in] items to be compared DESCRIPTION Checks several cases when the DATETIME comparator should be used. The following cases are accepted: In all other cases (date-[int|real|decimal]/[int|real|decimal]-date) the comparison is handled by other comparators. Compare strings byte by byte. End spaces are also compared. Compare item values as dates. Compare items values as DATE/DATETIME for regular comparison functions. The correct DATETIME values are obtained with help of the get_datetime_value() function. Compare signed (*left) with unsigned (*B) Compare values as BIGINT UNSIGNED. Compare unsigned (*left) with signed (*B) Compare two Item objects as JSON. If one of the arguments is NULL, and the owner is not EQUAL_FUNC, the null_value flag of the owner will be set to true. Compare NULL values for two arguments. When called, we know that at least one argument contains a NULL value. Compare arguments using numeric packed temporal representation. Check if str_arg is a constant and convert it to datetime packed value. Note, const_value may stay untouched, so the caller is responsible to initialize it. Comparison function are expected to operate on arguments having the same data types. Since MySQL has very loosened up rules, it accepts all kind of arguments which the standard SQL does not allow, and then it converts the arguments internally to ones usable in the comparison. This function transforms these internal conversions to explicit CASTs so that the internally executed query becomes compatible with the standard At the moment nodes are injected only for comparisons between: 1) temporal types and numeric data types: in which case the comparison is normally done as DOUBLE, so the arguments which are not floating point, will get converted to DOUBLE, and also for 2) comparisons between temporal types: in which case the comparison happens as DATETIME if the arguments have different data types, so in this case the temporal arguments that are not DATETIME will get wrapped in a CAST to DATETIME. WL#12108; This function will limit itself to comparison between regular functions, aggregation functions and fields, all of which are constant for execution (so this excludes stored procedures, stored functions, GC, user defined functions, as well as literals). For const arguments, see type conversions done in fold_condition. Sets compare functions for various datatypes. NOTE The result type of a comparison is chosen by item_cmp_type(). Here we override the chosen result type for certain expression containing date or time or decimal expressions. A function pointer that is used for retrieving the value from argument "left". This function is only used when we are comparing in a datetime context, and it retrieves the value as a DATE, TIME, DATETIME or YEAR, depending on the comparison context. Only used by compare_json() in the case where a JSON value is compared to an SQL value. This member points to pre-allocated memory that can be used instead of the heap when converting the SQL value to a JSON value.
https://dev.mysql.com/doc/dev/mysql-server/latest/classArg__comparator.html
CC-MAIN-2021-49
refinedweb
558
54.12
2nd December 2014 | By: marcinkawa Using SOAP with SUDS – an introduction I’m sure that most of you reading this post have heard/used the XML/SOAP – same as me. However I’d never used the WSDL before, yet last week I needed to work with two, unconnected to each other APIs, using this protocol. So I’ve started researching WSDL and apparently it is the standard protocol for describing API methods of web services. WSDL stands for Web Services Description Language and is an XML document that uses SOAP to exchange information. It allows you to send requests and receive responses from a remote server. One of the interesting and useful things about this protocol is that it describes the accepted types and methods really precisely. That allows you to easily prepare empty objects (like template) which is formatted in a way the server can accept. The most common language that we’re using in-house is Python (by the way, it’s an awesome language). The choice of available WSDL libs for python is not great and a lot of libs that exist out there are just outdated. It seems that the only one that is noteworthy is suds. Suds is a lightweight SOAP python client for consuming Web Services. And its use is really straightforward. from suds.client import Client url = '' client = Client(url) You can easily inspect the service types and methods by parsing client object to string. print client Suds ( ) version: 0.4 GA build: R699-20100913 Service ( AutomatedBatchService ) tns="" Prefixes (1) ns0 = "" Ports (1): (AutomatedBatchPort) Methods (22): addalias(authElem authElem, xs:string userAddressOrId, xs:string aliasAddress, xs:string confirm, ) adddomain(authElem authElem, xs:string orgNameOrId, adddomainargs args, ) . . # Other functions . suspenduser(authElem authElem, xs:string userAddressOrId, xs:string optArgStr1, xs:string optArgStr2, xs:string optArgStr3, ) test(xs:boolean should_work, ) Types (67): AdminBlockException AuthenticationException . . # Other types . testResponse userRecord As I mentioned before we know exactly how the functions and types are built. Thereby we can use object factory provided by suds. Let’s say we want to execute the `adddomain` method. To do that we need to prepare three objects whose types are `authElem`, xs:string, adddomainargs. auth = client.factory.create('authElem') args = client.factory.create('adddomainargs') print auth (authElem){ apiKey = None email = None pword = None xauth = None } print args (adddomainargs){ domain = None } As we can see the objects were created for us. In the case of `orgNameOrId` we don’t need to create a special type as it is just a simple string. Anyway, now we just need to fill the created objects with proper data. auth.apiKey = '< your api key >' auth.email = 'info@aeguana.com' auth.pword = '< your password >' auth.xauth = '< your auth key >' orgNameOrId = '' args.domain = '' And call the method: resp = adddomain(auth, orgNameOrId, args) But (there is always a ‘but’), sometimes the XML is broken and/or the namespace defined in the XML document is unknown. Therefore we can not create the suds client and we are getting back an error, each time we try to do it. And as it was in my case one of the services was causing this error: TypeNotFound: Type not found: '(Array,, )' The solution for this is really easy but it’s hard to figure out what’s happening at the beginning. I found some help by reading the post here on Parky’s Place blog. To solve the issue we need to tell suds which namespace our XML is using. To find out what namespace it is we need to look at the XML file header. <definitions xmlns: # XML body </definitions> The value from fields “xmlns:tns” and “targetNamespace” are the ones we are interested in. As we can see the namespace used in this document is “urn:idu”. So now we need to instruct the suds client to use this namespace: tns = "urn:idu" imp = Import('', '') imp.filter.add(tns) client = Client(url, plugins=[ImportDoctor(imp)]) That’s it, our client is ready to work now!
http://blog.aeguana.com/2014/12/02/using-soap-with-suds-an-introduction/
CC-MAIN-2021-17
refinedweb
662
63.29
X a serial device. Configuring the Modules: IMPORTANT: The latest versions of X-CTU support Linux so don’t follow the older guides found online which require ‘wine’ installation on Linux to run it. Firstly, download and install X-CTU. The official guide from DIGI will walk you through this process. Once you are done with this, plug in your XBee adapter and launch X-CTU. The device should get detected automatically and you’ll be presented with a screen similar to the one seen below. Now it is important to note that this is not an ordinary XBee adapter which is why you’ll see many more options than usual. Firstly, all your devices should be have same Modem VID (ID) and Hopping Channel (HP) for them to communicate. Now, further settings will depend on your individual requirements but just to explain some important parameters: - Multi-Transmit (MT): To set/read number of additional broadcast re-transmissions. All broadcast packets are transmitted MT+1 times to ensure it is received. - Broadcast Radius (BR): To set/read the transmission radius for broadcast data transmissions. Set to 0 for maximum radius. If BR is set greater than Network Hops then the value of Network Hops is used. - Mesh Retries (MR): To set/read maximum number of network packet delivery attempts. If MR is non-zero, packets sent will request a network acknowledgement, and can be resent up to MR times if no acknowledgements are received. Once you are done configuring your XBee PRO adapter as per your mesh network configurations, you are now ready to start using them. Using Python for Serial Communication To carry out serial communication using Python, first we need to install pySerial. Skip to Step 2 if you already have pip installed. sudo apt-get install python-pip sudo pip install pyserial Now, to have bi-directional or full duplex communication, we’ll have to use threads which ensure that read and write can happen simultaneously. Here is a small python script which does that: import serial from threading import Thread ser = serial.Serial("/dev/ttyUSB0", 9600, timeout=1) def read_serial(): while True: if ser.inWaiting() > 0: print ser.readline() def write_serial(): while True: x = input("Enter: ") ser.write(x) t1 = Thread(target=read_serial) t2 = Thread(target=write_serial) t1.start() t2.start() To fix the issue of having to set the port manually every time or hard-coding it, you can add the lines below in your python script and then call the function connect, as provided below, to automatically detect the USB port. This will only work for one XBee adapter connected to the computer. import subprocess def connect(): global ser, flag x = subprocess.check_output("ls /dev/serial/by-id", shell = True).split() if x[0].find("Digi") != -1: y = subprocess.check_output("dmesg | grep tty", shell = True).split() indices = [i for i, x in enumerate(y) if x == "FTDI"] address = "/dev/" + y[indices[-1]+8] ser = serial.Serial(address, 9600, timeout = 1) ser.flushInput() ser.flushOutput() flag = 0 else: raise ValueError Now you have configured the adapters and written a basic Python Script to carry out serial communication on a Mesh Network. For advanced usage, look in to: - pySerial API: - This library has many more advanced functionalities to configure the port being used. The example code snippets provided on the website serve as a good starting point. - Threading API: - This library has many advanced functions to control the operation of a thread. One thing to look in particular is thread lock which is useful while operating on shared data structures between threads. Resources - To compare the DigiMesh architecture to ZigBee mesh architecture, you can refer to this guide which points out the pros and cons of both. - For detailed information, please refer to the User Guide. The guide has details regarding technical specifications, internal and overall communication architecture, command reference tables, etc.
https://roboticsknowledgebase.com/wiki/networking/xbee-pro-digimesh-900/
CC-MAIN-2021-04
refinedweb
646
56.76
This patch fixes a regression introduced by:commit bb29ab26863c022743143f27956cc0ca362f258cAuthor: Ingo Molnar <mingo@elte.hu>Date: Mon Jul 9 18:51:59 2007 +0200This caused the jiffies counter to leap back and forth on cpufreq changeson my x86 box. I'd say that we can't always assume that TSC does "smallerrors" only, when marked unstable. On cpufreq changes these errors can behuge.The original bug report can be found here:: Stefano Brivio <stefano.brivio@polimi.it>---diff --git a/arch/x86/kernel/tsc_32.c b/arch/x86/kernel/tsc_32.cindex 9ebc0da..d29cd9c 100644--- a/arch/x86/kernel/tsc_32.c+++ b/arch/x86/kernel/tsc_32.c@@ -98,13 +98,8 @@ unsigned long long native_sched_clock(void) /* * Fall back to jiffies if there's no TSC available:- * ( But note that we still use it if the TSC is marked- * unstable. We do this because unlike Time Of Day,- * the scheduler clock tolerates small errors and it's- * very important for it to be as fast as the platform- * can achive it. ) */- if (unlikely(!tsc_enabled && !tsc_unstable))+ if (unlikely(!tsc_enabled)) /* No locking but a rare wrong value is not a big deal: */ return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ); -- CiaoStefano
http://lkml.org/lkml/2007/12/6/377
CC-MAIN-2017-04
refinedweb
193
65.93
1,3 Numbers whose digits in base 2 are in nonincreasing order. Might be called "nialpdromes". Subset of A077436. Proof: Since a(n) is of form (2^i-1)2^j, i,j>=0, a(n)^2 = [2^(2i)-2^(i+1)]2^(2j) + 2^(2j) where the first sum term has i-1 one bits and its 2j-th bit is zero, while the second sum term switches the 2j-th bit to one, giving i one bits, as in a(n). - Ralf Stephan, Mar 08 2004 Numbers n such that binary representation contains no "01". - Benoit Cloitre, May 23 2004 Every polynomial with coefficients equal to 1 for the leading terms and 0 after that, evaluated at 2. For instance a(13) = x^4 + x^3 + x^2 at 2, a(14) = x^4 + x^3 + x^2 + x at 2. - Ben Paul Thurston, Jan 11 2008 From Gary W. Adamson, Jul 18 2008: (Start) As a triangle by rows starting: 1; 2, 3; 4, 6, 7; 8, 12, 14, 15; 16, 24, 28, 30, 31; ..., equals A000012 * A130123 * A000012, where A130123 = (1, 0,2; 0,0,4; 0,0,0,8;...). Row sums of this triangle = A000337 starting (1, 5, 17, 49, 129, ...). (End) First differences are A057728 = 1; 1; 1; 1; 2,1; 1; 4,2,1; 1; 8,4,2,1; 1;... i.e., decreasing powers of 2, separated by another "1". - M. F. Hasler, May 06 2009 Apart from first term, numbers that are powers of 2 or the sum of some consecutive powers of 2. - Omar E. Pol, Feb 14 2013 A049502(a(n)) = 0. - Reinhard Zumkeller, Jun 17 2015 From Andres Cicuttin, Apr 29 2016: (Start) Numbers that can be digitally generated with twisted ring (Johnson) counters. This is, the binary digits of a(n) correspond to those stored in a shift register where the input bit of the first bit storage element is the inverted output of the last storage element. After starting with all 0’s, each new state is obtained by rotating the stored bits but inverting at each state transition the last bit that goes to the first position (see link). Examples: for a(n) represented by three bits Binary a(5)= 4 -> 100 last bit = 0 a(6)= 6 -> 110 first bit = 1 (inverted last bit of previous number) a(7)= 7 -> 111 and for a(n) represented by four bits a(8) = 8 -> 1000 a(9) = 12 -> 1100 last bit = 0 a(10)= 14 -> 1110 first bit = 1 (inverted last bit of previous number) a(11)= 15 -> 1111 (End) Powers of 2 represented in bases which are members of this sequence must always contain at least one digit which is also a power of 2. This is because 2^i mod (2^i - 2^j) = 2^j, which means the last digit always cycles through powers of 2 (or if i=j+1 then the first digit is a power of 2 and the rest are trailing zeros). The only known non-member of this sequence with this property is 5. - Ely Golden, Sep 05 2017 T. D. Noe and R. Zumkeller, Table of n, a(n) for n = 1..10000, First 5051 terms from T. D. Noe S. M. Shabab Hossain, Md. Mahmudur Rahman and M. Sohel Rahman, Solving a Generalized Version of the Exact Cover Problem with a Light-Based Device, Optical Supercomputing, Lecture Notes in Computer Science, 2011, Volume 6748/2011, 23-31, DOI: 10.1007/978-3-642-22494-2_4. Eric Weisstein's World of Mathematics, Digit Wikipedia, Ring counter Index entries for 2-automatic sequences. a(n) = 2^s(n) - 2^((s(n)^2 + s(n) - 2n)/2) where s(n) = ceiling((-1 + sqrt(1+8n))/2). - Sam Alexander, Jan 08 2005 a(n) = 2^k + a(n-k-1) for 1 < n and k = A003056(n-2). The rows of T(r, c) = 2^r-2^c for 0 <= c < r read from right to left produce this sequence: 1; 2, 3; 4, 6, 7; 8, 12, 14, 15; ... - Frank Ellermann, Dec 06 2001 For n > 0, a(n) mod 2 == A010054(n). - Benoit Cloitre, May 23 2004 A140130(a(n)) = 1 and for n > 1: A140129(a(n)) = A002262(n-2). - Reinhard Zumkeller, May 14 2008 a(n+1) = (2^(n - r(r-1)/2) - 1) 2^(r(r+1)/2 - n), where r=round(sqrt(2n)). - M. F. Hasler, May 06 2009 Start with A000225. If n is in sequence, then so is 2n. - Ralf Stephan, Aug 16 2013 G.f.: (x^2/((2-x)*(1-x)))*(1 + Sum_{k>=0} x^((k^2+k)/2)*(1 + x*(2^k-1))). The sum is related to Jacobi theta functions. - Robert Israel, Feb 24 2015 a(22) = 64 = 32 + 32 = 2^5 + a(16) = 2^A003056(20) + a(22-5-1). a(23) = 96 = 64 + 32 = 2^6 + a(16) = 2^A003056(21) + a(23-6-1). a(24) = 112 = 64 + 48 = 2^6 + a(17) = 2^A003056(22) + a(24-6-1). a:=proc(n) local n2, d: n2:=convert(n, base, 2): d:={seq(n2[j]-n2[j-1], j=2..nops(n2))}: if n=0 then 0 elif n=1 then 1 elif d={0, 1} or d={0} or d={1} then n else fi end: seq(a(n), n=0..2100); # Emeric Deutsch, Apr 22 2006 Union[Flatten[Table[2^i - 2^j, {i, 0, 100}, {j, 0, i}]]] (* T. D. Noe, Mar 15 2011 *) Select[Range[0, 2^10], NoneTrue[Differences@ IntegerDigits[#, 2], # > 0 &] &] (* Michael De Vlieger, Sep 05 2017 *) (PARI) for(n=0, 2500, if(prod(k=1, length(binary(n))-1, component(binary(n), k)+1-component(binary(n), k+1))>0, print1(n, ", "))) (PARI) A023758(n)= my(r=round(sqrt(2*n--))); (1<<(n-r*(r-1)/2)-1)<<(r*(r+1)/2-n) /* or, to illustrate the "decreasing digit" property and analogy to A064222: */ A023758(n, show=0)={ my(a=0); while(n--, show & print1(a", "); a=vecsort(binary(a+1)); a*=vector(#a, j, 2^(j-1))~); a} \\ M. F. Hasler, May 06 2009 (PARI) is(n)=if(n<5, 1, n>>=valuation(n, 2); n++; n>>valuation(n, 2)==1) \\ Charles R Greathouse IV, Jan 04 2016 (PARI) list(lim)=my(v=List([0]), t); for(i=1, logint(lim\1+1, 2), t=2^i-1; while(t<=lim, listput(v, t); t*=2)); Set(v) \\ Charles R Greathouse IV, May 03 2016 (Haskell) import Data.Set (singleton, deleteFindMin, insert) a023758 n = a023758_list !! (n-1) a023758_list = 0 : f (singleton 1) where f s = x : f (if even x then insert z s' else insert z $ insert (z+1) s') where z = 2*x; (x, s') = deleteFindMin s -- Reinhard Zumkeller, Sep 24 2014, Dec 19 2012 A000337(r) = sum of row T(r, c) with 0 <= c < r. See also A003056. Cf. A130123, A175332, A007088, A049502, A101082 (complement). This is the base-2 version of A064222. First differences are A057728. Sequence in context: A077436 A277704 A082752 * A054784 A018585 A018399 Adjacent sequences: A023755 A023756 A023757 * A023759 A023760 A023761 nonn,easy Olivier Gérard Definition changed by N. J. A. Sloane, Jan 05 2008 approved
http://oeis.org/A023758
CC-MAIN-2019-18
refinedweb
1,205
80.01
Welcome to the exciting world of GUI programming with Tkinter. This chapter aims to get you acquainted with Tkinter, the built-in Graphical User Interface (GUI) library for all standard Python distributions. Tkinter (pronounced tea-kay-inter) is the Python interface to Tk, the GUI toolkit for Tcl/Tk. Tcl (Tool command language), which is pronounced as tickle, is a popular scripting language in the domains of embedded applications, testing, prototyping, and GUI development. On the other hand, Tk is an open source, multiplatform widget toolkit that is used by many different languages to build GUI programs. The Tkinter interface is implemented as a Python moduleâ Tkinter.py in Python 2.x Versions and tkinter/__init__.py in Python 3.x Versions. If you look at the source code, Tkinter is just a wrapper around a C extension that uses the Tcl/Tk libraries. Tkinter is suitable for a wide variety of areas, ranging from small desktop applications to scientific modeling and research endeavors across various disciplines. When a person learning Python needs to graduate to GUI programming, Tkinter seems to be the easiest and fastest way to get the work done. Tkinter is a great tool for the programming of GUI applications in Python. The features that make Tkinter a great choice for GUI programming include the following: - It is simple to learn (simpler than any other GUI package for Python) - Relatively little code can produce powerful GUI applications - Layered design ensures that it is easy to grasp - It is portable across all operating systems - It is easily accessible, as it comes pre-installed with the standard Python distribution None of the other Python GUI toolkits have all of these features at the same time. The purpose of this chapter is to make you comfortable with Tkinter. It aims to introduce you to the various components of GUI programming with Tkinter. We believe that the concepts that you will develop in this chapter will enable you to apply and develop GUI applications in your area of interest. The key aspects that we want you to learn from this chapter include the following: - Understanding the concept of a root window and the main loop - Understanding widgetsâthe building blocks of programs - Getting acquainted with a list of available widgets - Developing layouts by using different geometry managers - Applying events and callbacks to make a program functional - Styling widgets by using styling options and configuring the root widget We assume a basic working knowledge of Python. You must know how to write and run basic programs in Python. We will develop our application on the Linux Mint platform. However, since Tkinter is multiplatform, you can follow along with the instructions in this book on Windows, Mac, or any other Linux distribution, without making any modifications to the code. By the end of this chapter, you will have developed several partly functional dummy applications, such as the one shown in the following screenshot: We call these dummy applications because they are neither fully functional nor do they serve any practical purpose other than to show a particular feature of Tkinter. We will write all our projects using Python Version 3.6.3, which is the latest stable release of Python at the time of writing. The Python download package and instructions for downloading for different platforms are available atÂ. The installer binaries for macOS X and the Windows platform are available at the aforementioned link. If you are following along on Unix, Linux, or BSD, the following procedure will install Python from the source. First, install tk8.6-dev and python3-tk packages on your computer using your applicable package manager. For instance, on Debian-based systems such as Ubuntu and Mint, run the following two commands from the Terminal: sudo apt install tk8.6-dev sudo apt install python3-tk Download Python 3.6.3 from the preceding link and extract it to any location of your choice. Open a Terminal in the location where you extracted Python and type in the following commands: ./configure make make test sudo make altinstall This should install Python 3.6.3 on your computer. Now open a command line and enter the following command: $ python3.6 This will open the Python 3.6 interactive shell. Type in the following command: >>> import tkinter This command should execute without any errors. If there are no error messages, the Tkinter module is installed on your Python distribution. When working with examples from this book, we do not support any Python Version except for Python 3.6.3, which comes bundled with Tkinter Tcl/Tk Version 8.6. However, most of the examples should work out-of-the-box on other minor Python 3 Versions. To check whether you have the correct Tkinter Version on your Python installation, type the following commands in your IDLE or interactive shell: >>> import tkinter >>> tkinter._test() This should confirm the Tcl/Tk Version as 8.6. We are now ready to build our GUI programs! The next steps are optional and you may skip them at your discretion. While the preceding steps are sufficient for us to develop our programs, I highly recommend that you use a virtual environment for developing your programs. Virtual environments provide a secluded environment with no conflicts with system programs, and they can be easily reproduced on any other system. So now let's set up a virtual environment. First, create a folder where you will keep all projects from this book. Let's call it myTkinterProjects or whatever suits you. Next, find the location of the Python 3.6 installation on your computer. On my computer, I can find the location of the Python installation by running the following command: $ which python3.6 Take a note of the location. For me it is /usr/local/bin/python3.6. Now open a Terminal in your myTkinterProjects folder and run the following command: $ virtualenv -p /location/of /python3.6 myvenv/ This will create a new virtual environment in a folder named myvenv inside your project folder. Lastly, we need to activate this virtual environment. This is done by running the following command: $ source myenv/bin/activate Now if you type the command python, it should pick up Python 3.6.3 from within your virtual environment. From now onward, every time we have to run a Python script or install a new module, we will first activate the virtual environment using the preceding command and run or install the module within this new virtual environment. As a GUI programmer, you will generally be responsible for deciding the following three aspects of your program: - Which components should appear on the screen? This involves choosing the components that make the user interface. Typical components include things such as buttons, entry fields, checkboxes, radio buttons, and scrollbars. In Tkinter, the components that you add to your GUI are called widgets. Widgets (short for window gadgets) are the graphical components that make up your application's frontend. - Where should the components go? This includes deciding the position and the structural layout of various components. In Tkinter, this is referred to as geometry management. - How do components interact and behave? This involves adding functionality to each component. Each component or widget does something. For example, a button, when clicked on, does something in response. A scrollbar handles scrolling, and checkboxes and radio buttons enable users to make some choices. In Tkinter, the functionality of various widgets is managed by command binding or event binding using callbacks. The following diagram shows the three components of GUI programming: GUI programming is an art, and like all art you need a drawing board to capture your ideas. The drawing board that you will use is called the root window. Our first goal is to get the root window ready. The following screenshot depicts the root window that we are going to create: Drawing the root window is easy. You just need the following three lines of code: import tkinter as tk root = tk.Tk() #line 2 root.mainloop() Save this with the .py file extension or check out the code present in the 1.01.py file. Open it in the IDLE window or run it from within your activated virtual environment using the following command: $ python 1.01.py Running this program should generate a blank root window, as shown in the preceding screenshot. This window is equipped with functional minimize, maximize, and close buttons, and a blank frame. Note Downloading the example code You can download the example code files for all Packt books you have purchased from your account at. Apart from going to Packt's official website, you can also find the code files for this book atÂ. If you purchased this book elsewhere, you can visit and register to have the files emailed directly to you. The following is a description of the preceding code: - The first line imported the tkintermodule into the namespace with tkas its alias. Now we can access all definitions of the classes, attributes, and methods of Tkinter by appending the alias tk to the name as in tk.Tk(). - The second line created an instance of the tkinter.Tkclass. This created what is called the root window, which is shown in the preceding screenshot. According to the conventions, the root window in Tkinter is usually called root, but you are free to call it by any other name. - The third line executed the mainloop (that is, the event loop) method of the root object. The mainloopmethod is what keeps the root window visible. If you remove the third line, the window created in line 2 will disappear immediately as soon as the script stops running. This will happen so fast that you will not even see the window appearing on your screen. Keeping the mainloopmethod running also lets you keep the program running until you press the Closebutton, which exits mainloop. - Tkinter also exposed the mainloopmethod as tkinter.mainloop(). So, you can even call mainloop()directly instead of calling root.mainloop(). Congratulations! You have completed your first objective, which was to draw the root window. You have now prepared your drawing board (root window). Now, get ready to paint it with your imagination! Note Commit the three lines of code (shown in code 1.01.py) to memory. These three lines generate your root window, which will accommodate all the other graphical components. These lines form the skeleton of any GUI application that you will develop in Tkinter. The entire code that will make your GUI application functional will go between line 2 (new object creation) and line 3 ( mainloop) of this code. Now that we have our top level or the root window ready, it is time to think over the question: which components should appear in the window? In Tkinter jargon, these components are called widgets. The syntax that is used to add a widget is as follows: my_widget = tk.Widget-name (its container window, ** its configuration options) In the following example ( 1.02.py ), we will add two widgets, a label and a button, to the root container. Also, note how all the widgets are added between the skeleton code that we defined in the first example: import tkinter as tk root = tk.Tk() label = tk.Label(root, text="I am a label widget") button = tk.Button(root, text="I am a button") label.pack() button.pack() root.mainloop() Running the preceding code( 1.02.py) will generate a window with a label and a button widget, as shown in the following screenshot: The following is a description of the preceding code: - This code added a new instance named labelfor the label widget. The first parameter defined root as its parent or container. The second parameter configured its text option to read I am a label widget. - Similarly, we defined an instance of a Button widget. This is also bound to the root window as its parent. - We used the pack()method, which is essentially required to position the label and button widgets within the window. We will discuss the pack()method and several other related concepts when exploring the geometry management task. However, you must note that some sort of geometry specification is essential for the widgets to be displayed. Note the following few important features that are common to all widgets: - All widgets are actually objects derived from their respective widget classes. So, a statement such as button = Button(its_parent)actually creates a button instance from the Buttonclass. - Each widget has a set of options that decides its behavior and appearance. This includes attributes such as text labels, colors, and font size. For example, the Button widget has attributes to manage its label, control its size, change its foreground and background colors, change the size of the border, and more. - To set these attributes, you can set the values directly at the time of creating the widget, as demonstrated in the preceding example. Alternatively, you can later set or change the options of the widget by using the .config()or .configure()method. Note that the .config()or .configure()methods are interchangeable and provide the same functionality. In fact, the .config()method is simply an alias of the .configure()method. There are two ways to create widgets in Tkinter. The first way involves creating a widget in one line and then adding the pack() method (or other geometry managers) in the next line, as follows: my_label = tk.Label(root, text="I am a label widget") my_label.pack() Alternatively, you can write both the lines together, as follows: tk.Label(root, text="I am a label widget").pack() You can either save a reference to the widget created ( my_label, as in the first example), or create a widget without keeping any reference to it (as demonstrated in the second example). You should ideally keep a reference to the widget in case the widget has to be accessed later on in the program. For instance, this is useful in case you need to call one of its internal methods or for its content modification. If the widget state is supposed to remain static after its creation, you need not keep a reference to the widget. Note Note that calls to pack() (or other geometry managers) always return None. So, consider a situation where you create a widget, and add a geometry manager (say, pack()) on the same line, as follows: my_label = tk.Label(...).pack(). In this case, you are not creating a reference to the widget. Instead, you are creating a None type object for the my_label variable. So, when you later try to modify the widget through the reference, you get an error because you are actually trying to work on a None type object. If you need a reference to a widget, you must create it on one line and then specify its geometry (like pack()) on the second line, as follows: my_label = tk.Label(...) my_label.pack() This is one of the most common mistakes committed by beginners. Now you will get to know all the core Tkinter widgets. You have already seen two of them in the previous exampleâthe Label and Button widgets. Now, let's explore all the other core Tkinter widgets. Tkinter includes 21 core widgets, which are as follows: Let's write a program to display all of these widgets in the root window. The format used to add widgets is the same as the one that we discussed in the previous task. To give you an idea about how it's done, here's some sample code that adds some common widgets: Label(parent, text="Enter your Password:") Button(parent, text="Search") Checkbutton(parent, text="Remember Me", variable=v, value=True) Entry(parent, width=30) Radiobutton(parent, text="Male", variable=v, value=1) Radiobutton(parent, text="Female", variable=v, value=2) OptionMenu(parent, var, "Select Country", "USA", "UK", "India","Others") Scrollbar(parent, orient=VERTICAL, command= text.yview) Can you spot the pattern that is common to each widget? Can you spot the differences? As a reminder, the syntax for adding a widget is as follows: Widget-name(its_parent, **its_configuration_options) Using the same pattern, let's add all the 21 core Tkinter widgets into a dummy application ( 1.03.py). We do not reproduce the entire code here. A summarized code description for 1.03.py is as follows:   - We create a top-level window and a mainloop, as shown in the earlier examples. - We add a frame widget and name it menu_bar. Note that frame widgets are just holder widgets that hold other widgets. Frame widgets are great for grouping widgets together. The syntax for adding a frame is the same as that for all the other widgets: frame = Frame(root) frame.pack() - Keeping the menu_barframe as the container, we add two widgets to it: - Menubutton - We create another frame widget and name it frame. Keeping frameas the container/parent widget, we add the following seven widgets to it: - Label - Entry - Button - Checkbutton - Radiobutton - OptionMenu BitmapClass - We then proceed to create another frame widget. We add six more widgets to the frame: ImageClass - Listbox - Spinbox - Scale - LabelFrame - We then create another frame widget. We add two more widgets to the frame: - Text - Scrollbar - We create another frame widget and add two more widgets to it: - Canvas - PanedWindow These constitute the 21 core widgets of Tkinter. Now that you have had a glimpse of all the widgets, let's discuss how to specify the location of these widgets using geometry managers. You may recall that we used the pack() method to add widgets to the dummy application that we developed in the previous section. The pack() method is an example of geometry management in Tkinter. The pack() method is not the only way of managing the geometry in your interface. In fact, there are three geometry managers in Tkinter that let you specify the position of widgets inside a top-level or parent window. The three geometry managers are as follows: - pack: This is the one that we have used so far. It is simple to use for simpler layouts, but it may get very complex for slightly complex layouts. - grid: This is the most commonly used geometry manager, and provides a table-like layout of management features for easy layout management. - place: This is the least popular, but it provides the best control for the absolute positioning of widgets. Now, let's have a look at some examples of all the three geometry managers in action. The pack manager can be a bit tricky to explain in words, and it can best be understood by playing with the code base. Fredrik Lundh, the author of Tkinter, asks us to imagine the root as an elastic sheet with a small opening at the center. The pack geometry manager makes a hole in the elastic sheet that is just large enough to hold the widget. The widget is placed along a given inner edge of the gap (the default is the top edge). It then repeats the process till all the widgets are accommodated. Finally, when all the widgets have been packed in the elastic sheet, the geometry manager calculates the bounding box for all the widgets. It then makes the parent widget large enough to hold all the child widgets. When packing child widgets, the pack manager distinguishes between the following three kinds of space: - Unclaimed space - Claimed but unused space - Claimed and used space The most commonly used options in pack include the following: side: LEFT, TOP, RIGHT, and BOTTOM (these decide the alignment of the widget) fill: X, Y, BOTH, and NONE (these decide whether the widget can grow in size) expand: Boolean values such as tkinter.YES/ tkinter.NO, 1/ 0, and True/ False anchor: NW, N, NE, E, SE, S, SW, W, and CENTER (corresponding to the cardinal directions) - Internal padding ( ipadxand ipady) for the padding inside widgets and external padding ( padxand pady), which all default to a value of zero Let's take a look at demo code that illustrates some of the pack features. Two of the most commonly used pack options are fill and expand: The following code ( 1.04.py) generates a GUI like the one shown in the preceding screenshot: import tkinter as tk root = tk.Tk() frame = tk.Frame(root) # demo of side and fill options tk.Label(frame, text="Pack Demo of side and fill").pack() tk.Button(frame, text="A").pack(side=tk.LEFT, fill=tk.Y) tk.Button(frame, text="B").pack(side=tk.TOP, fill=tk.X) tk.Button(frame, text="C").pack(side=tk.RIGHT, fill=tk.NONE) tk.Button(frame, text="D").pack(side=tk.TOP, fill=tk.BOTH) frame.pack() # note the top frame does not expand or fill in X or Y directions # demo of expand options - best understood by expanding the root #vwidget and seeing the effect on all the three buttons below. tk.Label (root, text="Pack Demo of expand").pack() tk.Button(root, text="I do not expand").pack() tk.Button(root, text="I do not fill x but I expand").pack(expand = 1) tk.Button(root, text="I fill x and expand").pack(fill=tk.X, expand=1) root.mainloop() The following is a description of the preceding code: - When you insert the Abutton in the root frame, it captures the leftmost area of the frame, expands, and fills the Ydimension. Because the fill option is specified as fill=tk.Y, it claims all the area that it wants and fills the Y dimension of its container frame. - Because frame is itself packed with a plain pack()method with no mention of a pack option, it takes the minimum space required to accommodate all of its child widgets. - If you increase the size of the root window by pulling it down or sideways, you will see that all the buttons within the frame do not fill or expand with the root window. - The positioning of the B, C, and Dbuttons occurs on the basis of the side and fill options specified for each of them. - The next three buttons (after B, C, and D) demonstrate the use of the expand option. A value of expand=1means that the button moves its place on resizing the window. Buttons with no explicit expand options stay in their place and do not respond to changes in the size of their parent container (the root window, in this case). - The best way to study this piece of code would be to resize the root window to see the effect that it has on various buttons. - The anchorattribute (not used in the preceding code) provides a means to position a widget relative to a reference point. If the anchorattribute is not specified, the pack manager places the widget at the center of the available space or the packing box. The other options that are allowed include the four cardinal directions (N, S, E, and W) and a combination of any two directions. Therefore, valid values for the anchorattribute are CENTER(the default value), N, S, E, W, NW, NE, SW, and SE. Note The values for most Tkinter geometry manager attributes can either be specified in capital letters without quotes (such as side=tk.TOP and anchor=tk.SE) or in small letters within quotes (such as side='top'and anchor='se'). We will use the pack geometry manager in some of our projects. Therefore, it will be worthwhile to get acquainted with pack and its options. The pack manager is ideally suited for the following two kinds of situation: - Placing widgets in a top-down manner - Placing widgets side by side 1.05.py shows an example of both of these scenarios: parent = tk.Frame(root) # placing widgets top-down tk.Button(parent, text='ALL IS WELL').pack(fill=tk.X) tk.Button(parent, text='BACK TO BASICS').pack(fill=tk.X) tk.Button(parent, text='CATCH ME IF U CAN').pack(fill=tk.X) # placing widgets side by side tk.Button(parent, text='LEFT').pack(side=tk.LEFT) tk.Button(parent, text='CENTER').pack(side=tk.LEFT) tk.Button(parent, text='RIGHT').pack(side=tk.LEFT) parent.pack() The preceding code produces a GUI, as shown in the following screenshot: For a complete pack reference, type the following command in the Python shell: >> import tkinter >>> help(tkinter.Pack) Besides getting interactive help with documentation, Python's REPL is also a great tool for iterating and quick prototyping of Tkinter programs. Note Where should you use the pack() geometry manager? Using the pack manager is somewhat complicated as compared to the grid method, which will be discussed next, but it is a great choice in situations such as the following: - Having a widget fill the complete container frame - Placing several widgets on top of each other or side by side (as shown in the preceding screenshot) Although you can create complicated layouts by nesting widgets in multiple frames, you will find the grid geometry manager more suitable for most complex layouts. The grid geometry manager is easy to understand and perhaps the most useful geometry manager in Tkinter. The central idea of the grid geometry manager is to organize the container frame into a two-dimensional table that is divided into a number of rows and columns. Each cell in the table can then be targeted to hold a widget. In this context, a cell is an intersection of imaginary rows and columns. Note that in the grid method, each cell can hold only one widget. However, widgets can be made to span multiple cells. Within each cell, you can further align the position of the widget using the sticky option. The sticky option decides how the widget is expanded. If its container cell is larger than the size of the widget that it contains, the sticky option can be specified using one or more of the N, S, E, and W options or the NW, NE, SW, and SE options. Not specifying stickiness defaults stickiness to the center of the widget in the cell. Let's have a look at demo code that illustrates some features of the grid geometry manager. The code in 1.06.py generates a GUI, as shown in the following screenshot: The following code ( 1.06.py) generates the preceding GUI: import tkinter as tk root = tk.Tk() tk.Label(root, text="Username").grid(row=0, sticky=tk.W) tk.Label(root, text="Password").grid(row=1, sticky=tk.W) tk.Entry(root).grid(row=0, column=1, sticky=tk.E) tk.Entry(root).grid(row=1, column=1, sticky=tk.E) tk.Button(root, text="Login").grid(row=2, column=1, sticky=tk.E) root.mainloop() The following is a description of the preceding code: - Take a look at the grid position defined in terms of the row and column positions for an imaginary grid table spanning the entire frame. See how the use of sticky=tk.Won both the labels makes them stick on the left-hand side, thus resulting in a clean layout. - The width of each column (or the height of each row) is automatically decided by the height or width of the widgets in the cell. Therefore, you need not worry about specifying the row or column width as equal. You can specify the width for widgets if you need that extra bit of control. - You can use the sticky=tk.NSEWargument to make the widget expandable and fill the entire cell of the grid. In a more complex scenario, your widgets may span across multiple cells in the grid. To make a grid to span multiple cells, the grid method offers handy options such as rowspan and columnspan. Furthermore, you may often need to provide some padding between cells in the grid. The grid manager provides the padx and pady options to provide padding that needs to be placed around a widget. Similarly, the ipadx and ipady options are used for internal padding. These options add padding within the widget itself. The default value of external and internal padding is 0. Let's have a look at an example of the grid manager, where we use most of the common arguments to the grid method, such as row, column, padx, pady, rowspan, and columnspan. 1.07.py produces a GUI, as shown in the following screenshot, to demonstrate how to use the grid geometry manager options: The following code ( 1.07.py ) generates the preceding GUI: import tkinter as tk parent = tk.Tk() parent.title('Find & Replace') tk.Label(parent, text="Find:").grid(row=0, column=0, sticky='e') tk.Entry(parent, width=60).grid(row=0, column=1, padx=2, pady=2, sticky='we', columnspan=9) tk.Label(parent, text="Replace:").grid(row=1, column=0, sticky='e') tk.Entry(parent).grid(row=1, column=1, padx=2, pady=2, sticky='we', columnspan=9) tk.Button(parent, text="Find").grid( row=0, column=10, sticky='e' + 'w', padx=2, pady=2) tk.Button(parent, text="Find All").grid( row=1, column=10, sticky='e' + 'w', padx=2) tk.Button(parent, text="Replace").grid(row=2, column=10, sticky='e' + 'w', padx=2) tk.Button(parent, text="Replace All").grid( row=3, column=10, sticky='e' + 'w', padx=2) tk.Checkbutton(parent, text='Match whole word only').grid( row=2, column=1, columnspan=4, sticky='w') tk.Checkbutton(parent, text='Match Case').grid( row=3, column=1, columnspan=4, sticky='w') tk.Checkbutton(parent, text='Wrap around').grid( row=4, column=1, columnspan=4, sticky='w') tk.Label(parent, text="Direction:").grid(row=2, column=6, sticky='w') tk.Radiobutton(parent, text='Up', value=1).grid( row=3, column=6, columnspan=6, sticky='w') tk.Radiobutton(parent, text='Down', value=2).grid( row=3, column=7, columnspan=2, sticky='e') parent.mainloop() Note how just 14 lines of the core grid manager code generate a complex layout such as the one shown in the preceding screenshot. On the other hand, developing this with the pack manager would have been much more tedious. Another grid option that you can sometimes use is the widget.grid_forget() method. This method can be used to hide a widget from the screen. When you use this option, the widget still exists at its former location, but it becomes invisible. The hidden widget may be made visible again, but the grid options that you originally assigned to the widget will be lost. Similarly, there is a widget.grid_remove() method that removes the widget, except that in this case, when you make the widget visible again, all of its grid options will be restored. For a complete grid reference, type the following command in the Python shell: >>> import tkinter >>> help(tkinter.Grid) Note Where should you use the grid geometry manager? The grid manager is a great tool for the development of complex layouts. Complex structures can be easily achieved by breaking the container widget into grids of rows and columns and then placing the widgets in grids where they are wanted. It is also commonly used to develop different kinds of dialog box. Now we will delve into configuring a grid's column and row sizes. Different widgets have different heights and widths. So, when you specify the position of a widget in terms of rows and columns, the cell automatically expands to accommodate the widget. Normally, the height of all the grid rows is automatically adjusted so it's the height of its tallest cell. Similarly, the width of all the grid columns is adjusted so it's equal to the width of the widest widget cell. If you then want a smaller widget to fill a larger cell or to stay on any one side of the cell, you can use the sticky attribute on the widget to control this aspect. However, you can override this automatic sizing of columns and rows by using the following code: w.columnconfigure(n, option=value, ...) AND w.rowconfigure(n, option=value, ...) Use these to configure the options for a given widget, w, in either the nth column or the nth row, specifying values for the options, minsize, pad, and weight. Note that the numbering of rows begins from 0 and not 1. The options available are as follows: The columnconfigure() and rowconfigure() methods are often used to implement the dynamic resizing of widgets, especially on resizing the root window. The place geometry manager is the most rarely used geometry manager in Tkinter. Nevertheless, it has its uses in that it lets you precisely position widgets within their parent frame by using the (x,y) coordinate system. The place manager can be accessed by using the place() method on any standard widget. The important options for place geometry include the following: - Absolute positioning (specified in terms of x=N or y=N) - Relative positioning (the key options include relx, rely, relwidth, and relheight) The other options that are commonly used with place include width and anchor(the default is NW). Refer to 1.08.py for a demonstration of common place options: import tkinter as tk root = tk.Tk() # Absolute positioning tk.Button(root, text="Absolute Placement").place(x=20, y=10) # Relative positioning tk.Button(root, text="Relative").place(relx=0.8, rely=0.2, relwidth=0.5, width=10, anchor=tk.NE) root.mainloop() You may not see much of a difference between the absolute and relative positions simply by looking at the code or the window frame. However, if you try resizing the window, you will observe that the Absolute Placement button does not change its coordinates, while the Relative button changes its coordinates and size to accommodate the new size of the root window: For a complete place reference, type the following command in the Python shell: >>> import tkinter >>> help(tkinter.Place) Note When should you use the place manager? The place manager is useful in situations where you have to implement custom geometry managers, or where the widget placement is decided by the end user. While the pack and grid managers cannot be used together in the same frame, the place manager can be used with any geometry manager within the same container frame. The place manager is rarely used because, if you use it, you have to worry about the exact coordinates. If you make a minor change to a widget, it is very likely that you will have to change the x,y values for other widgets as well, which can be very cumbersome. We will use the place manager in Chapter 7, Piano Tutor. This concludes our discussion on geometry management in Tkinter. In this section, you had a look at how to implement the pack, grid, and place geometry managers. You also understood the strengths and weaknesses of each geometry manager. You learned that pack is suitable for a simple side-wise or top-down widget placement. You also learned that the grid manager is best suited for the handling of complex layouts. You saw examples of the place geometry manager and explored the reasons behind why it is rarely used. You should now be able to plan and execute different layouts for your programs using these Tkinter geometry managers. Now that you have learned how to add widgets to a screen and position them where you want, let's turn our attention to the third component of GUI programming. This addresses the question of how to make widgets functional. Making widgets functional involves making them responsive to events such as the pressing of buttons, the pressing of keys on a keyboard, and mouse clicks. This requires associating callbacks with specific events. Callbacks are normally associated with specific widget events using command binding rules, which are discussed in the following section. The simplest way to add functionality to a button is called command binding, whereby a callback function is mentioned in the form of command = some_callback in the widget option. Note that the command option is available only for a few selected widgets. Take a look at the following sample code: def my_callback (): # do something when button is clicked After defining the preceding callback, we can connect it to, say, a button with the command option referring to the callback, as follows: tk.Button(root, text="Click me", command=my_callback) A callback is a function memory reference ( my_callback in the preceding example) that is called by another function (which is Button in the preceding example) and that takes the first function as a parameter. Put simply, a callback is a function that you provide to another function so that it can calling it. Note that my_callback is passed without parentheses, (), from within the widget command option, because when the callback functions are set it is necessary to pass a reference to a function rather than actually call it. If you add parentheses, (), as you would for any normal function, it would be called as soon as the program runs. In contrast, the callback is called only when an event occurs (the pressing of a button in this case). If a callback does not take any argument, it can be handled with a simple function, such as the one shown in the preceding code. However, if a callback needs to take arguments, we can use the lambda function, as shown in the following code snippet: def my_callback (argument) #do something with argument Then, somewhere else in the code, we define a button with a command callback that takes some arguments, as follows: tk.Button(root,text="Click", command=lambda: my_callback ('some argument')) Python borrows a specific syntax from functional programming, called the lambda function.  The lambda function lets you define a single-line, nameless function on the fly. The format for using lambda is as follows: lambda arg: #do something with arg in a single line Here's an example: square = lambda x: x**2 Now, we can call the square method, as follows: >> print(square(5)) ## prints 25 to the console The command option that is available with the Button widget and a few other widgets is a function that can make the programming of a click-of-a-button event easy. Many other widgets do not provide an equivalent command binding option. By default, the command button binds to the left-click and the spacebar. It does not bind to the Return key. Therefore, if you bind a button by using the command function, it will react to the space bar and not the Return key. This is counter-intuitive for many users. What's worse is that you cannot change the binding of the command function easily. The moral is that command binding, though a very handy tool, is not flexible enough when it comes to deciding your own bindings. This brings us to the next method for handling events. Fortunately, Tkinter provides an alternative event binding mechanism called bind() to let you deal with different events. The standard syntax used to bind an event is as follows: widget.bind(event, handler, add=None) When an event corresponding to the event description occurs in the widget, it calls not only the associated handler, which passes an instance of the event object as the argument, but also the details of the event. If there already exists a binding for that event for this widget, the old callback is usually replaced with the new handler, but you can trigger both the callbacks by passing add='+' as the last argument. Let's look at an example of the bind() method (code 1.09.py): import tkinter as tk root = tk.Tk() tk.Label(root, text='Click at different\n locations in the frame below').pack() def callback(event): print(dir(event)) print("you clicked at", event.x, event.y) frame = tk.Frame(root, bg='khaki', width=130, height=80) frame.bind("<Button-1>", callback) frame.pack() root.mainloop() The following is a description of the preceding code: - We bind the Frame widget to the <Button-1>event, which corresponds to the left-click. When this event occurs, it calls the callbackfunction, passing an object instance as its argument. - We define the callback(event)function. Note that it takes the eventobject generated by the event as an argument. - We inspect the event object by using dir(event), which returns a sorted list of attribute names for the event object passed to it. This prints the following list: [ '__doc__' , '__module__' , 'char' , 'delta' , 'height' , 'keycode' , 'keysym' , keysym_num' , 'num' , 'send_event' , 'serial' , 'state' ,'time' , 'type' , 'widget' , 'width' , 'x' , 'x_root' , 'y' , 'y_root '] - From the attributes list generated by the object, we use two attributes, event.xand event.y, to print the coordinates of the point of click. When you run the preceding code (code 1.09.py ), it produces a window, as shown in the following screenshot: When you left-click anywhere in the yellow colored frame within the root window, it outputs messages to the console. A sample message passed to the console is as follows: ['__doc__', '__module__', 'char', 'delta', 'height', 'keycode', 'keysym', 'keysym_num', 'num', 'send_event', 'serial', 'state', 'time', 'type', 'widget', 'width', 'x', 'x_root', 'y', 'y_root'] You clicked at 63 36. In the previous example, you learned how to use the <Button-1> event to denote a left-click. This is a built-in pattern in Tkinter that maps it to a left-click event. Tkinter has an exhaustive mapping scheme that perfectly identifies events such as this one. Here are some examples to give you an idea of event patterns: In general, the mapping pattern takes the following form: <[event modifier-]...event type [-event detail]> Typically, an event pattern will comprise the following: - An event type: Some common event types include Button, ButtonRelease, KeyRelease, Keypress, FocusIn, FocusOut, Leave(when the mouse leaves the widget), and MouseWheel. For a complete list of event types, refer to the eventtypes section at. - An event modifier (optional): Some common event modifiers include Alt, Any(used like <Any-KeyPress>), Control, Double(used like <Double-Button-1>to denote a double-click of the left mouse button), Lock, and Shift. For a complete list of event modifiers, refer to the event modifiers section at. - The event detail (optional): The mouse event detail is captured by the number 1 for a left-click and the number 2 for a right-click. Similarly, each key press on the keyboard is either represented by the key letter itself (say, B in <KeyPress-B>) or by using a key symbol abbreviated as keysym. For example, the up arrow key on the keyboard is represented by the keysym value of KP_Up. For a complete keysymmapping, refer to. Let's take a look at a practical example of event binding on widgets (refer to code 1.10.py for the complete working example): The following is a modified snippet of code; it will give you an idea of commonly used event bindings: widget.bind("<Button-1>", callback) #bind widget to left mouse click widget.bind("<Button-2>", callback) # bind to right mouse click widget.bind("<Return>", callback)# bind to Return(Enter) Key widget.bind("<FocusIn>", callback) #bind to Focus in Event widget.bind("<KeyPress-A>", callback)# bind to keypress A widget.bind("<KeyPress-Caps_Lock>", callback)# bind to CapsLock keysym widget.bind("<KeyPress-F1>", callback)# bind widget to F1 keysym widget.bind("<KeyPress-KP_5>", callback)# bind to keypad number 5 widget.bind("<Motion>", callback) # bind to motion over widget widget.bind("<Any-KeyPress>", callback) # bind to any keypress Rather than binding an event to a particular widget, you can also bind it to the top-level window. The syntax remains the same except that now you call it on the root instance of the root window such as root.bind(). In the previous section, you had a look at how to bind an event to an instance of a widget. This can be called an instance-level binding. However, there may be times when you need to bind events to an entire application. At times, you may want to bind an event to a particular class of widget. Tkinter provides the following levels of binding options for this: widget.bind_all(event, callback, add=None) The typical usage pattern is as follows: root.bind_all('<F1>', show_help) Application-level binding here means that, irrespective of the widget that is currently under focus, pressing the F1 key will always trigger the show_help callback as long as the application is in focus. w.bind_class(class_name, event, callback, add=None) The typical usage pattern is as follows: my_entry.bind_class('Entry', '<Control-V>', paste) In the preceding example, all the entry widgets will be bound to the <Control-V> event, which will call a method named paste (event). Note Event propagation Most keyboard and mouse events occur at the operating system level. The event propagates hierarchically upward from its source until it finds a window that has the corresponding binding. The event propagation does not stop there. It propagates itself upwards, looking for other bindings from other widgets, until it reaches the root window. If it does reach the root window and no bindings are discovered by it, the event is disregarded. You need variables with a wide variety of widgets. You likely need a string variable to track what the user enters into the entry widget or text widget. You most probably need Boolean variables to track whether the user has checked off the Checkbox widget. You need integer variables to track the value entered in a Spinbox or Slider widget. In order to respond to changes in widget-specific variables, Tkinter offers its own variable class. The variable that you can use to track widget-specific values must be subclassed from this Tkinter variable class. Tkinter offers some commonly used predefined variables. They are StringVar, IntVar, BooleanVar, and DoubleVar. You can use these variables to capture and play with the changes in the values of variables from within your callback functions. You can also define your own variable type, if required. Creating a Tkinter variable is simple. You simply have to call the constructor: my_string = tk.StringVar() ticked_yes = tk.BooleanVar() group_choice = tk.IntVar() volume = tk.DoubleVar() Once the variable is created, you can use it as a widget option, as follows: tk.Entry(root, textvariable=my_string) tk.Checkbutton(root, text="Remember Me", variable=ticked_yes) tk.Radiobutton(root, text="Option1", variable=group_choice, value="option1") tk.Scale(root, label="Volume Control", variable=volume, from =0, to=10) Additionally, Tkinter provides access to the values of variables via the set() and get() methods, as follows: my_var.set("FooBar") # setting value of variable my_var.get() # Assessing the value of variable from say a callback A demonstration of the Tkinter variable class is available in the 1.11.py code file. The code generates a window, as shown in the following screenshot: This concludes our brief discussion on events and callbacks. Here's a brief summary of the things that we discussed: - Command binding, which is used to bind simple widgets to certain functions - Event binding using the widget.bind_all( event, callback, add=None) method to bind keyboard and mouse events to your widgets and invoke callbacks when certain events occur - The passing of extra arguments to a callback using the lambdafunction - The binding of events to an entire application or to a particular class of widget by using bind_all()and bind_class() - Using the Tkinter variableclass to set and get the values of widget-specific variables In short, you now know how to make your GUI program responsive to end-user requests! In addition to the bind method that you previously saw, you might find the following two event-related options useful in certain cases: - Unbind: Tkinter provides the unbind option to undo the effect of an earlier binding. The syntax is as follows: widget.unbind(event) The following are some examples of its usage: entry.unbind('<Alt-Shift-5>') root.unbind_all('<F1>') root.unbind_class('Entry', '<KeyPress-Del>') - Virtual events: Tkinter also lets you create your own events. You can give these virtual events any name that you want. For example, let's suppose that you want to create a new event called <<commit>>, which is triggered by the F9 key. To create this virtual event on a given widget, use the following syntax: widget.event_add('<<commit>>', '<KeyRelease-F9>') You can then bind <<commit>> to a callback by using a normal bind() method, as follows: widget.bind('<<commit>>', callback) Other event-related methods can be accessed by typing the following line in the Python Terminal: >>> import tkinter >>> help(tkinter.Event) Now that you are ready to delve into real application development with Tkinter, let's spend some time exploring a few custom styling options that Tkinter offers. We will also have a look at some configuration options that are commonly used with the root window. So far, we have relied on Tkinter to provide specific platform-based styling for our widgets. However, you can specify your own styling of widgets, such as their color, font size, border width, and relief. A brief introduction to styling features that are available in Tkinter is supplied in the following section. You may recall that we can specify widget options at the time of its instantiation, as follows: my_button = tk.Button(parent, **configuration options) Alternatively, you can specify the widget options by using configure() in the following way: my_button.configure(**options) Styling options are also specified as options to the widgets either at the time of creating the widgets, or later by using the configure option. Under the purview of styling, we will cover how to apply different colors, fonts, border widths, reliefs, cursors, and bitmap icons to widgets. First, let's see how to specify the color options for a widget. You can specify the following two types of color for most widgets: - The background color - The foreground color You can specify the color by using hexadecimal color codes for the proportion of red(r), green(g), and blue(b). The commonly used representations are #rgb (4 bits), #rrggbb (8 bits), and #rrrgggbbb (12 bits). For example, #fff is white, #000000 is black, #f00 is red (R= 0xf, G= 0x0 , B= 0x0 ), #00ff00 is green (R= 0x00, G= 0xff, B= 0x00), and #000000fff is blue (R= 0x000 , G= 0x000 , B= 0xfff ). Alternatively, Tkinter provides mapping for standard color names. For a list of predefined named colors, visit or. Next, let's have a look at how to specify fonts for our widgets. A font can be represented as a string by using the following string signature: {font family} fontsize fontstyle The elements of the preceding syntax can be explained as follows: font family: This is the complete font family long name. It should preferably be in lowercase, such as font="{nimbus roman} 36 bold italic". fontsize: This is in the printer's point unit ( pt) or pixel unit ( px). fontstyle: This is a mix of normal/bold/italic and underline/overstrike. The following are examples that illustrate the method of specifying fonts: widget.configure (font='Times 8') widget.configure(font='Helvetica 24 bold italic') If you set a Tkinter dimension in a plain integer, the measurements take place in pixel units. Alternatively, Tkinter accepts four other measurement units, which are m(millimeters), c(centimeters), i(inches), and p(printer's points, which are about 1/72"). For instance, if you want to specify the wrap length of a button in terms of a printer's point, you can specify it as follows: button.configure(wraplength="36p") The default border width for most Tkinter widgets is 2 px. You can change the border width for widgets by specifying it explicitly, as shown in the following line: button.configure(borderwidth=5) The relief style of a widget refers to the difference between the highest and lowest elevations in a widget. Tkinter offers six possible relief stylesâ flat, raised, sunken, groove, solid, and ridge: button.configure(relief='raised') Tkinter lets you change the style of the mouse cursor when you hover over a particular widget. This is done by using the option cursor, as follows: button.configure(cursor='cross') For a complete list of available cursors, refer to. Though you can specify the styling options at each widget level, sometimes it may be cumbersome to do so individually for each widget. Widget-specific styling has the following disadvantages: - It mixes logic and presentation into one file, making the code bulky and difficult to manage - Any change in styling has to be applied to each widget individually - It violates the don't repeat yourself (DRY) principle of effective coding, as you keep specifying the same style for a large number of widgets Fortunately, Tkinter now offers a way to separate presentation from logic and specify styles in what is called the external option database. This is just a text file where you can specify common styling options. A typical option database text file looks like this: *background: AntiqueWhite1 *Text*background: #454545 *Button*foreground: gray55 *Button*relief: raised *Button*width: 3 In its simplest use, the asterisk ( *) symbol here means that the particular style is applied to all the instances of the given widget. For a more complex usage of the asterisk in styling, refer to. These entries are placed in an external text ( .txt) file. To apply this styling to a particular piece of code, you can simply call it by using the option_readfile() call early in your code, as shown here: root.option_readfile('optionDB.txt') Let's have a look at an example (see code 1.12.py ) of using this external styling text file in a program: import tkinter as tk root = tk.Tk() root.configure(').grid(row=2, column=3) tk.Button(root, text='+').grid(row=3, column=1) tk.Button(root, text='v').grid(row=3, column=2) tk.Button(root, text='-').grid(row=3, column=3) for i in range(9): tk.Button(root, text=str(i+1)).grid(row=4+i//3, column=1+i%3) root.mainloop() The following is a description of the preceding code: - The code connects to an external styling file called optionDB.txtthat defines common styling for the widgets. - The next segment of code creates a Text widget and specifies styling on the widget level. - The next segment of code has several buttons, all of which derive their styling from the centralized optionDB.txtfile. One of the buttons also defines a custom cursor. Specifying attributes such as font sizes, the border width, the widget width, the widget height, and padding in absolute numbers, as we have done in the preceding example, can cause some display variations between different operating systems such as Ubuntu, Windows, and Mac respectively, as shown in the following screenshot. This is due to differences in the rendering engines of different operating systems: Now that we are done discussing styling options, let's wrap up with a discussion on some commonly used options for the root window: Let's explain these styling options in more detail: root.geometry('142x280+150+200'): Specifying the geometry of the root window limits the launch size of the root window. If the widgets do not fit in the specified size, they get clipped from the window. It is often better not to specify this and let Tkinter decide this for you. self.root.wm_iconbitmap('my_icon.ico')or self.root.iconbitmap('my_icon.ico '): This option is only applicable to Windows. Unix-based operating systems do not display the title bar icon. This section applies not only for Tkinter, but also for any Python object for which you may need help. Let's say that you need a reference to the Tkinter pack geometry manager. You can get interactive help in your Python interactive shell by using the help command, as shown in the following command lines: >>> import tkinter >>> help(tkinter.Pack) This provides detailed help documentation of all the methods defined under the Pack class in Tkinter. You can similarly receive help for all the other individual widgets. For instance, you can check the comprehensive and authoritative help documentation for the Label widget in the interactive shell by typing the following command: >>>help(tkinter.Label) This provides a list of the following: - All the methods defined in the Labelclass - All the standard and widget-specific options for the Labelwidget - All the methods inherited from other classes Finally, when in doubt regarding a method, look into the source code of Tkinter, which is located at <location-of-python-installation>\lib\. For instance, the Tkinter source code is located in the /usr/lib/python3.6.3/tkinter directory on my Linux Mint operating system. You might also find it useful to look at the source code implementation of various other modules, such as the color chooser, file dialogs, and ttk modules, and the other modules located in the aforementioned directory. This brings us to end of this chapter. This chapter aimed to provide a high-level overview of Tkinter. We worked our way through all the important concepts that drive a Tkinter program. You now know what a root window is and how to set it up. You also know the 21 core Tkinter widgets and how to set them up. We also had a look at how to lay out our programs by using the Pack, Grid, and Place geometry managers, and how to make our programs functional by using events and callbacks. Finally, you saw how to apply custom styles to GUI programs. To summarize, we can now start thinking about making interesting, functional, and stylish GUI programs with Tkinter! In the next chapter, we will build our first real application - a Text editor. Before you proceed to the next chapter, make sure you can answer these questions to your satisfaction: - What is a root window? - What is the main loop? - How do you create a root window? - What are widgets? How do you create widgets in Tkinter? - Can you list or identify all available widgets in Tkinter? - What are geometry managers used for? - Can you name all the available geometry managers in Tkinter? - What are events in a GUI program? - What are callbacks? How are callbacks different from regular functions? - How do you apply callbacks to an event? - How do you style widgets using styling options? - What are the common configuration options for the root window? It would be a good idea to modify the examples from this chapter to lay out the widgets in different ways or to tweak the code to function in other ways to get your feet wet. We recommend that you take a look at the documentation for all three geometry managers in your Python shell using the following commands: >>> import tkinter >>> help(tkinter.Pack) >>> help(tkinter.Grid) >>> help(tkinter.Place) You can also find an excellent documentation of Tkinter atÂ. Â
https://www.packtpub.com/product/tkinter-gui-application-development-blueprints-second-edition/9781788837460
CC-MAIN-2020-40
refinedweb
9,888
55.13
This program consists of calculating the bills for the We Spray Anything Company. They use planes to spray crops for a variety of problems. The rates they charge the farmer depend on what is being sprayed and how many acres one wants sprayed. There are discounts if the amount to be sprayed is sufficiently large or if the bill exceeds a certain amount. If the area to be sprayed is greater than 1000 acres, the farmer receives a 5% discount of his total bill. In addition, any farmer whose bill is over $1500, after the 5% discount for over 1000 acres, receives a further 10% discount on the amount over $1500. This 10% discount is taken even if the farmer does not have 1000 acres. We will be reading the data in from a file. Each line in the file will be a triple of numbers: (1) the ID number of the client, (2) a code for what is being sprayed, and (3) the number of acres being sprayed. The main module will read in the data from a file. After reading in each triple, we will calculate the bill. Since the calculation of the bill is something which logically stands by itself, we will create a separate module calculateBill which will calculate the bill and return the amount. The line of code that does this is: amountDue = calculateBill(type,acres); To check the program to see if it is working, the following inputs (hopefully correctly) calculate the amount due: Input Amount Due 1000 1 1200 $1140.00 1001 2 800 $2310.00 1002 3 300 $1200.00 1003 4 1100 $5793.00 1004 3 783 $2968.80 1005 1 1550 $1472.50 A print out on one line the client ID, type, number of acres, and the amount due. An example of what the output will look like is: Client Number Type Acres Amount Due 1000 1 1200 $1140.00 1001 2 800 $2310.00 Note If there is bad input data, for example, the type does not have the values of 1-4 inclusive, calculateBill will return a negative value. In this case you should print out a "bad input data" for the amount: 1003 5 600 bad input data After we have read in all of the relevant data, we will output the total amount billed for all of the clients in a separate line. You will have a while loop to control the reading of data from the file. You will continue to read in data until the clientNumber value of 0 is read in. After exiting the while loop, you will ouput a single line telling how much was due for all of the clients for this input file. Note: Be sure to close your file before exciting the program. I have attached the txt file we are supposed to load for this. I really need some input, as I have been looking at this so long my head is beginning to spin. Thanks! package Program4; import java.io.*; import java.util.*; public class MainModule { public static void main(String[] args)throws IOException { int clientNumber, //Client ID number type, //Type of billing //Type 1: Spraying for weeds, $1 an acre //Type 2: Spraying for grasshoppers, $3 an acre //Type 3: Spraying for army worms, $4 an acre //Type 4: Spraying for all of these, $6 an acre acres; //Number of acres to be sprayed double amountDue; //The amount due for the client Scanner scan = new Scanner(new FileReader ("spraying.txt")); clientNumber = scan.nextInt(); type = scan.nextInt(); acres = scan.nextInt(); amountDue = calculateBill(type,acres); int sum, counter; final int SENTINEL = 0; counter = 0; sum = 0; while (clientNumber != SENTINEL) System.out.println(); } public static double calculateBill(int type, int acres) { double grossCharge; switch (type) { case '1': grossCharge = (1 * acres); break; case '2': grossCharge = (3 * acres); break; case '3': grossCharge = (4 * acres); break; case '4': grossCharge = (6 * acres); if (acres > 1000) grossCharge *= 0.95; else if (acres < 0) throw new IllegalArgumentException("acres cannot be negative"); if (grossCharge > 1500) grossCharge = 0.90*(grossCharge - 1500) + 1500; } return calculateBill (type, acres); }} Attached File(s) spraying.txt (177bytes) Number of downloads: 85
http://www.dreamincode.net/forums/topic/102550-billing-problem-with-file-retrieval-multiple-methods-switch-and-whil/page__p__624953
CC-MAIN-2016-22
refinedweb
690
79.7
Introduction Authors sometimes want user agents to render content that does not come from the document tree. One familiar example of this is numbered headings; the author does not want to mark the numbers up explicitly, they want the user agent to generate them automatically. Counters and markers are used to achieve these effects. Similarly, authors may want the user agent to insert the word "Figure" before the caption of a figure, or "Chapter 7" on a line before the seventh chapter title. chapter { counter-increment :chapter ; } chapter > title::before { content : "Chapter " counter (chapter ) "\A" ; } Another common effect is replacing elements with images or other multimedia content. Since not all user agents support all multimedia formats, fallbacks may have to be provided. /* Replace <logo> elements with the site’s logo, using a format * supported by the UA */ logo { content : url ( logo.mov ), url ( logo.mng ), url ( logo.png ),none ; } /* Replace <figure> elements with the referenced document, or, * failing that, with either the contents of the alt attribute or the * contents of the element itself if there is no alt attribute */ figure[alt] { content : attr (href url ), attr (alt ); } figure:not([alt]) { content : attr (href url ),contents ; } 1. Inserting and replacing content with the content property User Agents are expected to support this property on all media, including non-visual ones. The content property dictates what is rendered inside an element or pseudo-element. For elements, it has only one purpose: specifying that the element renders as normal, or replacing the element with an image (and possibly some associated "alt text"). For pseudo-elements and margin boxes, it is more powerful. It controls whether the element renders at all, can replace the element with an image, or replace it with arbitrary inline content (text and images). - normal - For an element or page margin box, this computes to contents. For ::before and ::after, this computes to none. For ::marker, this computes to itself (normal). - none - On elements, this inhibits the children of the element from being rendered as children of this element, as if the element was empty. On pseudo-elements it inhibits the creation of the pseudo-element as if it had display: none. In neither case does it prevent any pseudo-elements which have this element or pseudo-element as an originating element from being generated. - <content-replacement> - Equal to: <image> Makes the element or pseudo-element a replaced element, filled with the specified <image>. Its normal contents are suppressed and do not generate boxes, as if they were display: none. If the <image> represents an invalid image, then it must be treated as instead representing an image with zero intrinsic width and height, filled with transparent black. The above invalid image behavior appears to be what Chrome is doing. Is this okay? Is there a better behavior we can/should use? "Zero intrinsic width and height" gives it an undefined aspect ratio, and sizing behavior is thus... undefined. At least, if you give it an explicit width or height, the other dimension remains at zero in Chrome. This might need to be explicitly defined over in the Images spec; needs some investigation around whether browsers act this way for 0x0 SVGs and rasters. Note: Replaced elements use different layout rules than normal elements. (In effect, it becomes equivalent to an HTML imgelement.) Note: Replaced elements do not have ::before or ::after pseudo-elements; the content property replaces their entire contents. - <content-list> - Equal to: [ <string> | contents | <image> | <counter> | <quote> | <target> | <leader()> ]+ Replaces the element’s contents with one or more anonymous inline boxes corresponding to the specified values, in the order specified. Its normal contents are suppressed and do not generate boxes, as if they were display: none. Each value contributes an inline box to the element’s contents. For <image>, this is an inline anonymous replaced element; for the others, it’s an anonymous inline run of text. If an <image> represents an invalid image, the user agent must do one of the following: "Skip" the <image>, generating nothing for it. Display some indication that the image can’t be displayed in place of the <image>, such as a "broken image" icon. This specification intentionally does not define which behavior a user agent must use, but it must use one or the other consistently. Note: If the value of <content-list> is a single <image>, it must instead be interpreted as a <content-replacement>. - / [ <string> | <counter> ]+ - Specifies the "alt text" for the element. See § 1.2 Alternative Text for Accessibility for details. If omitted, the element has no "alt text". Should the contents keyword be replaced with content()? 1.1. Accessibility of Generated Content Generated content should be searchable, selectable, and available to assistive technologies. The content property applies to speech and generated content must be rendered for speech output. [CSS3-SPEECH] Start work on an AAM for CSS. 1.2. Alternative Text for Accessibility Content intended for visual media sometimes needs alternative text for speech output or other non-visual mediums. The content property thus accepts alternative text to be specified after a slash (/) after the last <content-list>. If such alternative text is provided, it must be used for speech output instead. This allows, for example, purely decorative text to be elided in speech output (by providing the empty string as alternative text), and allows authors to provide more readable alternatives to images, icons, or text-encoded symbols. .new::before { content : url ( ./img/star.png ) / "New!" ; /* or a localized attribute from the DOM: attr("data-alt") */ } .expandable::before { content : "\25BA" / "" ; /* a.k.a. ► */ /* aria-expanded="false" already in DOM, so this pseudo-element is decorative */ } 2. <content-list> Values and Functions The <content-list> value is used in content to fill an element with one or more anonymous inline boxes, including images, strings, the values of counters, and the text value of elements. In this section we enumerate the possibilities. 2.1. String - <string> - Represents an anonymous inline box filled with the specified text. Note: White space in the string is handled the same as in literal text, and controlled by the properties in [CSS-TEXT-3] and elsewhere. In particular, white space character can collapse, even across multiple strings, such as in content: "First " " Second";, which by default will render similar to "First Second"(with a single visible space between the two words). 2.2. <image> - <image> - Represents an anonymous inline replaced element filled with the specified <image>. If the <image> represents an invalid image, this value instead represents nothing. (No inline content is added to the element, as if this value were "skipped".) CSS2.1 explicitly allowed the UA to substitute a broken image icon if the image was invalid. However, no browser appears to do this. Is this removal okay? 2.3. Element Content - contents - The element’s descendents. Since this can only be used once per element (you can’t duplicate the children if, e.g., one is a plugin or form control), it is handled as follows: - If set on the element: Always honoured. Note that this is the default, since the initial value of content is normal and normal computes to contents on an element. - If set on one of the element’s other pseudo-elements: Check to see that it is not set on a "previous" pseudo-element, in the following order, depth first: the element itself ::before ::after Should this behave as an empty string on pseudo-elements? If it is already used, then it evaluates to nothing (like none). Only pseudo-elements that are actually generated are checked. foo { content :normal ; } /* this is the initial value */ foo::after { content :contents ; } ...the element’s content property would compute to contents and the after pseudo element would have no contents (equivalent to none) and thus would not appear. foo { content :none ; } foo::after { content :contents ; } But in this example, the ::after pseudo-element will contain the contents of the foo element. Use cases for suppressing the content on the element and using it in a pseudo-element would be welcome. Note: While it is useless to include contents twice in a single content property, that is not a parse error. The second occurrence simply has no effect, as it has already been used. It is also not a parse error to use it on a ::marker pseudo-element, it is only during the rendering stage that it gets treated like none. Do we need the statement about marker pseudo-elements here? Or is this legacy from the old version of the spec? 2.4. Quotes HTML has long had the q element, used to delimit quotations. The quotes property, in conjunction with the various *-quote values of the content property, can be used to properly style such quotations. 2.4.1. Specifying quotes with the quotes property User Agents are expected to support this property on all media, including non-visual ones. This property specifies quotation marks for any number of embedded quotations. Values have the following meanings: - none - The open-quote and close-quote values of the content property produce no quotations marks, as if they were no-open-quote and no-close-quote respectively. - auto - A typographically appropriate used value for quotes is automatically chosen by the UA based on the content language of the element and/or its parent. Note: The Unicode Common Locale Data Repository [CLDR] maintains information on typographically apropriate quotation marks. UAs can use other sources of information as well, particularly as typographic preferences can vary; however it is encouraged to submit any improvements to Unicode so that the entire software ecosystem can benefit. - [ . 2.4.2. The *-quote values of the content property <quote> = open-quote | close-quote | no-open-quote | no-close-quote - open-quote - close-quote - These values are replaced by the appropriate string from the quotes property, and increments (decrements) the level of nesting for quotes. See § 2.4.1 Specifying quotes with the quotes property for more information. - no-open-quote - no-close-quote - Inserts nothing (as in none), but increments (decrements) the level of nesting for quotes. See § 2.4.1 Specifying quotes with the quotes property for more information.. Note: Quote nesting, like counter inheritance, operates on the “flattened element tree” in the context of the [DOM].. blockquote, and inserts a single closing quote at the end: blockquote p:before { content :open-quote } blockquote p:after { content :no-close-quote } blockquote p:last-child::after { content :close-quote } : "\00AB\2005" "\2005\00BB" "\2039\2005" "\2005\203A" } :lang(en) > * { quotes : "\201C" "\201D" "\2018" "\2019" } The quotation marks are shown here in a form that most people will be able to type. If you can type them directly, they will look like this: :lang(fr) > * { quotes : "« " " »" "‹ " " ›" } :lang(en) > * { quotes : "“" "”" "‘" "’" } /* Specify pairs of quotes for two levels in two languages */ :lang(en) > q { quotes : '"' '"' "'" "'" } :lang(no) > q { quotes : "«" "»" "’" "’" } /* Insert quotes before and after Q element content */ q::before { content :open-quote } q::after { content :close-quote } to the following HTML fragment: <html lang="en"> <head> <title>Quotes</title> </head> <body> <p><q>Quote me!</q></p> </body> </html> would allow a user agent to produce: "Quote me!" while this HTML fragment: <html lang="no"> <head> <title>Quotes</title> </head> <body> <p><q>Trøndere gråter når <q>Vinsjan på kaia</q> blir deklamert.</q></p> </body> </html> would produce: «Trøndere gråter når ’Vinsjan på kaia’ blir deklamert.» 2.5. Leaders A leader, sometimes known as a tab leader or a dot leader, is a repeating pattern used to visually connect content across horizontal spaces. They are most commonly used in tables of contents, between titles and page numbers. The leader() function, as a value for the content property, is used to create leaders in CSS. This function takes a string (the leader string), which describes the repeating pattern for the leader. 2.5.1. The leader() function - leader( <leader-type> ) - Inserts a leader. See the section on leaders for more information. leader() = leader( <leader-type> ) <leader-type> = dotted | solid | space | <string> Three keywords are shorthand values for common strings: - dotted - Equivalent to leader(".") - solid - Equivalent to leader("_") - space - Equivalent to leader(" ") - <string> - Issue: Define this. ol.toc a::after { content : leader ( '.' ) target-counter ( attr (href ))? 2.5.2. Rendering leaders Consider a line which contains the content before the leader (the “before content”), the leader, and the content after the leader (the “after content”). Leaders obey the following rules: The leader string must appear in full at least once. The leader should be as long as possible Visible characters in leaders should vertically align with each other when possible. Line break characters in the leader string must be ignored. White space in the leader string follows normal CSS rules. A leader only appears between the start content and the end content. A leader only appears on a single line, even if the before content and after content are on different lines. A leader can’t be the only thing on a line. 2.5.3. Procedure for rendering leaders Lay out the before content, until reaching the line where the before content ends. BBBBBBBBBB BBB The leader string consists of one or more glyphs, and is thus an inline box. A leader is a row of these boxes, drawn from the end edge to the start edge, where only those boxes not overlaid by the before or after content. On this line, draw the leader string, starting from the end edge, repeating as many times as possible until reaching the start edge. BBBBBBBBBB .......... Draw the before and after content on top of the leader. If any part of the before content or after content overlaps a glyph in a leader string box, that glyph is not displayed. BBBBBBBBBB BBB....AAA If one full copy of the leader string is not visible: BBBBBBB BBBBBBA Insert a line break after the before content, draw the leader on the next line, and draw the after content on top, and hide any leader strings that are not fully displayed. BBBBBBB BBBBBB ......A what to do if after content is wider than the line box? Leaders don’t quite work in table layouts. How can we fix this? 2.6. Cross references and the target-* functions Many documents contain internal references: Three new values for the content property are used to automatically create these types of cross-references: target-counter(), target-counters(), and target-text(). Each of these displays information obtained from the target end of a link. <target> = <target-counter()> | <target-counters()> | <target-text()> See sections below for details on each of these. 2.6.1. The target-counter() function target-counter() = target-counter( [ <string> | <url> ] , <custom-ident> , <counter-style>? ) The target-counter() function retrieves the value of the innermost counter with a given name. The required arguments are the url of the target and the name of the counter. An optional counter-style argument can be used to format the result. These functions only take a fragment URL which points to a location in the current document. If there’s no fragment, if the ID referenced isn’t there, or if the URL points to an outside document, the user agent must treat that as an error. what should error handling be? restrict syntactically to local references for now. …which will be discussed on page <a href="#chapter4_sec2">< 2.6.2. The target-counters() function This functions fetches the value of all counters of a given name from the end of a link, and formats them by inserting a given string between the value of each nested counter. target-counters() = target-counters( [ <string> | <url> ] , <custom-ident> , <string> , <counter-style>? ) I have not found a compelling example for target-counters() yet. found a compelling example, in CSS specs. Do something. 2.6.3. The target-text() function The target-text() function retrieves the text value of the element referred to by the URL. An optional second argument specifies what content is retrieved, using the same values as the string-set property above. target-text() = target-text( [ <string> | . 2.7. Named strings This section introduces named strings, which are the textual equivalent of counters and which have a distinct namespace from counters. Named strings follow the same nesting rules as counters. The string-set property accepts values similar to the content property, including the extraction of the current value of counters. Named strings are a convenient way to pull metadata out of the document for insertion into headers and footers. In HTML, for example, META elements contained in the document HEAD can set the value of named strings. In conjunction with attribute selectors, this can be a powerful mechanism: meta[author] { string-set :author attr (author ); } head > title { string-set :title contents ; } @page :left { @top { text-align :left ; vertical-align :middle ; content : string (title ); } } @page :right { @top { text-align :right ; vertical-align :middle ; content : string (author ); } } 2.7.1. The string-set property User Agents are expected to support this property on all media, including non-visual ones.. - none - The element does not set any named strings. [ <custom-ident> <string>+ ]# - The element establishes one or more named strings, corresponding to each comma-separated entry in the list. For each entry, the <custom-ident> gives the name of the named string. It’s followed by one or more <string> values, which are concatenated together to form the value of the named string. If an element has style containment, the string-set property must have no effects on descendants of that element. H1 { string-set :chapter contents ; } When an H1 element is encountered, the chapter string is set to the element’s textual contents, and the previous value of chapter, if any, is overwritten. 2.7.2. The string() function string() = string( <custom-ident> , [ first | start | last | first-except ]? ) The string() function is used to copy the value of a named string to the document, via the content property. This function requires one argument, the name of the named string. Since the value of a named string may change several times on a page (as multiple elements defining the string can appear) an optional second argument indicates which value of the named string should be used. The second argument of the string() function is one of the following keywords: - first - The value of the first assignment on the page is used. If there is no assignment on the page, the entry value is used. If no second argument is provided, this is the default value. - start - If the element is the first element on the page, the value of the first assignment is used. Otherwise the entry value is used. The entry value may be empty if the named string hasn’t yet appeared. - The exit value of the named string is used. - first-except - This is identical to first, except that the empty string is used on the page where the value is assigned. we may need to kill the entire content string. Is this necessary?. @page { size : 15 cm 10 cm ; margin : 1.5 cm ; @top-left { content : "first: " string (heading ,first ); } @top-center { content : "start: " string (heading ,start ); } @top-right { content : "last: " string (heading ,last ); } } h2 { string-set :heading content () } The following figures show the first, start, and last assignments of the “heading” string on various pages. 2.7.3. The content() function content() = content( [ text | before | after | first-letter | marker ]? ) - text - The string value of the element. If no value is specified in content(), it acts as if text were specified. - before - The string value of the ::before pseudo-element. - after - The string value of the ::after pseudo-element. - first-letter - The first letter of the element, as defined for the ::first-letter pseudo-element - marker - The string value of the ::marker pseudo-element. ”. 3. Automatic counters and numbering: the counter-increment and counter-reset properties (moved) Now described in [CSS3LIST] Should this move back to CSS Content? 4. Bookmarks Some document formats, most notably PDF, allow the use of bookmarks as an aid to navigation. Bookmarks provide a list of links to document elements, as well as text to label the links and a level value. A bookmark has three properties: bookmark-level, bookmark-label, and bookmark-state. When a user activates a bookmark, the user agent must bring that reference point to the user’s attention, exactly as if navigating to that element by fragment URL. This will also trigger matching the :target pseudo-class. If an element has style containment, the bookmark-level, bookmark-label, and bookmark-state properties must have no effect on descendants of the element. 4.1. bookmark-level The bookmark-level property determines if a bookmark is created, and at what level. If this property is absent, or has value none, no bookmark should be generated, regardless of the values of bookmark-label or bookmark-state. - <integer> - defines the level of the bookmark, with the top level being 1 (negative and zero values are invalid). - none - no bookmark is generated. section h1 { bookmark-level : 1 ; } section section h1 { bookmark-level : 2 ; } section section section h1 { bookmark-level : 3 ; } Note: Bookmarks do not need to create a strict hierarchy of levels. Should a bookmark be created for elements with display: none? 4.2. bookmark-label - <content-list> - <content-list> is defined above, in the section on the string-set property. The value of <content-list> becomes the text content of the bookmark label. <h1>Loomings</h1> CSS: h1 { bookmark-label : content (text ); bookmark-level : 1 ; } The bookmark label will be “Loomings”. 4.3. bookmark-state The bookmark-state may be open or closed. The user must be able to toggle the bookmark state. - open - Subsequent bookmarks with bookmark-level greater than the given bookmark are displayed, until reaching another bookmark of the same level or lower. If one of subsequent bookmark is closed, apply the same test to determine if its subsequent bookmarks should be displayed. - closed - Subsequent bookmarks of bookmark-level greater than the given bookmark are not displayed, until reaching another bookmark of the same level or lower. Is the initial bookmark state, or the bookmark state updated by the UA as appropriate? 5. Changes since the 2 June 2016 Working Draft Significant changes since the 2 June 2016 Working Draft consist primarily of: - Adding auto as the initial value of quotes. - Lots of miscellaneous spec clean up: errors, cross-references, overly-loose or sloppy definitions, etc. See also previous changes. Acknowledgements Stuart Ballard, David Baron, Bert Bos, Tantek Çelik, and James Craig provided invaluable suggestions used in this specification.
http://www.w3.org/TR/css-content-3/
CC-MAIN-2021-39
refinedweb
3,756
54.52
Telegraf has reached the ripe old age of V1.21.2. Thanks to community feedback and contribution, there have been many features added over the years. Lately, I have seen these questions pop up: - How can I monitor the performance of my Telegraf instance? - What configuration parameters can I change to reduce memory consumption? - How can I maintain a configuration file with hundreds of plugins? - How can I improve the readability of debugging and test new configs? If any of these questions plague your mind, have no fear — this blog is here to help! Here are my golden rules for maintaining best practices when building your Telegraf solution. Maintaining a large and complex config file In many use cases, Telegraf is being deployed to ingest data from multiple input sources and deliver that data to either InfluxDB or other enterprise platforms (as shown in the below example). So how do we maintain and future-proof the Telegraf config? Divide and conquer My first golden rule is to split your configuration into manageable chunks. How is this possible? Telegraf provides the ability to add configuration files to the telegraf.d directory. This is usually located: - Linux: /etc/telegraf/telegraf.d/ - Windows: C:\Program Files\Telegraf\telegraf.d (You set this as part of the service install) - Mac: /usr/local/etc/telegraf.d Note: you can also define your own directory locations for storing Telegraf configs using the –config-directory flag. All files ending in .conf are considered a Telegraf config. Doing this allows you to keep parts of your large configuration in multiple smaller ones. For example: - Create three config files called: inputs, processors and outputs. Add your plugins to match the corresponding config. - Create a config file per usage scenario. This is my personal preference when using Telegraf. This is how I would divide up the above diagram into configuration files: Pros: - This structure can be scaled to hundreds of plugins while maintaining the readability and maintainability of scenarios running under one Telegraf instance. Cons: - The administrator must remember that Telegraf does not distinguish between config files (they are run as one). Routing must still be considered in each configuration file (We will discuss this later in the blog post). Naming plugins Let’s start with the easy one which will save you hours debugging in the future: naming your plugins. My second golden rule is to provide a descriptive alias to each one of your plugins. An example would look like this: [[inputs.file]] alias = "file-2" files = ["/data/sample.json"] data_format = "json" This will provide further context when inspecting Telegraf logs, allowing you to route out the problematic plugin: Without Alias: 2021-11-29T17:11:04Z E! [inputs.file] Error in plugin: could not find file: /data/sample.json With Alias: 2021-11-29T17:11:04Z E! [inputs.file::file-2] Error in plugin: could not find file: /data/sample.json Tags, tags, tags! Before we dive into the usefulness of tags, let’s quickly run through the data structure of line protocol and why it matters to understand its structure when using Telegraf. Line protocol is made up of 4 key components: - Measurement name: Description and namespace for the metric - Tags: Key/Value string pairs and usually used to identify the metric - Fields: Key/Value pairs that are typed and usually contain the metric data - Timestamp: Date and time associated with the fields Suppose we are ingesting this JSON message and overwrite the measurement name of the plugin to be: [ { "Factory" :"US_Factory", "Machine" :"Chocolate_conveyor", "Temperature" : 30, "Speed" : 0.6 }, { "Factory" :"US_Factory", "Machine" :"hard_candy_conveyor", "Temperature" : 40, "Speed" : 0.4 }, { "Factory" :"UK_Factory", "Machine" :"Chocolate_conveyor", "Temperature" : 28, "Speed" : 0.5 } ] Here is the current result in line protocol: <span style="color: #4a86e8;">factory_data</span> <span style="color: #01cc01;">1638975030000000000</span> <span style="color: #4a86e8;">factory_data</span> <span style="color: #01cc01;">1638975030000000000</span> <span style="color: #4a86e8;">factory_data</span> <span style="color: #01cc01;">1638975030000000000</span> Houston, I think we have a problem (to quote the Apollo 13 astronauts’ radio communications upon discovering a problem). Since we have not defined tags, each one of our JSON properties has become a field. In some circumstances, this might not be a problem. In this case, it’s a big one! Imagine if we wrote these metrics to InfluxDB, since each metric shares the same timestamp, we would essentially overwrite our data with the next value. This is where the importance of assigning tags early on within the Telegraf pipeline comes into play. Let’s define these now: <span style="color: #4a86e8;">factory_data</span> <span style="color: #ff9900;">Temperature=30,Speed=0.6</span> <span style="color: #980000;">1638975030000000000</span> <span style="color: #4a86e8;">Factory_data</span> <span style="color: #ff9900;">Temperature=40,Speed=0.4</span> <span style="color: #980000;">1638975030000000000</span> <span style="color: #4a86e8;">factory_data</span> <span style="color: #ff9900;">Temperature=28,Speed=0.5</span> <span style="color: #980000;">1638975030000000000</span> As you can see, tagging provides a searchable and segregatable definition to our metrics. It is an extremely important data feature used within InfluxDB. Aside from this, Telegraf can make use of tags as part of a number of advanced features like routing, which we will discuss next. Routing plugins My next golden rule is to always be in control of where your data is going. For simple Telegraf configs, this really isn’t a problem as usually you are collecting from one or more input sources and sending the data to an output plugin like InfluxDB. However, let’s consider the example shown in the above diagram. How do I make sure that my OPC-UA data is only included in the machine’s bucket of InfluxDB and my Modbus data is included within the sensors bucket. This is where routing comes into play. Just to be clear routing = filtering in official Telegraf terminology. We essentially drop the metrics before they are processed by a plugin depending on the rule used: - namepass: An array of glob pattern strings. Only metrics whose measurement name matches a pattern in this list are emitted. - namedrop: The inverse of namepass. If a match is found, the metric is discarded. This is tested on metrics after they have passed the namepass test. Let’s take a look at this example: [[outputs.influxdb_v2]] namepass = ["test"] alias = "k8" urls = ["${INFLUX_HOST}"] token = "${INFLUX_TOKEN}" organization = "${INFLUX_ORG}" bucket = "bucket1" [[outputs.influxdb_v2]] namedrop = ["test"] alias = "k8-2" urls = ["${INFLUX_HOST}"] token = "${INFLUX_TOKEN}" organization = "${INFLUX_ORG}" bucket = "bucket2" [[inputs.file]] alias = "file-1" files = ["./data/sample.json"] data_format = "json" tag_keys = ["Driver", "Channel", "Trace", "Notes", "Address", "Instrument"] name_override = "test" [[inputs.file]] alias = "file-2" files = ["./data/sample.json"] data_format = "json" tag_keys = ["Driver", "Channel", "Trace", "Notes", "Address", "Instrument"] name_override = "test2" [[inputs.file]] alias = "file-3" files = ["./data/sample.json"] data_format = "json" tag_keys = ["Driver", "Channel", "Trace", "Notes", "Address", "Instrument"] name_override = "test3" The breakdown: - There are three file input plugins. Each measurement name has been overwritten using name_override (test, test2, test3). - We have two InfluxDB output plugins, each pointing at a different bucket (bucket1, bucket2) - In bucket1 we only want to accept metrics from “test”. In this case, we use a namepass. This will drop all other metrics (test2 & test3) and write only “test” to InfluxDB. - In bucket2 we will store all other metrics accept “test” since we are already storing this in bucket1. We can use namedrop to drop “test” before it’s processed by the InfluxDB plugin. The rest of the metrics are accepted as normal. Note: It’s worth mentioning that we have only discussed dropping metrics based on the measurement name in this blog. There is also equivalent functionality for tags (tagpass, tagdrop). Find more information here. InfluxDB bucket routing by tag So currently to route data between buckets, we generate an output plugin for each bucket. This is not particularly efficient if all data is ending up in the same InfluxDB instance. Another method of routing data between buckets is to use bucket_tag. Let’s take a look at a config: [[outputs.influxdb_v2]] alias = "k8" urls = ["${INFLUX_HOST}"] token = "${INFLUX_TOKEN}" organization = "${INFLUX_ORG}" bucket_tag = "bucket" [[inputs.file]] alias = "file-1" files = ["./data/sample.json"] data_format = "json" tag_keys = ["Driver", "Channel", "Trace", "Notes", "Address", "Instrument"] name_override = "test" [inputs.file.tags] bucket = "bucket1" [[inputs.file]] alias = "file-2" files = ["./data/sample.json"] data_format = "json" tag_keys = ["Driver", "Channel", "Trace", "Notes", "Address", "Instrument"] name_override = "test2" [inputs.file.tags] bucket = "bucket2" As you can see for each input file, we define a tag (this is completely optional since you can use one of your already defined tags. The tag value, though, should equal one of your bucket names). Within our InfluxDB V2 output plugin instead of defining a bucket explicitly, we add our tag to bucket_tag. The value of this tag is used to match against a bucket name. Sensitive configuration parameters A highly important security feature to consider is storing credential information within a config. If I told a security specialist that I was going to store their enterprise systems security token within a configuration file, I think they might just implode right in front of me. One of the best ways to mitigate this is using environment variables as part of your best practice. This provides more scope to apply security best practices but also provides further flexibility in your Telegraf config. Here is an example: [[outputs.influxdb_v2]] alias = "k8" urls = ["${INFLUX_HOST}"] token = "${INFLUX_TOKEN}" organization = "${INFLUX_ORG}" bucket = "${INFLUX_BUCKET}" In the above example, each parameter for connecting to our InfluxDB instance has been anonymized by an environment variable. Note you could also deploy some form of scripting log for changing these parameters reactively and automatically restarting the Telegraf service based upon a desired system state change. New config debugging Itchy feet before pressing the go button on your Telegraf config? Don’t worry — from days working in automation, I am exactly the same. Luckily, Telegraf has a few tricks we can deploy before we hit production. Test flag The test flag provides two great opportunities: - A sense check of your configuration file (TOML parsing errors, connection errors, etc.) - It also provides insight into what the final data structure will look like based on your pipeline design. telegraf --test --config ./file_parsing/telegraf-json-v1.conf Running the above will yield the following output based upon my pipeline: > test,Address=femto.febo.com:1298,Channel=1/1,Driver=Symmetricom\ 5115A,Instrument=TSC-5120A,Trace=HP5065A\ vs.\ BVA,host=Jays-MBP Bin\ Density=29,Bin\ Threshold=4,Data\ Type=0,Duration=86400000000,Duration\ Type=5,Input\ Freq=5000000,MJD=56026.95680392361,Sample\ Interval=0.1,Sample\ Rate=1000,Scale\ Factor=1,Stop\ Condition=0,Trace\ History=1 1638543044000000000 > test-list-2,host=Jays-MBP angle_0=0.35431448844127544,angle_1=0.09063859006636221,odometer_0=9.9,odometer_1=9.1,odometer_2=9.5,updated=1634607913.044073,x=566753.985858001,y=566753.9858582001 1638543044000000000 Debug flag After running the test flag you have two options; go gun-ho into running the Telegraf service or run using the debug flag. Using the debug flag exposes extended logging for each plugin within the pipeline. A great use case for this is trying to understand connectivity/parsing errors. Note that this is where Aliases come into effect. telegraf --debug --config ./file_parsing/telegraf-json-v1.conf Our log looks like this: 2021-12-08T13:24:13Z I! Starting Telegraf 1.20.3 2021-12-08T13:24:13Z I! Loaded inputs: file (3x) 2021-12-08T13:24:13Z I! Loaded aggregators: 2021-12-08T13:24:13Z I! Loaded processors: 2021-12-08T13:24:13Z I! Loaded outputs: influxdb_v2 2021-12-08T13:24:13Z I! Tags enabled: host=Jays-MacBook-Pro.local 2021-12-08T13:24:13Z I! [agent] Config: Interval:5s, Quiet:false, Hostname:"Jays-MacBook-Pro.local", Flush Interval:10s 2021-12-08T13:24:13Z D! [agent] Initializing plugins 2021-12-08T13:24:13Z D! [agent] Connecting outputs 2021-12-08T13:24:13Z D! [agent] Attempting connection to [outputs.influxdb_v2::k8] 2021-12-08T13:24:13Z D! [agent] Successfully connected to outputs.influxdb_v2::k8 2021-12-08T13:24:13Z D! [agent] Starting service inputs 2021-12-08T13:24:28Z D! [outputs.influxdb_v2::k8] Wrote batch of 9 metrics in 28.325372ms 2021-12-08T13:24:28Z D! [outputs.influxdb_v2::k8] Buffer fullness: 0 / 10000 metrics Additionally, we can define the –once flag alongside –debug. –once will trigger the Telegraf agent to run the full pipeline once and only once. The main difference to keep in mind between the –test and –once flags is that the –test will NOT deliver the gathered metrics to the output endpoints. Here is an example of the test flag: telegraf --once --config ./file_parsing/telegraf-json-v1.conf Improving Telegraf’s efficiency So we have spent some time building a config based on the golden rules above. We start up our Telegraf service to begin ingesting and outputting metrics. The next step is to optimize Telegraf’s overall performance for the host it’s running on. This will be different for each use case, but what I hope to provide is a checklist of steps that will allow you to make a calculated judgment on what settings to change. Monitoring Telegraf I am a strong believer in the saying “eating your own dog food”. If Telegraf is designed to scrape and monitor metrics from other platforms, it should also be able to monitor itself. We can do this using the Telegraf Internal Input Plugin. Let’s create a config for it following our best practices: - Create a conf file called telegraf-internal-monitor.conf - Add the Telegraf Internal plugin and an InfluxDB output plugin (remember to apply an alias and routing). Find an example here. Note: I have chosen to enable memstats for this plugin. This is primarily due to the fact that some of the template dashboard nodes expect metric data from memstats. It is worth noting this feature is mostly relevant for debugging purposes and does not need to be enabled all the time. - Thanks to Steven Soroka, there is an InfluxDB template for dashboarding the new metrics we are collecting. Find that template here. We now have a dashboard that looks something like this: The checklist So we have already ticked the first point of our list (Gaining visibility over our current Telegraf agent performance). So what next? Well, let’s have a look at the checklist and then explain the science/madness behind each item. Time interval In short, the interval parameter defines when the Telegraf agent will trigger the collection of metrics from each input plugin. So in general we should be conscious of when and why we are collecting data from a specific input. For example, if our endpoint only updates once an hour, then it makes no sense to scrape the endpoint every 10 seconds. My golden rule is to explicitly specify a collection interval for each input plugin based upon the endpoint behavior. Ask yourself: how regularly do I need to monitor new data from this endpoint? You also have the option of defining multiple Telegraf instances. We will discuss this within the Extra Credit section. Flush interval Parallel to this, you must also consider your flush internal. Flush interval simply sets a trigger time for when all metrics stored within the buffer are written to their output endpoints. Here are some points to consider: - If you are collecting metrics on the hour, it does not make sense to flush your buffer before the hour. - Experiment with your flush interval based upon your collection throughput. For example, the closer the flush interval is to a collection interval, the higher the processing requirements at that time. - The longer the flush interval, the higher the latency until you see the metric in e.g. your database. Batching Batching governs how many metrics are sent to the output plugin at one time. For example, let’s consider we have a batch size of 20, but we are collecting 30 metrics per interval. Telegraf will automatically send the first 20 metrics to the output endpoints because we have reached our batching size. The remaining 10 will be sent afterwards. It is worth noting that when the flush interval is triggered, the entire buffer will be emptied in batches maximum to the buffer limit. For example, a buffer of 80 would release 4 batches of 20 metrics one after the other. Writes and buffer size So it is worth mentioning straight up — the buffer affects memory usage. For most systems, the default limit will not cause a noticeable effect on system performance. That being said smaller edge devices (Raspberry Pi’s, Jetsons, etc.) may require more careful management of memory. My advice is to use the internal plugin to monitor three metrics: - Write buffer size – this one is a no-brainer. Keep note of any peaks within this count which reach close to your limit. Are there any trends in this data? Sharp spikes could be due to a number of input plugins triggering in close proximity. Gradual incline can be due to limited connectivity to output plugin endpoints. - Metrics dropped – This is a strong indicator that your buffer size is too small for your desired input frequency. - Metrics gathered vs. metrics written – This cell provides a good indicator of the overall health between collecting and writing metrics. If these two line graphs mirror one another closely, then you have scope to adjust your buffer size. As you can see before 4 pm, my metrics gathered to metrics written mirrored each other nicely. After 4 pm, I doubled the flush interval parameter which we discussed earlier. Collection and flush jitter Another important feature Telegraf offers is staggering the collection and writing of metrics from different plugins. This is done using the collection and flush jitter. They both work slightly differently, so let’s discuss: - Collection jitter forces each input plugin to sleep for a random amount of time within the jitter before collecting. This can be used to avoid many plugins querying things like sysfs at the same time, which can have a measurable effect on the system. - Flush jitter randomizes the flush interval by a set amount of time within the jitter. This is primarily to avoid large write spikes from users running several Telegraf instances. Extra credit Finally, let’s discuss some optional wins which will help improve the monitoring and durability of your Telegraf solution. Remote monitoring So you might have a use case where the Telegraf host is not always accessible. In these situations, we still want to be able to monitor the health of our Telegraf agent. To do this, we can use Health Output Plugin (example config here): [[outputs.health]] service_address = "" namepass = ["internal_write"] tagpass = { output = ["influxdb"] } [[outputs.health.compares]] field = "buffer_size" lt = 100.0 Let’s break this config snippet down: - Service address allows us to designate a port for the health output to listen on. We will use this port to collect our health status. - We then namepass and tagpass to filter for the specific metric we would like to operate on. In this case, we only care about internal_write which comes from our internal plugin discussed earlier. We further filter internal_write with tagpass to only give us metrics related to the InfluxDB output plugins. - Lastly, we define a conditional argument that compares the value of a field. In this case, we are checking buffer_size to see if the value reaches 100 or over, then our conditional check fails. Note that you can define multiple checks with this plugin. The main rule to keep in mind: If all conditional statements pass, then the health plugin outputs OK, else any one rule fails then the plugin outputs unhealthy. Multiple Telegraf instances Lastly, let’s reflect on the durability of our solution in the event of a failure. Since our Telegraf runs as a single process, we run the risk that if one of our plugins fails, this could interrupt the stability of the rest. One of the primary ways to mitigate this is running multiple instances of Telegraf. Let’s consider our original industrial example: This architecture ensures that if one modbus_sensor collection fails, we will continue collecting data from our opc_ua_machines and system_performance. The easiest way to achieve this is through Docker containers. Here is an example docker-compose to get you started. Conclusion I hope this blog post gives you some confidence in the control you have over the Telegraf agent and its setup. In a lot of cases, Telegraf’s default behavior and setup will provide the plug-and- play functionality you need to get your project off the ground. It is always worthwhile keeping these golden rules in mind to make sure your Telegraf solution is scalable, efficient and maintainable as your project expands. I would love to hear your thoughts on this matter. Have I overlooked a golden rule that should be on here? Head over to the InfluxData Slack and Community forums (just make sure to @Jay Clifford). Let’s continue the discussion there!
https://w2.influxdata.com/blog/telegraf-best-practices/
CC-MAIN-2022-33
refinedweb
3,491
57.37
The following form allows you to view linux man pages. #include <unistd.h> useconds_t ualarm(useconds_t usecs, useconds_t interval); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): ualarm(): The ualarm() function causes the signal SIGALRM to be sent to the invoking process after (not less than) usecs microseconds. The delay may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers. Unless caught or ignored, the SIGALRM signal will terminate the pro- cess. If the interval argument is nonzero, further SIGALRM signals will be sent every interval microseconds after the first. This function returns the number of microseconds remaining for any alarm that was previously set, or 0 if no alarm was pending. EINTR Interrupted by a signal. EINVAL usecs or interval is not smaller than 1000000. (On systems where that is considered an error.) Multithreading (see pthreads(7)) The ualarm() function is thread-safe. 4.3BSD, POSIX.1-2001. POSIX.1-2001 marks ualarm() as obsolete. POSIX.1-2008 removes the specification of ualarm(). 4.3BSD, SUSv2, and POSIX do not define any errors. POSIX.1-2001 does not specify what happens if the usecs argument is 0. On Linux (and probably most other systems), the effect is to cancel any pending alarm. alarm(2), getitimer(2), nanosleep(2), select(2), setitimer(2), usleep(3), time(7) 2013-12-23 UALARM(3) webmaster@linuxguruz.com
http://www.linuxguruz.com/man-pages/ualarm/
CC-MAIN-2018-09
refinedweb
239
57.98
Developing Without a Build: Introduction This article is part of a series on developing without a build: - Introduction (this article) - es-dev-server - Testing (coming soon!) In this article, we explore why and if we should do development without a build step, and we give an overview of the current and future browser APIs that make this possible. In the followup articles, we look into how es-dev-server can help us with that and how to handle testing. Modern web development In the early days of web development, all we needed was a simple file editor and a web server. It was easy for newcomers to understand the process and get started making their own web pages. Web development has changed a lot since then: the complexity of the tools we use for development has grown just as much as the complexity of the things that we're building on the web. Imagine what it's like if you're coming in completely new to web development: - You first need to learn a lot of different tools and understand how each of them is changing your code before it can actually run in the browser. - Your IDE and linter likely do not understand the syntax of this framework that was recommended to you by a friend, so you need to find the right mix of plugins that makes it work. - Source maps need to be configured properly for all of the tools in the chain if you want to have any chance of debugging your code in the browser. Getting them to work with your tests is a whole other story. - You decided to keep things simple and not use typescript. You're following the tutorials and but can't get this decorators thing to work and the error messages are not helping. Turns out you didn't configure your babel plugins in the correct order... It may sound exaggerated, and I know that there are very good starter projects and tutorials out there, but this experience is common to a lot of developers. You may have jumped through similar hoops yourself. I think that's really a shame. One of the key selling points of the web is that it's an easy and open format. It should be easy to just get started right away without a lot of configuration and ceremony. I'm not criticizing the build tools themselves, they all have a role and a purpose. And for a long time, using a build was the only real way to actually create complex applications on the web. Web standards and browser implementations were just not there to support modern web development. Build tools have really helped push web development forward. But browsers have improved a lot in the past years, and there are many exciting things to come in the near future. I think that now is a good time to consider if we can do away with a big part of the tooling complexity, at least during development. Maybe not yet for all types of projects, but let's see how far we can go. This is not a step by step tutorial, but you can follow along with any of the examples by using any web server. For example http-server from npm. Run it with -c-1 to disable time-based caching. npx http-server -o -c-1 Modules can be loaded in the browser using regular script tags with a type="module" attribute. We can just write our module code directly inline: <!DOCTYPE html> <html> <head></head> <body> <script type="module"> console.log('hello world!'); </script> </body> </html> From here we can use static imports to load other modules: <script type="module"> import './app.js'; console.log('hello world!'); </script> Note that we need to use an explicit file extension, as the browser doesn't know which file to request otherwise. The same thing works if we use the src attribute: <script type="module" src="./app.js"></script> We don't write our code in just one file. After importing the initial module, we can import other modules. For example, let's create two new files: src/app.js: import { message } from './message.js'; console.log(`The message is: ${message}`); src/message.js: export const message = 'hello world'; Place both files in a src directory and import app.js from your index.html: <!DOCTYPE html> <html> <head></head> <body> <script type="module" src="./src/app.js"></script> </body> </html> If you run this and check the network panel, you will see both modules being loaded. Because imports are resolved relatively, app.js can refer to message.js using a relative path: This seems trivial, but it is extremely useful and something we did not have before with classic scripts. We no longer need to coordinate dependencies somewhere central or maintain a base URL. Modules can declare their own dependencies, and we can import any module without knowing what their dependencies are. The browser takes care of requesting the correct files. Dynamic imports When building any serious web application we are usually going to need to do some form of lazy loading for best performance. Static imports like we saw before cannot be used conditionally, they always need to exist at the top level. For example, we cannot write: if (someCondition) { import './bar.js'; } This is what dynamic imports are for. Dynamic imports can import a module at any time. It returns a Promise that resolves with the imported module. For example let's update the app.js example we created above: window.addEventListener('click', async () => { const module = await import('./message.js'); console.log(`The message is: ${module.message}`); }); Now we are not importing the message module right away, but delaying it until the user has clicked anywhere on the page. We can await the promise returned from the import and interact with the module that was returned. Any exported members are available on the module object. Lazy evaluation This is where developing without a bundler has a significant benefit. If you bundle your application before serving it to the browser, the bundler needs to evaluate all your dynamic imports to do code splitting and output separate chunks. For large applications with a lot of dynamic imports, this can add significant overhead as the entire application is built and bundled before you can see anything in the browser. When serving unbundled modules, the entire process is lazy. The browser only does the necessary work to load the modules that were actually requested. Dynamic imports are supported by the latest versions of Chrome, Safari, and Firefox. It's not supported in the current version of Edge but will be supported by the new Chromium-based Edge. Read more about dynamic imports at MDN Non-relative requests Not all browser APIs resolve requests relative to the module's location. For example when using fetch or when rendering images on the page. To handle these cases we can use import.meta.url to get information about the current module's location. import.meta is a special object which contains metadata about the currently executing module. url is the first property that's exposed here, and works a lot like __dirname in NodeJS. import.meta.url points to the url the module was imported with: console.log(import.meta.url); // logs We can use the URL API for easy URL building. For example to request a JSON file: const lang = 'en-US'; // becomes const translationsPath = new URL(`./translations/${lang}.json`, import.meta.url); const response = await fetch(translationsPath); Read more about import.meta at MDN When building an application you will quickly run into having to include other packages from npm. This also works just fine in the browser. For example, let's install and use lodash: npm i -P lodash-es import kebabCase from '../node_modules/lodash-es/kebabCase.js'; console.log(kebabCase('camelCase')); Lodash is a very modular library and the kebabCase function depends on a lot of other modules. These dependencies are taken care of automatically, the browser resolves and imports them for you: Writing explicit paths to your node modules folder is a bit unusual. While it is valid and it can work, most people are used to writing what's called a bare import specifier: import { kebabCase } from 'lodash-es'; import kebabCase from 'lodash-es/kebabCase.js'; This way you don't specifically say where a package is located, only what it's called. This is used a lot by NodeJS, whose resolver will walk the file system looking for node_modules folders and packages by that name. It reads the package.json to know which file to use. The browser cannot afford to send a bunch of requests until it stops getting 404s, that would be way too expensive. Out of the box, the browser will just throw an error when it sees a bare import. There is a new browser API called import maps which lets you instruct the browser how to resolve these imports: <script type="importmap"> { "imports": { "lodash-es": "./node_modules/lodash-es/lodash.js", "lodash-es/": "./node_modules/lodash-es/" } } </script> It's currently implemented in chrome behind a flag, and it's easy to shim on other browsers with es-module-shims. Until we get broad browser support, that can be an interesting option during development. It's still quite early for import maps, and for most people, they may still be a bit too bleeding edge. If you are interested in this workflow I recommend reading this article Until import maps are properly supported, the recommended approach is to use a web server which rewrites the bare imports into explicit paths on the fly before serving modules to the browser. There are some servers available that do this. I recommend es-dev-server which we will explore in the next article. Caching Because we aren't bundling all of our code into just a few files, we don't have to set up any elaborate caching strategies. Your web server can use the file system's last modified timestamp to return a 304 if the file hasn't changed. You can test this in your browser by turning off Disable cache and refreshing: Non-js modules So far we've only looked into javascript modules, and the story is looking pretty complete. It looks like we have most of the things we need to write javascript at scale. But on the web we're not just writing javascript, we need to deal with other languages as well. The good news is that there are concrete proposals for HTML, CSS and JSON modules, and all major browser vendors seem to be supportive of them: The bad news is that they're not available just yet, and it's not clear when they will be. We have to look for some solutions in the meantime. JSON In Node JS it's possible to import JSON files from javascript. These become available as javascript objects. In web projects, this is used frequently as well. There are many build tool plugins to make this possible. Until browsers support JSON modules, we can either just use a javascript module which exports an object or we can use fetch to retrieve the JSON files. See the import.meta.url section for an example which uses fetch. HTML Over time web frameworks have solved HTML templating in different ways, for example by placing HTML inside javascript strings. JSX is a very popular format for embedding dynamic HTML inside javascript, but it is not going to run natively in the browser without some kind of transformation. If you really want to author HTML in HTML files, until we get HTML modules, you could use fetch to download your HTML templates before using it with whatever rendering system you are using. I don't recommend this because it's hard to optimize for production. You want something that can be statically analyzed and optimized by a bundler so that you don't spawn a lot of requests in production. Luckily there is a great option available. With es2015/es6 we can use tagged template string literals to embed HTML inside JS, and use it for doing efficient DOM updates. Because HTML templating often comes with a lot of dynamism, it is actually a great benefit that we can use javascript to express this instead of learning a whole new meta syntax. It runs natively in the browser, has a great developer experience and integrates with your module graph so it can be optimized for production. There are some really good production ready and feature complete libraries that can be used for this: - htm, JSX using template literals. Works with libraries that use JSX, such as react - lit-html, a HTML templating library - lit-element, integrates lit-html with web components - haunted, a functional web components library with react-like hooks - hybrids, another functional web component library - hyperHTML, a HTML templating library For syntax highlighting you might need to configure your IDE or install a plugin. CSS For HTML and JSON there are sufficient alternatives. Unfortunately, with CSS it is more complicated. By itself, CSS is not modular as it affects the entire page. A common complaint is that this is what makes CSS so difficult to scale. There a lot of different ways to write CSS, it's beyond the scope of this article to look into all of them. Regular stylesheets will work just fine if you load them in your index.html. If you are using some kind of CSS preprocessor you can run it before running your web server and just load the CSS output. Many CSS in JS solutions should also work if the library publishes an es module format that you can import. Shadow dom For truly modular CSS I recommend looking into Shadow dom, it fixes many of the scoping and encapsulation problems of CSS. I've used it with success in many different types of projects but it's good to mention that it's not yet a complete story. There are still missing features that are being worked out in the standard so it may not yet be the right solution in all scenarios. Good to mention here is the lit-element library, which offers a great developer experience when authoring modular CSS without a build step. lit-element does most of the heavy lifting for you. You author CSS using tagged template literals, which is just syntax sugar for creating a Constructable Stylesheet. This way you can write and share CSS between your components. This system will also integrate well with CSS modules when they are shipped. We could emulate CSS modules by using fetch, but as we saw with HTML it's hard to optimize this for production use. I'm not a fan of CSS in JS, but lit-element's solution is different and very elegant. You're writing CSS in a JS file, but it's still valid CSS syntax. If you like to keep things separated, you can just create a my-styles.css.js file and use a default export of just a stylesheet. Library support Luckily the amount of libraries shipping es module format is growing steadily. But there are still popular libraries which only ship UMD or CommonJS. These don't work without some kind of code transformation. The best thing we can do is open issues on these projects to give them an indication of how many people are interested in supporting the native module syntax. I think this is a problem that will disappear relatively quickly, especially after Node JS finishes their es modules implementation. Many projects already use es modules as their authoring format, and I don't think anyone really likes having to ship multiple imperfect module formats. Final thoughts The goal of this article is to explore workflows where we don't need to do any building for development, and I think we've shown that there are real possibilities. For a lot of use cases, I think we can do away with most of the tooling for development. In other cases, I think they can still be useful. But I think our starting point should be reversed. Instead of trying to make our production builds work during development, we should be writing standard code that runs in the browser as is and only perform light transformations if we think it's necessary. It's important to reiterate that I don't think that build tools are evil, and I am not saying that this is the right approach for every project. That is a choice that each team should make for themselves based on their own requirements. es-dev-server You can do almost everything described in this article with any regular web server. That being said, there are still web server features which can really help with the development experience. Especially if we want to run our applications on older browsers, we might need some help. At open-wc we created es-dev-server, a composable web server that focuses on developer productivity when developing without a build step. Check out our next article to see how we can set it up! Getting started To get started with developing without any build tools, you can use the open-wc project scaffolding to set up the basics: npm init @open-wc It sets up the project with lit-element, a web component library. You can swap this for any library of your choosing, the setup is not specific to web components. Discussion Great article! I know that you mention it’s out of scope to go through all CSS solutions, but is there any one that you’d recommend/endorse for someone just getting started? I know I’ve personally had success with github.com/lukejacksonn/csz, but curious if there are others that aren’t webpack-dependent. Also, shameless plug for @pika/web to install npm dependencies that don’t need bare module imports or a special dynamic file server: github.com/pikapkg/web Thanks! I don't have that much experience with build-less css-in-js solutions yet. That looks like a pretty interesting library though. I think we can collect some different libraries, and dive into an investigation in a followup article :) Pika is really interest too! Should we be concerned about the rabbit hole of HTTP requests that could have it's own negative impacts... if there are any? I'm still not leveraging the benefits of HTTP/2's request and response multiplexing; so I'm wondering if bundling and all it's "tree shaking" refinements for a single file request may be more performant? 🤷♂️ I see es-dev-server has the word "dev" in it. Is this only recommended for development, not production? Is there not yet any HTTP/2 server for production that is better than bundling?
https://practicaldev-herokuapp-com.global.ssl.fastly.net/open-wc/developing-without-a-build-1-introduction-26ao
CC-MAIN-2020-45
refinedweb
3,161
62.98
Hi everybody, I really tried to do my assignment but I am lost . Any helping is very helpful , Thanks Write a program that will generate a set of 50 random integers in the range -20 to + 20. The program should display the following: a) The number of positive and negative numbers (treat 0 as positive). b) The average value of the positive numbers c) The average value of the negative numbers d) The largest and smallest number. e) The average of all the numbers. You must use a for loop structure for this question along with the Math.random() method to generate the random numbers. Hint: Generate numbers in the range of 0-40 and subtract 20 My try is : public class Assign4A { public static void main(String[] args){ // a for (int i = 0; i < 50; i++) { int random = (int)(Math.random() * (40) + (-20) ); System.out.print(random + " " ); } //b for ( int i = 0; i < 50 ; i++) { int random = (int)(Math.random() * (49) + 1 ); System.out.print( random + " " + "\n" ); } int n = 50; int sum = runSimulation(n); System.out.print(sum ); } public static int runSimulation (int n){ int sum = 0; for (int i = 1; i <= n; i++){ int sim = (int)(Math.random() * (49) + 1 ); sum += sim; } return sum; } }
https://www.daniweb.com/programming/software-development/threads/437844/homework-about-randomnumber-loops
CC-MAIN-2018-30
refinedweb
206
66.33
29 May 2012 07:17 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The producer shut the plant in early May because of high inventory levels, which was a result of slow demand in the hydrous ethanol market. “Our stock levels were growing as the ethanol market started to weaken in the last 2-3 months,” the source said, without elaborating further. The company was running the plant at around 80% capacity following a turnaround in April. “We are not sure if we will raise the operating rate to 100% capacity as this will depend on the market situation in the near future. Currently, buyers are covered with material until August, so we can only make offers in mid-J
http://www.icis.com/Articles/2012/05/29/9564746/vietnams-dai-viet-to-restart-dak-nong-ethanol-unit-next.html
CC-MAIN-2014-52
refinedweb
119
60.65
Programming Reference/Librarys Question & Answer Q&A is closed Q&A is closed Returns a string to the screen. cputs is the null-terminated string from str in the current text window. The newline character is not here appended to the string. Depending _directvideo of the global variable, the string is written either directly or through a BIOS call to screen memory. To contrast to fprintf and printf, not translated cputs line character (\ n) in the combination of characters carriage return / line feed (\ r \ n). Note: Do not use this function in any case in Win32 GUI applications. #include <conio.h> int main(void) { clrscr(); window(10, 10, 80, 25); cputs("Text in Window\r\n"); getch(); return 0; } Text in Window
https://code-reference.com/c/conio.h/cputs
CC-MAIN-2020-16
refinedweb
122
63.7
Comparing Linked Data Triplestores Virtuoso, GraphDB, Blazegraph, Stardog, AnzoGraph and more… There are many Triplestores available and it is difficult to decide which is best for each use-case. In this article I tie all of my previous posts together and explore the pros and cons of some of the most popular triplestores. I will be using RDF and SPARQL queries that I have created and discussed previously. If interested, I have covered: Why Use Linked Data to Tackle Big Data Problems Understanding Linked Data Formats Creating Linked Data with OpenRefine Constructing SPARQL Queries Edit (22/01/2019): AnzoGraph completes C++ compilations on the first run of a query so was unfairly represented originally. I have therefore evaluated AnzoGraph once again and updated the results throughout. The Triplestores: I have tried to cover a wide array of Triplestores and filter down as we explore deeper. These were all deployed on the same server, one at a time, with default settings where possible. To begin in no particular order, I cover: Blazegraph Version: 2.1.4 Deployed using Docker from this repository. Predicate used in full text index query: bds:search Stardog Version: 5.3.5 Installed directly following the official instructions. Predicate used in full text index query: <tag:stardog:api:property:textMatch> Virtuoso Version: 07.20.3217 Deployed using Docker from this repository. Predicate used in full text index query: bif:contains GraphDB Version: graphdb-free-8–3–1 Deployed using Docker from this repository. Predicate used in full text index query: luc:myIndex AnzoGraph Version : r201901202057.beta Deployed using Docker following official instructions. AllegroGraph Version: 6.4.3 Deployed using Docker from this repository. MarkLogic Version: 9.0–7 Deployed using Docker from this repository. Apache Rya Rya is still incubating so not quite mature enough to compare fairly. In the future, when suitable, I will do a further comparison including Rya. RDF Loading Speed: It may not be the most important factor, but loading RDF into the triplestore is one of the first things we will need to do. As mentioned above, the data we are loading was created in one of my previous posts and can be downloaded here. Right from the start, AllegroGraph takes an extraordinarily long time to populate. Marklogic is overshadowed by AllegroGraph but still takes 2 minutes to load the data in RDF/XML format! Due to these extreme loading times and other factors (discussed throughout this article) I eliminated these two from deeper exploration. Inspecting the chart, without AllegroGraph and MarkLogic, we can see that loading RDF in RDF/XML format is generally faster than in N-Triples. AnzoGraph does not support RDF/XML as it is a much newer triplestore and RDF/XML is an older format that is dropping in popularity. Outstandingly, AnzoGraph loads the data in N-Triples format in just 18753ms, significantly beating all others. It appears that by excluding older RDF formats, AnzoGraph can optimise loading speeds for the newer formats. GraphDB is the only other triplestore that is faster to load N-Triples than RDF/XML. Blazegraph, Stardog and Virtuoso are all much faster at loading RDF/XML (over twice as fast in Stardog and Virtuoso). Why this is the case I do not know, but this may be important to consider if you will be loading lots of data regularly. Remember from one of my previous articles, if you are loading data using data streams you cannot use RDF/XML so don’t fall into that trap. SPARQL Query Speeds: In an article about constructing SPARQL queries, I created eight queries of varying complexity to run on the data I just loaded above. These queries can be found here. In summary, the queries are: Q1: List the names of every gold medallist (excluding duplicates). Q2: List the names of every athlete, with at least one medal, alongside their total number of medals (sorted by the number of medals). Q3: List each country alongside the average height and weight of its athletes (sorted by the average height). Q4: List each year alongside the oldest Judo competitor in that year Q5: List every athlete with “louis” in their name alongside the city and season that they competed in. This query uses regex. Q6: Get a list of every city that an athlete from Serbia and Montenegro competed in. Count the number of males and females that ever competed in one of those cities and return these counts. The next two are a little more complex: Q7: List every sport’s name that has a stored team size in DBpedia and return these sizes next to the corresponding sport. QFTI: List every athlete with “louis” in their name alongside the city and season that they competed in. This query uses each triplestores full text index feature unlike Q5. I ran each of these queries three times and chart the mean of these times. The first six queries are very standard and should run with no problems on every triplestore. In the following chart I have summed the result times to get an overall idea of each triplestore’s performance: This aggregation suggests that Virtuoso and AnzoGraph are the ones to watch as they are significantly faster (almost 3 times faster than the next best; Stardog) than all of the other triplestores over six diverse queries. Stardog and GraphDB are similar to each other and Blazegraph is a lot slower overall. AnzoGraph was by far the fastest at loading data so this result is promising. It is possible that AllegroGraph and MarkLogic take additional loading time to optimise the graph for queries so in a future article (once problems I discuss later are resolved) I will test this hypothesis. This summary is nice to get an idea but let’s explore each triplestore’s performance per query. The fastest queries to complete were queries 1 and 4 so we will investigate these first. Interestingly, GraphDB is the fastest to complete these simple queries with Virtuoso being the slowest to finish query 4 (still only 90ms). Stardog and AnzoGraph take a particularly long time to complete query 1. Stardog for example took 412ms to complete compared to GraphDB which took just 16.7ms. This disparity to answer the exact same query could be significant but, as we saw above, their total time to complete the first six queries was similar. Next, queries 2, 3 and 5 are a little more complex: With the exception of query 2, AnzoGraph is faster than the others and Blazegraph is the slowest. Queries 2 and 3 both require more operations (count, mean, group, order, etc..) than queries 1 and 4. This suggests that GraphDB is the fastest at retrieving entities but Virtuoso is far better at running operations efficiently. Both Blazegraph and GraphDB are much slower to complete query 3 than query 2 which suggests that they are not optimised for mathematical queries. In contrast, AnzoGraph seems to be the opposite, completing query 3 much faster than query 2. Query 5 is a text query using regex which AnzoGraph performs the fastest, followed by Stardog. Blazegraph, which is noted to be very good at text queries, performs the slowest. This is because this query uses standard regex and not its full text indexing feature. This is shown later in the full text index query. It is also important to note that AnzoGraph does not have have a built-in full text index which is likely why it optimises regex queries so much more than the others. If you want to use multiple triplestores, these regex results are useful to ensure your query will run on all of them without any query tailoring. Query 6 is a nested query that traverses almost the entire knowledge graph twice. These results really show the power of Linked Data. If you work with relational databases you will know that a query with this many joins would take minutes if not hours. Virtuoso and AnzoGraph complete this query in an exceptional time. Virtuoso in 128ms and AnzoGraph in just 105.7ms! Stardog and GraphDB follow at around 600ms and Blazegraph trails behind, taking over 3 seconds to complete. If you plan to regularly send deep queries, Blazegraph may be a poor choice. Query 7 is a federated query, meaning it links to an external knowledge graph which in this case is DBpedia (running on Virtuoso). This means that the time does depend on the response of a public (and popular) triplestore. As mentioned, I did repeat the queries multiple times so the effects of this variation should be minimised. AnzoGraph was the fastest and surprisingly, Virtuoso the slowest to complete query 7. The poor performance from Virtuoso results from how it stores the data. The linked data we loaded contained duplicates due to the method I used to create it. Most triplestores never store duplicates whereas Virtuoso stores duplicate literals. This means that the sport entities have duplicate labels which are sent to the DBpedia endpoint. DBpedia then has to find the team size of each sport multiple times, hence the increased response time. Edit (17/12/2018): I cleared my Virtuoso instance and loaded the data without duplicates and re-tested this query. Here is the updated chart: I left both charts to highlight that this can happen in Virtuoso. It may seem like Stardog responded incredibly fast but it has no bar because it timed out every time. This is due to the fact that Stardog does not optimise federated queries adequately. Finally, in the full text query I want the same results as in query 5 but instead of using regex, the query is customised for each triplestore. This is done by using the predicates listed above in the Triplestores section. AnzoGraph by itself does not implement it’s own full text index queries so does not appear in this chart. If you want this feature you have to integrate AnzoGraph with its counterpart, Anzo. Virtuoso once again outperforms the other triplestores followed by Blazegraph and GraphDB. Stardog took significantly longer but still only took 127.7ms. If you scroll up and inspect the query 5 results, you will notice that AnzoGraph was the fastest and Blazegraph was the slowest. This is because Blazegraph focuses on full text index queries so has not optimised for regex queries. Blazegraph took 2586.7ms to complete query 5 but only 42.7ms to return the exact same results using its full text index. To point out, Stardog is not slower to complete this query (127.7ms) than query 5 (509.3ms), this is just not their focus. AnzoGraph and Virtuoso were not the fastest to complete every query but overall they come out on top if speed is your priority. Just note that literals can be duplicated in Virtuoso which can significantly slow down federated queries. Deployment: Blazegraph I deployed Blazegraph using Docker from this repository that has very clear documentation. You can load data into Blazegraph in multiple ways but with large RDF files, data must be accessible from within the container. You can docker cp your data into the container but we just set up a volume and had no problems. Overall: Very easy to deploy and load data. Stardog Stardog was also very easy to deploy. You have to download a zip and licence key, which you have to make sure is in the right place, but that is as complex as it gets. One command to start Stardog and one more to load your data. Overall: Very easy to deploy and load data. Virtuoso Similar to Blazegraph, Virtuoso is very easy to deploy following these instructions. These also detail volumes for loading data. There are some quirks with isql-v to load your data but following the documentation, it is relatively simple. Overall: Very easy to deploy and fairly easy to load data. GraphDB Again, using this repository, GraphDB deployed smoothly. The instructions do not detail volumes so adding -v /path/to/data:/root/graphdb-import to the docker run command is what you need to ensure your data shows up on the interface. Again, this is only required if you are loading very large data files as you can select a local file through the user-interface. Overall: Very easy to deploy and load data. AnzoGraph Using the official Docker image of AnzoGraph, everything starts fine. There are some bugs however and if you hit one and want to restart, everything breaks. This is true even if you restart a completely functioning container. As you can see from our results, you can deploy, load and query AnzoGraph as long as you never hit a bug or restart the container. Edit (22/01/2019): These problems are now fixed in the latest Docker Image. Overall: Loading data is simple enough but everyone needs to restart at some point so the official image needs fixed. AllegroGraph Using the official Docker repository, AllegroGraph was easy to deploy but unlike the others, is not the smartest when loading data. The free version of AllegroGraph can store up to 5,000,000 triples. The data I was loading contained more than this if you count the duplicate triples (which are not stored). If I removed the duplicates, I could not fairly compare the loading and query times against the other triplestores which is another reason I decided not to include AllegroGraph in this round of speed tests. Overall: Easy to deploy but a pain to load without cleaning RDF first. MarkLogic Using these instructions, MarkLogic is fairly easy to deploy. You need to download an installer and edit a few lines of code but it is well documented. Loading data was relatively easy but it is clear that MarkLogic is made for consultants to use. I could not find an easy way to query the data. Maybe I missed something obvious but neither the user interface or documentation provided me with an answer so this was an additional reason to exclude MarkLogic from this round of speed tests. Overall: Fairly easy to deploy and load data but querying that data is a mystery. User Interface: Obviously this section is more subjective so for clarity I consider these factors as important: - Ease to load data - Ease to query data - Ease to explore data - Ease to monitor system - Ease to manage data I have excluded AllegroGraph and MarkLogic from my detailed discussion here as poor performance in previous tests can not be outweighed by a nice interface. In short, Allegrograph has a fairly nice interface whereas MarkLogic’s UI is very un-intuitive. Edit (22/01/2019): I also don’t cover AnzoGraph’s UI as it originally appeared to perform poorly. Its interface is very easy to use! Data loading, data querying and system monitoring are all very intuitive. Data is managed using graphs and data exploration could be improved if you compare it to GraphDB. I will discuss it more in depth in the future. Blazegraph Blazegraph has a relatively nice user-interface and I consider it easy to find whatever I need. There is a tab called update with multiple options to load your data. If a method is not suitable (data file too large for example) the error message clearly explains alternative methods. The query tab is also simple and intuitive. Results are shown in simple tables and queries are stored in a history which is always useful when building applications. Query errors generally explain the problem which helps when debugging queries (that have syntax errors). For other errors (such as a spelling error in a predicate), Blazegraph has an explore tab that is opened whenever you click on a URI in query results. You can also manually type a URI in the explore tab which will show every link to and from that given entity. This explorer is a bit clunky but really helps with query creation and debugging as you can quickly see what predicates are linking entities. Monitoring Blazegraph is a simple couple of tabs (status and performance) but it does have useful information such as status of running queries, system up-time, etc… Extensive logs can also be accessed using the docker logs command. You can split your RDF by creating ‘Namespaces’ in Blazegraph which are extremely useful to keep applications separate and queries fast. You can enable geospatial mode or full text mode for example over a portion of your data instead of the whole lot. Stardog Compared to Blazegraph, Stardog has an overall prettier interface. Loading data can not be done through the UI however but is a simple command. Once you have a database (equivalent of namespace), you can update it with an update SPARQL query. The query panel is very similar to the others, queries can be typed into a text box and results display in a table. Errors are again fairly understandable to sort syntax errors and queries can be saved for later use. Exploring data (called browsing in Stardog) is very easy and has a much nicer design. To show the full extent of this, here is a screenshot from the official docs (displaying all the niceties): Like Blazegraph, monitoring Stardog can be done through the UI with more detailed information stored in the logs. As mentioned, you can load data into separate databases to keep your data organised. Similar to Blazegraph, features like full text indexing can be turned on or off per database. Stardog also allows the activation and deactivation of databases individually if that is something you need. Virtuoso Compared to the others, Virtuoso has the worst interface. This has the benefit that you can be sure it will work in any browser. You cannot load data using the UI, this must be done using isql through your terminal. This is easy enough but removes the options to upload data held on your local machine. Querying is again standard, a little hard to find when you first use Virtuoso but once there it is a text box like the others. Results are displayed in a table like the others and errors are relatively clear. Annoyingly (really annoyingly), Virtuoso does not have a nice implementation of data exploration. You have to write a query every time you want to remember what predicate is used to link anything. For development, this is very time consuming! If you are constructing a large query for example, you have to keep copying it somewhere so that you can run tiny queries to explore your knowledge graph. In Blazegraph these are two separate tabs which keeps exploration and construction isolated from one and other. For this reason alone, I avoid developing with Virtuoso. Monitoring the system is quite extensive in Virtuoso and again, there are detailed logs if you need. Data is organised using graphs, I do not find this as simple to manage my data as I can in Blazegraph or Stardog. They work similarly but in practice it is not as intuitive through the UI. One benefit is that you can use graphs as a variable in your SPARQL queries. In the others, you can use SERVICE queries to query multiple namespaces but in Virtuoso you can construct queries that for example: “Get all graphs that contain people entities and return the number of people in each of these graphs”. If you have many graphs, this can really simplify cross-graph queries. GraphDB Finally, GraphDB has a very pretty interface. Loading data is very intuitive and there are many options so you can do this however you want. Querying is similar but again, very nice to look at. The text box implements syntax highlighting, auto-prefixing and can be saved easily. Results can be displayed in a table but, through integration with Google charts, can be visually output also. As you may have noticed, I really appreciate the ability to explore my data during development and GraphDB is by far the winner for this. Data can be visually explored which speeds up query construction significantly. You can very quickly look at the section of the graph you are working with. If your query is not working you can instantly see if there is a spelling error in a predicate for example. This is an example of the visual explorer: Monitoring the system in GraphDB is once again similar to the others, logs can be easily accessed using the docker logs command if you ever need more information than is provided through the interface. Similar to Virtuoso, GraphDB uses graphs to organise data. Though the interface is much easier to manage than in Virtuoso. Every dataset is given a new graph by default unless you actively tell it to combine with an existing graph. Graphs can be managed and deleted from a table which ensures clarity to the user. Authentication: All of the triplestores apart from Blazegraph have an authentication layer built in. GraphDB is off by default but you can turn security on and set up users and roles. Stardog does have its authentication on by default but you should change the default username and password to make use of it. Virtuoso, AnzoGraph, AllegroGraph and MarkLogic have security on by default. If security is of high importance, it is probably best to avoid Blazegraph. Conclusions: Depending on your priorities, there are a few viable options but in my opinion I recommend the following: - GraphDB for development while you are constructing your application. - AnzoGraph or Virtuoso when you move into production if speed is important. The reason for this is, the extra time your queries take to run does not come close to the amount of additional time you have to spend exploring and debugging your data in Virtuoso. Once your queries are built, then you can move to Virtuoso or AnzoGraph to take advantage of their speed. This is very simple to do as SPARQL queries are standard so you just have to change endpoint. If you are using a feature like full text index search you may have to switch a few predicates but this is very quick and easy to do with a find and replace. Notes: - Needing to use an old browser? Use Virtuoso. - If regularly loading large batches of data, use RDF/XML if running Virtuoso, Blazegraph or Stardog. - Remember however, RDF/XML is not suitable for streaming. - Literals can be duplicated in Virtuoso which can significantly slow down federated queries. In the future, when Apache Rya becomes more stable, I will compare triplestores with the no-duplicate data so that AllegroGraph and Rya can be added. The results in this article can be found here. Next I will increase the number of triples to see how these triplestores perform on a larger scale.
https://medium.com/wallscope/comparing-linked-data-triplestores-ebfac8c3ad4f
CC-MAIN-2020-34
refinedweb
3,791
62.68
Type: Posts; User: rockx... 2kaud's code has already solved the problem. Now this leaves two of my requirements unattended. these are 3 & 4. or the application should randomly pick 5 nodes without pick one node twice. ok, as stated in my first post. i want the user to enter any integer between 1-60 (inclusive). the user has the liberty to enter any particular integer more than two times. And the set of... I also need to know as to why does the program crash when i change if ( it->second > 1 ) to while ( it->second > 1 ) #include <list> #include <map> #include <iostream> #include <algorithm> #include <fstream> typedef std::list<int> IntList; typedef std::map<int, int> IntMap; using namespace std; Dear Paul, when i insert the following code myList.sort(); IntList::iterator lt = myList.begin(); while(lt != myList.end()) { cout << *lt << " "; Here are some good reference for your needs... what can i do to randomly select 5 nodes from the following IntList myList; and output it to the screen Assuming there are more than 5 entries in the list
http://forums.codeguru.com/search.php?s=26c7caa3a69597262b7d146362260ab0&searchid=2752083
CC-MAIN-2014-15
refinedweb
181
75.3
Objective Electromyography (EMG) measures muscle response or electrical activity in response to a nerve's stimulation of the muscle. This project describes the process of obtaining the raw EMG data from a muscle flex and converting it into a real-time signal that can communicate with a PIC® microcontroller to be used in various embedded control applications. Introduction The project uses a Curiosity High Pin Count (HPC) Development Board and a PIC16F18875 microcontroller in conjunction with an EMG click™ board, 3-connector sensor cable, and electrode pads. The raw EMG data obtained from a muscle flex is rather noisy with rapid and random changes. This article outlines how to use a PIC microcontroller to condition the signal, essentially smoothing it out, to make it effective for further use in embedded control. We use a combination of rectification, peak-to-peak filter, and a moving average filter to achieve a smooth signal. You may use this signal conditioning module for any application that needs EMG signals. These projects demonstrate the use of the modules: "Controlling a Motorized Prosthetic Arm using EMG Signals" and "Push-Up Counter Bluetooth Application Using EMG Signals". Materials Hardware Tools - Curiosity HPC Development Board - PIC16F18875 - EMG Click: MIKROE-2621 - EMG Cable: MIKROE-2457 - Sensor Adhesive Electrodes Software Tools Exercise Files Signal Processing Implementation The raw EMG signals output by the EMG sensor are noisy with many rapid changes, which makes it hard to use these signals in conjunction with a microcontroller. Hence, we need to process the signals further to achieve a smoother signal that is more tolerant of noise. The processing of the signals has been achieved by two filters: a peak-to-peak filter and a moving average filter. This signal has been further rectified to produce a smoother signal capable of communicating with a PIC microcontroller for embedded control. Circular Buffer Implementation Since the 8-bit microcontrollers have a limited memory to implement multiple filters, circular buffers have been used for storing and operating on data. Circular buffers are fixed-sized FIFO queues that behave like they were connected end-to-end and as though the memory was contiguous and circular. The advantage of a circular buffer is that when any new data point is added or consumed, the elements do not need to be shuffled around like in most other data structures. When data is added, the front pointer advances; when data is consumed, the tail pointer advances. If the end of the buffer is reached, we simply wrap around to the beginning to replace the oldest data. A total of three circular buffers have been used: - Signal Buffer (sb_data): To continuously store the sampled EMG signals incoming from the sensor - Peak Buffer (pk_data): Stores elements in a moving window to calculate a neutral peak value - Moving Average Buffer (ma_data): Stores moving average that updates for every new data point Each buffer has the functions _isfull, _isempty, _insert, _remove, and _peek that are used as necessary for the implementation of the filters. A .c source file and a .h header file together contain the declarations and definitions of all these functions for each buffer in the files of their namesakes: - signal_buffer.c and signal_buffer.h – Functions for Signal Buffer - peak_filter.c and peak_filter.h – Functions for Peak Buffer - moving_avg_filter.c and moving_avg_filter.h – Functions for Moving Average Buffer Filters Implementation The filters for processing the signal are implemented in the signal_processing.c source file and the corresponding signal_processing.h header file. There are two main functions: - get_neutral_peaktopeak(): This function implements the Peak Filter and returns neutral_datapoint calculated using highest and lowest peaks among the elements present in the Peak Buffer (pk_data) at a given point of time. - get_moving_average(): This function implements the Moving Average Filter and returns the average of data points present in the Moving Average Buffer (ma_data) for a given window. The sum is updated for every new data point added (and/or removed). Functional Flow Diagram - A timer interrupt is generated every 20 ms which triggers the Timer Interrupt Handler to start acquiring ADC samples from the EMG sensor. - The A/D conversion result at the current time is added to the FIFO Signal Circular Buffer (sb_data). - The first element from the buffer is added to another set of elements whose neutral peak values are calculated. - A moving average is calculated for a window of fixed size that is updated with every new addition of a data point. - We compare the obtained moving average value with a threshold to see if it passes as an intended muscle flex to eliminate noise. - This data can now be used in any embedded control application. Connection Diagram HARDWARE SETUP HARDWARE CONNECTIONS Make the following hardware connections: - Connect the USB power to the board to turn it on. - Connect the 3.5 mm phone jack to the EMG sensor module. - Connect three sensor pads to the three electrodes attached to the cable for metallic contact. - Insert the EMG click module on the mikroBUS™ Slot 2 of the Curiosity board (refer to the Hardware Setup Diagram). - Prepare the skin where you would like to attach the electrodes by wiping it clean and letting the area dry. - Your forearm is recommended for best results, although any muscle group would give you EMG signals. - Place the red electrode at the center of the muscle group and blue electrode adjacent to it at the end of the muscle group - Place the black electrode (reference electrode) where a bone is prominent (such as the side of your wrist). Create a New Project Create a new standalone project in MPLAB X for a PIC16F18875. If this is your first time using MPLAB X, follow the instructions in the following article: "Create a Standalone Project". 4 Setup Project Resources These peripherals need to be selected for this project: - System Module - Interrupt Module - Pin Module - Analog-to-Digital Converter with Computation (ADCC) - TMR6 - EUSART The System Module, Interrupt Module, and Pin Module are automatically included, but the ADCC, TMR6 and EUSART must be selected for the project. The list of peripherals shows up under the "Device Resources" list. Double-click on each to have them added to the project. The result should look like the picture below: System Module Setup Click on the 'System Module' and the MCC screen will show the 'Easy Setup' menu. - Select 'HFINTOSC' from the Oscillator Select drop-down. - Select '16_MHz' from the HF Internal Clock drop-down. - Select '1' from the Clock Divider drop-down. - For the Watchdog Timer Enable Option, select 'WDT Disabled, SWDTEN is ignored'. - At the "Programming" section, check the box for 'Low-Voltage Programming Enable'. - On the 'Registers' tab, all registers can be left to their default values. Timer Module Setup Click on the TMR6 Module and the MCC screen shows the 'Easy Setup' menu. - Check the box 'Enable Timer' option. - Select 'FOSC/4' as the Clock Source . - Choose the Postscaler value as '1:8'. - Choose the Prescaler value as '1:64'. - Choose 'Rising Edge' for Polarity. - Type 20 ms in the Timer Period box and press Enter. The nearest available period will show under 'Actual Period'. - Check the box for 'Enable Timer Interrupt'. - All other fields can be left to their default values. ADC Module Setup Click on the ADCC Module and the MCC screen will show the 'Easy Setup' menu. - Check the box for 'Enable ADC'. - Choose 'Basic_mode' for Operating. - Choose 'FOSC/ADCLK' for Clock Source. - Choose 'FOSC/16' for Clock. - Select 'left' as theResult Alignment from the drop-down menu. - All other fields can be left to their default values. UART Module Setup The UART module can be used to communicate with any peripheral to send control signals using the EMG click. Steps are given below to configure UART for the development board for further use. If your application does not use a UART protocol, you can skip this step and replace it with any other protocol you might need. Click on the EUSART Module and the MCC screen will show the 'Easy Setup' menu. - Select 'asynchronous mode' from the drop-down. - Check the box for 'Enable EUSART'. - Check the box for 'Enable Transmit'. - Check the box for 'Enable Receive'. - Set the Baud Rate to '19200'. - Choose '8-bit' for Transmission and Reception. - Check the box for 'Enable EUSART Interrupts'. - Check the box for 'Redirect STDIO to USART'. - Leave Buffer Size as '8' for Transmit and Receive buffers. - All other fields in the 'Registers' tab can be left to their default values. 5 Configure Pin Manager To assign pins on the microcontroller, open the Pin Manager window at the bottom of the screen. To select a pin, click on the corresponding blue unlocked lock button, turning it into a green locked symbol. Ensure the pins look as shown in the picture below: - Choose the 'PDIP40' package from the drop-down menu. - Module ADCC: Click on Analog inputs (ANx) for (Port A – Pin 0) and (Port A – Pin 2) so they turn green. - Module EUSART: Similarly, click on (Port C – Pin 7) for RX and (Port C – Pin 6) for TX. - Pin Module: Click on (Port B – Pin 4) and (Port C – Pin 5) for GPIO Input and (Port A – Pin 7) for GPIO Output. - RESET: Click on (Port E – Pin 3) for MCLR (or leave it if it already shows green and locked). - TMR6: Ensure (Port B – Pin 7) is green for T6IN input. 6 Customize Names for Pins Pin Module Setup To easier understand and program, we can have custom names for the pins on the microcontroller that we intend to observe or control. Click on 'Pin Module' in the 'Project Resources' tab on the left while MCC is open. Rename the pins according to the following diagram. To rename a pin, click on the 'Custom Name' for the pin and type in the new name. Now you can see the names on the Pin Manager: Package View window change as well. 8 Add Signal Processing Module The processing module consists of a total of eight files that you need to copy or move into your project’s working folder. Download the project ZIP file from the "Exercise Files" section of this page and expand the contents. Then move or copy the following files to the working project folder: - peak_filter.c - peak_filter.h - moving_avg_filter.c - moving_avg_filter.h - signal_buffer.c - signal_buffer.h - signal_processing.c - signal_processing.h Follow these steps to copy the files above if you haven’t already done so: - Go back to MPLAB X IDE. Right-click on 'Source Files' in the 'Projects' tab. - Click on ‘Add Existing Item’ from the list. - Navigate to the folder containing the downloaded exercise files and choose peak_filter.c, moving_avg_filter.c, signal_buffer.c, and signal_processing.c. - You have now added the .c source files. - Right-click on the header files and select ‘Add Existing Item’ from the list. - Again, navigate to the folder containing the downloaded exercise files and choose peak_filter.h, moving_avg_filter.h, signal_buffer.h, and signal_processing.h. - The final projects tab will now look like this: 9 Edit main.c The main file needs to be edited to include function calls to the signal processing modules and your custom application. Double-click on the main.c file to open it up in the editor window. a The main.c file requires a few lines to be uncommented for global and peripheral interrupts to work. MCC already has the control commands in the default main.c file, but they are commented out with two forward slashes (//). The forward slashes need to be removed to enable these lines of code. b The following header files are to be included before the main function with the #include directive: #include "mcc_generated_files/mcc.h" #include "peak_filter.h" #include "moving_avg_filter.h" #include "signal_buffer.h" #include "signal_processing.h" #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <math.h> c Some flags need to be defined for event-marking. Please include the following variable declarations after the #include statements: d Sampling of the EMG signal is done every 20 ms using a timer interrupt. Your interrupt handler routine needs to be included next. Include the following code snippet to your main.c file before the main function: e Now we move on to initialize the timer interrupt handler in the main() function. Add the following code to the main function: g We run an infinite loop to continuously check for user-initiated changes. Changes can be made to the mode of control and to start the process with two switches. Add the following code to achieve that functionality: h Another infinite loop is required for the signal processing functions. Add the following code to add that functionality: Analysis You will now have added all files and functionality to your project to begin EMG signal acquisition and subsequent use in embedded applications. You may tailor this project to suit the needs of your specific application. The variable, result, stores the processed real-time EMG data and can be used with any number of routines that store, display, manipulate or use it as a control signal. The variable, count, gives the number of data points present in the signal buffer. The filters used to achieve the signal processing are discussed in the next section. The tutorial above will help you add the module files to your own project. Alternatively, you can download this project from the "Exercise Files" section and choose to build your application on top of it. The following projects are built on top of this module for reference: "Controlling a Motorized Prosthetic Arm using EMG Signals" and "Push-Up Counter Bluetooth Application using EMG Signals". Both of these projects use the UART protocol for embedded control. You may choose to use any other protocol by making the required selections while configuring the MCC before generating code. Results To reference the results obtained by the signal processing module, a comparison is presented below. Given below are the signals before processing, right out of the Analog Out pin of the EMG sensor and the same signals after processing using a peak-to-peak filter and a moving average filter: Conclusions can be drawn from the graphs on the necessity of having a signal processing module for easy, robust and convenient control of the EMG signals. You may make use of the module in any EMG application you see fit.
https://microchipdeveloper.com/projects:emg-signal-processing-for-embedded-applications
CC-MAIN-2019-22
refinedweb
2,395
64.71
the parameter parser allows things like: thorn::param1 = 011 thorn::param2 = 012.34 in parameter files. For floating point values this is a bit unexpected but otherwise mostly harmless. For integers the situation is a bit more complex since in C a leading zero is used to indicate a octal number. And (worse) while the parameter file parser converts the string "011" to the number 11 the Cactus call CCTK_ParameterSet will convert it to 9. The difference is ultimately the difference between calling atof (Parser) and strtol (CCTK_ParameterSet). To avoid confusion it would likely be good to change CCTK_ParameterSet to behave the way the Parameter parser does. This is a change in behaviour compared to the pre-Piraha parser, however I suspect the number of users that actually used octal (or hexedecimal) notation in their parameter files is small. The change is to change inval = strtol (value, &endptr, 0); to inval = strtol (value, &endptr, 10); in line 2209 of src/main/Parameters.c and similar in line 2270. Keyword: postrelease Steve? In principle I agree with Roland, but I could also see you wanting to add octal and hexadecimal support to the parser - just to have it more 'complete'. Which is it for you? :) It turns out that this was fixed in commit 5063, when I switched from using strtol() to operator>>(). I chose the latter because it does more error checking. Interestingly, it also has the effect of reverting Cactus back to the old behavior with regard to leading zeros. This still persists in rev 5066 (just checked). Attached please find a thorn that demonstrates the issue. After digging in to this deeper, it seems the real problem is that Piraha integration was incomplete. Util_ExpressionEvaluate() is still used when expressions are set internally. On line 10, you see Piraha's conversion for "010" which is 10. On line 32, you see the old method's conversion for "010" which is 8. I think what I should do is replace Util_ExpressionEvaluate. Just to be sure, however, the value we want from "010" is 10, right? If I understood it correctly, the current (old) Cactus behavior is to evaluate 010 as octal number. I don't mind one way or another for octal numbers. I cannot think of a reason to use them, other than maybe some unix rights mask, but then we could have some other solution for that. Hexadecimal numbers might be another matter, these are more commonly used in general. Replying to [comment:5 sbrandt]: Piranha parameter parser: * currently parses only parameter files, plan to extent to all ccl files * should use namespace and adhere to Cactus naming and commenting conventions: either use C++ namespace cctk (and cctki?) and/or prefix all externally visible functions by either cctk or cctki depending on whether they should be user callable or not [NOTE: these are lowercase but they should have been uppercase CCTK (RH)] * remove and replace existing math evaluator/parser by piranha one to have uniform math support So I think 2nd point is already handled. All of Piraha is wrapped in the C++ namespace "cctki_piraha". This ticket is essentially about the 3rd point. I think the 1st point should be its own ticket. OK, this is long overdue, but I replaced the expression evaluator with Piraha. One new feature, which I can take out if no one likes it, is that you can set temporaries in an evaluation. Thus, if you do this: You'll get "result=19." See the patch. What "namespace" are the temporaries set in? Can codes create their own space to avoid conflicts with existing temporaries? Out of caution, I would comment out or otherwise disable the setting of temporaries using the flesh expression parser in case it causes problems. It could then be enabled if people need the feature and it is worth the risk of confusion. This patch introduces a new type "sval", I assume for string valued expressions. Existing code will not check exhaustively for the type of the expression. I doubt this is a problem in practice, as the expression parser code is rarely used outside the flesh I think. There is a switch statement at the top of the patch which does not have a default case. Please add a fatal error message here. Do I understand correctly that you are replacing the Util_Expression* flesh API with a different API? Doesn't this break backward compatibility? Should there be a wrapper introduced? Then the changes to Groups.c and Parameters.c would not be needed. I support replacing the expression parser with Piraha, but I don't think we should change/eliminate the Util_* expression API. Did I misunderstand what the patch was doing? Sorry for not responding to this sooner: (1) The ability to set variables (e.g. symbols preceded by $) can easily be removed. (2) I added sval for completeness. Someone might want to evaluate a string par. (3) I can add the default check. (4) The API still looks basically the same, only the implementation changed. It passes the test suite last I checked. The goal was to remove subtle behavioral differences between expression evaluation and parameter parsing. As far as I can see in the patch, the function Util_ExpressionParse has been removed. Is this correct? I consider this a change to the API, because code which calls this function will have to be changed. I had assumed that this function was documented and an official part of the flesh API, rather than an internal function, since it has a Util_ prefix rather than CCTKi_. However, I now see that it is not documented (). I suspect that it is considered by most Cactus developers to be part of the flesh API, and should have been documented. Since it is callable from user code, I don't think it should be removed. Instead, the API should be maintained, and should call the new code underneath. I said "basically the same." Since nothing in the ET test suite called it, and (as you pointed out) the docs don't mention it I figured it wasn't used, and open to some modification. The above function (cctk_PirahaEval), does essentially the same thing, but returns a uExpressionValue rather than a uExpression. I imagined a value would be more useful since the uExpression contains internal things like tokens and token counts. Of course, I could always rename cctk_PirahaEval as Util_ExpressionParse, but since the return value changed I thought it might make sense to change the name. Do you have a thorn and test case that uses this function? No, I don't. The ET tests are not exhaustive, and while they are useful for detecting some problems, they should not be used as evidence that something should not be supported. Cactus is a framework; the Einstein Toolkit is just one user of that framework. Many people use the Cactus flesh with thorns which are not in the Einstein Toolkit. Just because something is not used in the toolkit, it doesn't mean it can be changed or removed. If we want to remove the Util_Expression API, we should discuss this first, weighing up the pros and cons, evaluating how likely it is that people will be affected, announcing the change well in advance (e.g. at least one release), and getting a consensus from the Cactus developers that this is a good idea. It's possible that nobody uses it; it is, after all, a rather obscure feature. But the Cactus flesh has a large number of users, and a decision like this should not be taken lightly. Would you like to propose that this flesh API is changed, and give arguments for why this is good and/or OK? My own preference would be to implement the old functionality (down to the return types and semantics) in terms of the new, or to provide a new API in addition to the old one, deprecating the old one, if wrapping the new API with the old is not considered feasible. This a regression, yes? Should it be noted in the release notes as such? I'm not sure what you mean by a regression. AFAIK, there is no test that identifies the problems discussed in this ticket. Probably something should be added.: In this case, it used to work, and now it doesn't. We have "regression tests" to catch regressions, but the word "regression" is not limited to whether the code is tested. If we know that something has broken in this release that worked before, then yes, it needs to be mentioned in the release notes. We should put the word "regression" into the ticket keywords when a ticket is associated with a regression so that we can search for them when writing the release notes. Uh, actually I think I should have remained silent. The possibility of encountering this low, since the original code was the one that would have allowed octal numbers ie 011octal = 9decimal. I would expect that not many users were using octal numbers in there parfiles. I confess that once I realized there were two distinct parsers in the system, that became the focus of the ticket for me. I actually forgot all about the octal conversion and whether it was desirable. Adding the octal conversion would be easy enough to do. My comment about the regression was simply that it doesn't break an existing software regression test, and so it seemed odd to me to call it a regression. I was wondering if I was missing something. Please review. The latest patch is "expressions.2.patch" in comment 16. I can only review code style and some general stuff since I do not actually understand what the Piraha parser does. line 2312 ff: 2312 int n=0; 2313 while(temp[n] != 0) 2314 n++; is just a strlen. So strlen should be used. Since the intend seems to be to try and avoid calling strlen() after each iteration, the most convenient way may be: for (unsigned int p = 0, n = strlen(temp); p < n; p++) the way eg Carpet caches the end() iterator for C++ style iterations. * there's a number of commented out lines that should not be committed (eg line 2845 of src/main/Groups.c, line 2223 of src/main/Parameters.c) * src/piraha/Makefile seems to hard-code compiler options for -O2 and -g. This should not be. * the patch redefine Util_StrCmpi. I don't understand why this is done. If actually required, I think it should be done in a separate commit. We may not even need Util_StrCmpi anymore since POSIX.1-2001 and we could officially add POSIX.1-2001 to Cactus' requirements. While we are discussing style questions -- strlenreturns size_t, not unsigned int. Yes, we should replace Util_StrCmpiby strcasecmp. In fact, we should make the former be just a wrapper around the latter. I should have added that with the exceptions of the points raised above, the patch is fine to apply. There may be more of the "unsigned int" issues around, since the type is already in the files (originating from sometime around 2001, where I suspect size_t was indeed the same as unsigned int).
https://bitbucket.org/einsteintoolkit/tickets/issues/1518/replace-internal-expression-parser-with
CC-MAIN-2021-31
refinedweb
1,871
65.32
New MathWorks Tools Posted by Sean de Wolski, Sean‘s pick this week is to revisit three prior Picks of the Week. While reading through the 2017 review and reviews for the previous years, I saw a few picks where MathWorks has now incorporated similar functionality into the product. Contents Extract Text from PDF Documents Jiro’s original pick is here:. This functionality was added in the Text Analytics Toolbox, released in R2017b. The function to use is extractFileText. Note that this is a generic text reading function that can read from PDF, Microsoft Word, or text files. Here, I’ll read the second page of the 2017 Pick of the Week index exported to pdf. txt = extractFileText('2017review.pdf', 'Pages', 3); lines = splitlines(txt); lines(strlength(lines) > 0) ans = 46×1 string array "1/3/2018 Looking back: 2017 in review » File Exchange Pick of the Week" " 3/5" "Deep Learning Tutorial Series" "Johanna Pingel" "Download code and watch video series to learn and implement deep learning techniques" "__________________________________________________________________________" "Process Manager" "Brian Lau" "Matlab class for launching and managing asynchronous processes" "__________________________________________________________________________" "CatStruct" "Jos (10584)" "Concatenate/merge structures (v4.1, feb 2015)." "__________________________________________________________________________" "Source Control Information Block" "Gavin Walker" "Display Simulink project source control information in the Simulink editor" "__________________________________________________________________________" "CNN for Old Japanese Character Classification" "Akira Agata" "Create Simple Deep Learning Network for Old Japanese Character Classification" "__________________________________________________________________________" "Fidget Spinner (Simscape Multibody)" "Pavel Roslovets" "3DOF gyro psysical model of fidger spinner" "__________________________________________________________________________" "Signature Tool" "McSCert" "The Signature Tool extracts the interface of a Simulink subsystem." "__________________________________________________________________________" "“Read text from a PDF document”" "Derek Wood" "Read the text from a simple PDF document into MATLAB as a string" "__________________________________________________________________________" "Real-Time Pacer for Simulink" "Gautam Vallabha" "Simulink block for forcing a simulation to run in real (wall clock) time" "__________________________________________________________________________" "impressionism" "David Mills" "impressionism takes an RGB image and “paints” it as though it were an impressionist painting." "__________________________________________________________________________" "OOP example" "per isakson" "tracer4m traces calls to methods and functions." "__________________________________________________________________________" Base 64 Encoding Jiro’s original pick is here: We were unaware that this was added as part of the HTTP interface in R2016b. The functions to use are matlab.net.base64encode and matlab.net.base64decode to encode and decode images. Here I will encode and decode an image of two cars on my desk. import matlab.net.* I = imread('lambos.jpg'); base64 = base64encode(I(:)); cars = base64decode(base64); imshow(reshape(cars, size(I))) Word Cloud My original pick is here:. This capability was added to MATLAB in R2017b as the wordcloud function. The Text Analytics Toolbox further enhances it and provides other ways to display text as well. Let’s see the word cloud of the Pick of the Week review. txt = extractFileText('2017review.pdf'); wordcloud(txt); It makes me happy to see “Cannibals” in there! Give the MathWorks versions a try and let us know what you think here. Published with MATLAB® R2018a To leave a comment, please click here to sign in to your MathWorks Account or create a new one.
https://blogs.mathworks.com/pick/2018/02/02/new-mathworks-tools/
CC-MAIN-2019-47
refinedweb
505
59.94
[Blog Blog public delegate int ChangeInt(int x); // Define a method to which the delegate can point static. Using an Anonymous Method With C# 2.0, anonymous methods allow you to write a method and initialize a delegate in place: ChangeInt myDelegate = new ChangeInt( delegate(int x) { return x * 2; } ); Console.WriteLine(“{0}”, myDelegate(5)); Using a Lambda Expression)); Using a Lambda with Two Arguments)); Statement Lambda Expressions. Lambda Expressions that Return Void public public delegate void OutputHelloToConsole(); static void Main(string[] args) { OutputHelloToConsole o = () => { Console.WriteLine(“Hello, World”); }; o(); } The Func Delegate Types Action Delegate Types”); }); } } Expression Trees Lambda expressions can also be used as expression trees. This is an interesting topic, but is not part of this discussion on writing pure functional transformations. [Blog Map] [Table of Contents] [Next Topic] … 🙂# 🙂 ?" 😉 ‘statement lambdas’ is ‘blocks’. ‘P’ 🙂 I generally pronounce "=>" as "goes to", but I also like "maps to" and "evaluates to". @chadmyers: Remind me never to involve myself in any Ruby circles. 😛 @chadmyers, the post on closures is now written: -Eric If you are using Linq to SQL, instead of writing regular Linq Queries, you should be using Compiled Queries. 🙂.)); Thanks. Thanks Al true;? -Eric ‘lazy’. ‘materialize’ the paragraphs I’m interested in, and contents of the paragraphs into a List<T>. Then subsequent iterations are over the much shorter List<T> instead of over the whole document. -Eric? Thanks for the very clear explanation! What I am additionally looking for is the c# specification that explains why the following code, taken from your example above, works: static List<T> MyWhereMethod<T>(IEnumerable<T> source, Func<T, bool> predicate) {…} … int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; List<int> filteredList = MyWhereMethod(source, i => i >= 5); How does the resolving work for the function-call with signature List<int> MyWhereMethod(IEnumerable<int>, Func<T, bool>)? There isn’t such a signature in this namespace, at least not literally. Contrary to my expectations the compiler apparently is smarter than I thought and resolves to the given MyWhereMethod<T>. Why is that? @Benjamin, The syntax that you’re asking about is how you write an anonymous method in C# 2.0. Because ChangeInt takes a delegate as an argument, it is valid to use the delegate keyword to write an anonymous method in-line, and pass it to the method. Lambda expressions are simply more terse syntax for writing an anonymous method. @Carl, This works because of the type inference that comes into play with generic methods. (Generic methods are those that are defined with a type parameter, i.e. List<T> MyWhereMethod<T>(IEnumerable<T> source, Func<T, bool> predicate). Type inference for generic methods is defined in section 7.4.2 of the C# 3.0 specification. The C# compiler goes through a specific set of steps when determining which method can bind to a method call, and which binding will have the highest priority, and will get the binding. Because the name is MyWhereMethod in the method call, and that is the name of the method, that method call will go through the type inference algorithm to decide whether the compiler can bind to the generic method. The first step in deciding whether the compiler can bind to the method is to infer the type of the generic parameter. The source argument is an array of integer, which implements IEnumerable<int>, so the compiler can infer the type of int for T, and see if the method binds properly. It then infers the type of i in the lambda expression as int, and infers the return type of List<int>, which exactly matches the value to the left of the equals sign. When the compiler infers T as int, because everything compiles properly, the compiler can then bind the method call to the generic method. -Eric Thanks for trying to explain, though this confuses me. You wrote: "Because ChangeInt takes a delegate as an argument". But I see that it takes an int, named x: public delegate int ChangeInt(int x); As far as I understand, you have a delegate named ChangeInt, to which you pass yet another delegate, that has a anonymous method: ChangeInt myDelegate = new ChangeInt(delegate(int x) { return x * 2; } What does "initialize a delegate in place" mean? I thought you already defined a delegate (ChangeInt) and initialized it with this line: new ChangeInt. Hi Benjamin, Sorry, I didn’t take the proper time to write the last answer. Here is how this works: // the following is the *definition* of a delegate type public delegate int ChangeInt(int x); // the following is a *declaration* of a delegate ChangeInt myDelegate = new ChangeInt( delegate(int x) { return x * 2; } ); In a declaration, when newing up the instance of a delegate, you can pass the name of a method that has the correct signature, which is how the example immediately preceding the one that we’re discussing works. Or when newing up the instance of a delegate, you can write an anonymous method right there, in place. This uses the delegate keyword, where you declare the types of the arguments and the body of the method immediately following ‘delegate’. Does that make sense? -Eric I think I do. In the second example there is not yet a definition of a delegate, but you make one with ChangeInt myDelegate = new ChangeInt(delegate(int x) {return x * 2;}); If that’s correct, than I understand. Thank you very much for taking the time Eric! While fiddling with code, I noticed you can also write this: public delegate int ChangeInt(int x); ChangeInt myDelegate = delegate(int x) { return x * 2; };} It produces the same output, no errors. Is there any difference between the two? Hi Benjamin, No, there is no difference between the two. The compiler can initialize the delegate with the anonymous method that you create with the delegate keyword. This is similar to code that you could write like this: ChangeInt myDelegate = (int x) => { return x * 2; }; or ChangeInt myDelegate => x => x * 2; For what its worth, I never use the delegate keyword, as you can always use the lambda expression syntax. After you become accustomed to lambda expression syntax, it becomes more natural, in my opinion. -Eric Excellent article! You made it so easy to understand. Thank you so much! Thanks Eric for the Nice Article. Thanks for the article, it helped clear a few things up for me! I have a question though and I may be completely missing something here, but take the following code from the article: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where(x => x > 5)) Console.WriteLine(i); Is there an advantage to using Lambda to extract data from the array rather than LINQ? Hi Andrew, Query expressions are directly translated to equivalent expressions using lambda expressions. The nomenclature is that when you express them using lambda expressions, they are written in ‘method syntax’. For example, another way to write the query that you referred to is like this: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; var q = source.Where(x => x > 5); foreach (int i in q) Console.WriteLine(i); This is exactly the same as if you write this: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; var q = from x in source where x > 5 select x; foreach (int i in q) Console.WriteLine(i); The second form is translated to the first by the compiler. I’ve written a few things that discuss this: For what it’s worth, I have gravitated completely to using ‘method syntax’. There are queries that you can write in method syntax that you can’t write using query expressions, but the reverse is not true, so I personally find it more convenient to consistently use method syntax. -Eric Thanks a lot EricWhite for your efforts. Your tutorial is so simple yet so authoritative. Its a breeze to learn lambadas/FP through your tutorial(s). Would you care to write some day on Expression trees using lambadas as mentioned. In the mean time can you suggest some resources which are as good as yours for learning Expression trees through FP. -Panks Hi Panks, I’m glad it’s useful. The SharePoint 2010 managed client side object model (CSOM) includes an interesting use of lambda expressions that are processed by expression trees. I’m planning on writing a blog post/MSDN article that explains that use of lambda expressions. It would be fun to also write a more general explanation of expression trees. -Eric I loved reading this. Now I know lambda. Thanks everyone Really good article to understand Lamda Expression @Eric: Brilliant Article Although I have a question: AS if can you please let me know ,wat are the scenarios where we should use each of the following : anonymous delegates vs. functional calls vs. lambda expression to optimize the performance of the application. What is the advantage of LAMBDA Expression over standard SQL I see what it does but I really don't know why we are all still coding? 30 years on and the code gets more complex to do the same old things. One day someone will design th "codeless development system" Interesting article though, I will need to put some in a project now as it won't be fashionable if you don't put the latest techy stuff in(just kidding) P Cheers Hi, I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of lambda expression in c# and it will help me a lot. This link……/Lambda%20Expression%20in%20c I have found another nice post over internet. It is also helpful to complete my task. Thank you very much!. dabbu-csharphelp.blogspot.in/…/lambda-expression.html I hope this blog is also useful to those users who wants to know about lambda expressio that how to find records from list using lambda expression. thanks to sharing this useful article. Lambda expressions take the relatively simply, and add a layer of complexity. They offer nothing that cannot be done in a simpler, more direct way. The emperor is naked. The code containing the "lambda expression": int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; var q = source.Where(x => x > 5); foreach (int i in q) Console.WriteLine(i); Is the same as: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source) if (i > 5) Console.WriteLine(i); Which is simpler? Which executes more quickly? Exactly. Sometimes, simpler is better. Especially when it comes to maintaining a huge code base. "Cool" does not equal "better" in the real world. Good to see that such type of articles are there for us(The beginers) 🙂
https://blogs.msdn.microsoft.com/ericwhite/2006/10/03/lambda-expressions/
CC-MAIN-2016-50
refinedweb
1,832
62.78
8.32: Drawing a Box on the Board or Elsewhere on the Screen - Page ID - 14608 def drawBox(boxx, boxy, color, pixelx=None, pixely=None): # draw a single box (each tetromino piece has four boxes) # at xy coordinates on the board. Or, if pixelx & pixely # are specified, draw to the pixel coordinates stored in # pixelx & pixely (this is used for the "Next" piece). if color == BLANK: return if pixelx == None and pixely == None: pixelx, pixely = convertToPixelCoords(boxx, boxy) pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx + 1, pixely + 1, BOXSIZE - 1, BOXSIZE - 1)) pygame.draw.rect(DISPLAYSURF, LIGHTCOLORS[color], (pixelx + 1, pixely + 1, BOXSIZE - 4, BOXSIZE - 4)) The drawBox() function draws a single box on the screen. The function can receive boxx and boxy parameters for board coordinates where the box should be drawn. However, if the pixelx and pixely parameters are specified, then these pixel coordinates will override the boxx and boxy parameters. The pixelx and pixely parameters are used to draw the boxes of the "Next" piece, which is not on the board. If the pixelx and pixely parameters are not set, then they will be set to None by default when the function first begins. Then the if statement on line 8 [450] will overwrite the None values with the return values from convertToPixelCoords(). This call gets the pixel coordinates of the board coordinates specified by boxx and boxy. The code won’t fill the entire box’s space with color. To have a black outline in between the boxes of a piece, the left and top parameters in the pygame.draw.rect() call have + 1 added to them and a - 1 is added to the width and height parameters. In order to draw the highlighted box, first the box is drawn with the darker color on line 10 [452]. Then, a slightly smaller box is drawn on top of the darker box on line 11 [453].
https://eng.libretexts.org/Bookshelves/Computer_Science/Book%3A_Making_Games_with_Python_and_Pygame_(Sweigart)/08%3A_Tetromino/8.32%3A_Drawing_a_Box_on_the_Board_or_Elsewhere_on_the_Screen
CC-MAIN-2021-21
refinedweb
319
60.75
Talk:C++ Programming/Q&A Welcome to the C++ Programming questions and answers page. Feel free to post any questions you have while learning to program in C++. If you have questions about this book, post them on the C++ Programming content discussion page. If you know the answer to a question, or you can improve any, go ahead and do it. After a response is given and the information is missing in the book, please add it and delete the post. (give at least 7 days after the reply, no archive is needed to be maintained of this page). You may also be interested on the material regarding this subject at Wikiversity. Contents how to move a text up and down using keys?[edit] how to move a text up and down using keys? You have to intercept the pressing of the keys, see the book example on how to get input from the keyboard and adapt it to detect those key presses, if you don't know the code for a particular key, print it to the screen after you have read it. if you think the example on how to get the keyboard data is missing something please ask again, please do sign you posts txs --Panic 14:41, 7 January 2007 (UTC) string::find return type[edit] Which one is right? string::find()returns an int? -- old version of C++ Programming/Code/IO/Streams/string; but the compiler I'm using today tells me "warning: comparison between signed and unsigned integer expressions". string::find()returns a size_type? -- SGI reference; but the compiler I'm using today keeps telling me "error: 'size_type' was not declared in this scope". string::find()returns a size_t? -- another C++ reference; this seems to compile -- on this ancient compiler I'm using today. But is it portable? --DavidCary (talk) 02:32, 16 March 2009 (UTC) - What compiler are you using? size_typeis the correct one, by what is on the 2003 standard. - Use string::size_type return = yourstring.find( <what you need to find> );and the "error: 'size_type' was not declared in this scope" should be solved. --Panic (talk) 19:06, 16 March 2009 (UTC) - Ah, that makes sense. Now my compiler accepts it. So actually string::find()returns a string::size_type - right? --DavidCary (talk) 04:04, 18 March 2009 (UTC) - Well the correct terminology is that the type is size_type, the string::bit is the namespace/scope were the compiler can find a definition for it, in general a type can be the same or different across several namespaces/scopes sharing the same keyword, in this case it also exists in other namespaces/scope (ie vector::size_type) and from your previous searches it seems that some time back it was a int. - For what is on the standard (2003) the size_type is implementation dependent and size_t will (with a high degree of certainty) be equal to size_type (but the standard doesn't commit to it and I couldn't find a clear reason why...) --Panic (talk) 04:44, 18 March 2009 (UTC) - Thank you. OK, I've updated C++ Programming/Code/IO/Streams/string based on the new understanding you've given me. As always, feel free to improve that page, even if it means reverting my mis-guided edits. --DavidCary (talk) 13:58, 24 March 2009 (UTC) mathematical operations[edit] a c++ programe that can display mathematical operations. - No major problem, the only difficulty would be the output but that depends only on how much it needed to conform with the standard notation. You could output a TeX formula and render it elsewhere. --Panic (talk) 19:50, 18 May 2009 (UTC) Ejecting optical drive[edit] How to eject optical drive using c++ code on turbo c++ 3.0 compiler without using any windows library or header file? - Only possibility is to call another program that executes that task. That operation is dependant on the OS. --Panic (discuss • contribs) 22:09, 28 April 2011 (UTC) MATALAB?[edit] How does C++ compare with MATALAB? When should one use C++ instead of MATLAB? When is C++ superior to MATLAB? When is MATLAB superior to C++? - That is a bit like discussing what the differences are between oranges and apples, even more problematic since the analogy is even closer since both are fruits. - C++ is a programming language MATLAB is not even if it is scriptable the functions or objectives rarely are the same (MATLAB can be used to examine algorithms). Since they really can't be directly compared (unless we define a specific problem that can be addressed by both) the comparison has no meaning in generic terms, each does what it they are proposed to do. Also consider that MATLAB is a commercial product there is some fairly recent products that already replicate some functionalities of that software package in the case of programming languages there is no direct concurrency, there is only one C++ language even if some other languages can perform the same tasks they are ultimately completely distinct in use, capabilities and results (see the book section that compares C++ with similar languages if you need further info on that). --Panic (discuss • contribs) 08:39, 1 June 2011 (UTC) WHAT IS IDE SOFTWARE?[edit] WHAT IS IDE SOFTWARE? - Your answer is in the book section about the compiler. --Panic (discuss • contribs) 12:52, 2 January 2012 (UTC) c++ programming logical[edit] A=9,B=9 why C=A!=B+1+(A==B) get the result C=0 ? —Preceding unsigned comment added by 111.118.129.179 (discuss • contribs) some time before 09:43, 4 February 2012 (UTC) - Go by steps and check operator resolution priority on the table. In any case doing a such logic in a single operation like that is bad coding practice, you can extend it into several operations unless compiler optimization is needs to be turned off, in that case you should provide an appropriate comment. --Panic (discuss • contribs) 09:44, 4 February 2012 (UTC) Programming terms[edit] hello there, I don't know anything about programming c++, but i ran on these words and would like to know what they are or how to get them: can you help pls? - - initial interface - - data loggin - - polling system - - object inspector - - gage component thanks a lot —Preceding unsigned comment by Elzeinhasan (discuss • contribs) added before 3:24, 7 November 2013 (UTC) - This have no specific relation to C++, even if they can be declared as terms used in programming. All depend on the context they are used so it would be mostly guessing to what they mean as listed above. - An interface can be many things but lets assume it refers to classes, in that case the initial interface may be indicating the parent class interface before derivation. - Data logging relates to keeping "data" for review (a log). - Polling system may be something like detecting if a system is active (for instance in dealing with threads) or in networks it can also be referring to deciding a priority by a vote (see distributed systems). - Object inspector is just like it states, you should learn more about Object Oriented Programming first. - The gage component can be so many things that I will not conjecture about it. - Programming is hard, it is not only understanding a language but knowing what can be done with it, understanding all the intrinsics of a language. Knowing the code is even less important that fully understanding the concepts behind how and why things are implemented as they are. If you understand those, every language will become very similar to you, as they ultimately share the same basic functional purpose. --Panic (discuss • contribs) 19:11, 2 May 2012 (UTC) C++[edit] What is the difference between call by value and call by reference - Please use the search function before asking a question. That subject is fully covered in Function Parameters. --Panic (discuss • contribs) 23:23, 29 July 2013 (UTC)
http://en.wikibooks.org/wiki/C%2B%2B_Programming/Q%26A
CC-MAIN-2013-48
refinedweb
1,323
61.36